babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. /**
  64. * Returns the log2 of value.
  65. */
  66. MathTools.Log2 = function (value) {
  67. return Math.log(value) * Math.LOG2E;
  68. };
  69. return MathTools;
  70. }());
  71. BABYLON.MathTools = MathTools;
  72. var Scalar = (function () {
  73. function Scalar() {
  74. }
  75. /**
  76. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  77. */
  78. Scalar.Lerp = function (start, end, amount) {
  79. return start + ((end - start) * amount);
  80. };
  81. /**
  82. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  83. */
  84. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  85. var squared = amount * amount;
  86. var cubed = amount * squared;
  87. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  88. var part2 = (-2.0 * cubed) + (3.0 * squared);
  89. var part3 = (cubed - (2.0 * squared)) + amount;
  90. var part4 = cubed - squared;
  91. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  92. };
  93. return Scalar;
  94. }());
  95. BABYLON.Scalar = Scalar;
  96. var Color3 = (function () {
  97. /**
  98. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  99. */
  100. function Color3(r, g, b) {
  101. if (r === void 0) { r = 0; }
  102. if (g === void 0) { g = 0; }
  103. if (b === void 0) { b = 0; }
  104. this.r = r;
  105. this.g = g;
  106. this.b = b;
  107. }
  108. /**
  109. * Returns a string with the Color3 current values.
  110. */
  111. Color3.prototype.toString = function () {
  112. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  113. };
  114. /**
  115. * Returns the string "Color3".
  116. */
  117. Color3.prototype.getClassName = function () {
  118. return "Color3";
  119. };
  120. /**
  121. * Returns the Color3 hash code.
  122. */
  123. Color3.prototype.getHashCode = function () {
  124. var hash = this.r || 0;
  125. hash = (hash * 397) ^ (this.g || 0);
  126. hash = (hash * 397) ^ (this.b || 0);
  127. return hash;
  128. };
  129. // Operators
  130. /**
  131. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  132. * Returns the Color3.
  133. */
  134. Color3.prototype.toArray = function (array, index) {
  135. if (index === undefined) {
  136. index = 0;
  137. }
  138. array[index] = this.r;
  139. array[index + 1] = this.g;
  140. array[index + 2] = this.b;
  141. return this;
  142. };
  143. /**
  144. * Returns a new Color4 object from the current Color3 and the passed alpha.
  145. */
  146. Color3.prototype.toColor4 = function (alpha) {
  147. if (alpha === void 0) { alpha = 1; }
  148. return new Color4(this.r, this.g, this.b, alpha);
  149. };
  150. /**
  151. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  152. */
  153. Color3.prototype.asArray = function () {
  154. var result = [];
  155. this.toArray(result, 0);
  156. return result;
  157. };
  158. /**
  159. * Returns the luminance value (float).
  160. */
  161. Color3.prototype.toLuminance = function () {
  162. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  163. };
  164. /**
  165. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  166. * Returns this new object.
  167. */
  168. Color3.prototype.multiply = function (otherColor) {
  169. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  170. };
  171. /**
  172. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  173. * Returns the current Color3.
  174. */
  175. Color3.prototype.multiplyToRef = function (otherColor, result) {
  176. result.r = this.r * otherColor.r;
  177. result.g = this.g * otherColor.g;
  178. result.b = this.b * otherColor.b;
  179. return this;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equals = function (otherColor) {
  185. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  186. };
  187. /**
  188. * Boolean : True if the rgb values are equal to the passed ones.
  189. */
  190. Color3.prototype.equalsFloats = function (r, g, b) {
  191. return this.r === r && this.g === g && this.b === b;
  192. };
  193. /**
  194. * Multiplies in place each rgb value by scale.
  195. * Returns the updated Color3.
  196. */
  197. Color3.prototype.scale = function (scale) {
  198. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  199. };
  200. /**
  201. * Multiplies the rgb values by scale and stores the result into "result".
  202. * Returns the unmodified current Color3.
  203. */
  204. Color3.prototype.scaleToRef = function (scale, result) {
  205. result.r = this.r * scale;
  206. result.g = this.g * scale;
  207. result.b = this.b * scale;
  208. return this;
  209. };
  210. /**
  211. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  212. */
  213. Color3.prototype.add = function (otherColor) {
  214. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  215. };
  216. /**
  217. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  218. * Returns the unmodified current Color3.
  219. */
  220. Color3.prototype.addToRef = function (otherColor, result) {
  221. result.r = this.r + otherColor.r;
  222. result.g = this.g + otherColor.g;
  223. result.b = this.b + otherColor.b;
  224. return this;
  225. };
  226. /**
  227. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  228. */
  229. Color3.prototype.subtract = function (otherColor) {
  230. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  231. };
  232. /**
  233. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  234. * Returns the unmodified current Color3.
  235. */
  236. Color3.prototype.subtractToRef = function (otherColor, result) {
  237. result.r = this.r - otherColor.r;
  238. result.g = this.g - otherColor.g;
  239. result.b = this.b - otherColor.b;
  240. return this;
  241. };
  242. /**
  243. * Returns a new Color3 copied the current one.
  244. */
  245. Color3.prototype.clone = function () {
  246. return new Color3(this.r, this.g, this.b);
  247. };
  248. /**
  249. * Copies the rgb values from the source in the current Color3.
  250. * Returns the updated Color3.
  251. */
  252. Color3.prototype.copyFrom = function (source) {
  253. this.r = source.r;
  254. this.g = source.g;
  255. this.b = source.b;
  256. return this;
  257. };
  258. /**
  259. * Updates the Color3 rgb values from the passed floats.
  260. * Returns the Color3.
  261. */
  262. Color3.prototype.copyFromFloats = function (r, g, b) {
  263. this.r = r;
  264. this.g = g;
  265. this.b = b;
  266. return this;
  267. };
  268. /**
  269. * Updates the Color3 rgb values from the passed floats.
  270. * Returns the Color3.
  271. */
  272. Color3.prototype.set = function (r, g, b) {
  273. return this.copyFromFloats(r, g, b);
  274. };
  275. /**
  276. * Returns the Color3 hexadecimal code as a string.
  277. */
  278. Color3.prototype.toHexString = function () {
  279. var intR = (this.r * 255) | 0;
  280. var intG = (this.g * 255) | 0;
  281. var intB = (this.b * 255) | 0;
  282. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  283. };
  284. /**
  285. * Returns a new Color3 converted to linear space.
  286. */
  287. Color3.prototype.toLinearSpace = function () {
  288. var convertedColor = new Color3();
  289. this.toLinearSpaceToRef(convertedColor);
  290. return convertedColor;
  291. };
  292. /**
  293. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  294. * Returns the unmodified Color3.
  295. */
  296. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  297. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  298. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  299. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  300. return this;
  301. };
  302. /**
  303. * Returns a new Color3 converted to gamma space.
  304. */
  305. Color3.prototype.toGammaSpace = function () {
  306. var convertedColor = new Color3();
  307. this.toGammaSpaceToRef(convertedColor);
  308. return convertedColor;
  309. };
  310. /**
  311. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  312. * Returns the unmodified Color3.
  313. */
  314. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  315. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  316. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  317. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  318. return this;
  319. };
  320. // Statics
  321. /**
  322. * Creates a new Color3 from the string containing valid hexadecimal values.
  323. */
  324. Color3.FromHexString = function (hex) {
  325. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  326. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  327. return new Color3(0, 0, 0);
  328. }
  329. var r = parseInt(hex.substring(1, 3), 16);
  330. var g = parseInt(hex.substring(3, 5), 16);
  331. var b = parseInt(hex.substring(5, 7), 16);
  332. return Color3.FromInts(r, g, b);
  333. };
  334. /**
  335. * Creates a new Vector3 from the startind index of the passed array.
  336. */
  337. Color3.FromArray = function (array, offset) {
  338. if (offset === void 0) { offset = 0; }
  339. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  340. };
  341. /**
  342. * Creates a new Color3 from integer values ( < 256).
  343. */
  344. Color3.FromInts = function (r, g, b) {
  345. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  346. };
  347. /**
  348. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  349. */
  350. Color3.Lerp = function (start, end, amount) {
  351. var r = start.r + ((end.r - start.r) * amount);
  352. var g = start.g + ((end.g - start.g) * amount);
  353. var b = start.b + ((end.b - start.b) * amount);
  354. return new Color3(r, g, b);
  355. };
  356. Color3.Red = function () { return new Color3(1, 0, 0); };
  357. Color3.Green = function () { return new Color3(0, 1, 0); };
  358. Color3.Blue = function () { return new Color3(0, 0, 1); };
  359. Color3.Black = function () { return new Color3(0, 0, 0); };
  360. Color3.White = function () { return new Color3(1, 1, 1); };
  361. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  362. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  363. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  364. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  365. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  366. return Color3;
  367. }());
  368. BABYLON.Color3 = Color3;
  369. var Color4 = (function () {
  370. /**
  371. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  372. */
  373. function Color4(r, g, b, a) {
  374. this.r = r;
  375. this.g = g;
  376. this.b = b;
  377. this.a = a;
  378. }
  379. // Operators
  380. /**
  381. * Adds in place the passed Color4 values to the current Color4.
  382. * Returns the updated Color4.
  383. */
  384. Color4.prototype.addInPlace = function (right) {
  385. this.r += right.r;
  386. this.g += right.g;
  387. this.b += right.b;
  388. this.a += right.a;
  389. return this;
  390. };
  391. /**
  392. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  393. */
  394. Color4.prototype.asArray = function () {
  395. var result = [];
  396. this.toArray(result, 0);
  397. return result;
  398. };
  399. /**
  400. * Stores from the starting index in the passed array the Color4 successive values.
  401. * Returns the Color4.
  402. */
  403. Color4.prototype.toArray = function (array, index) {
  404. if (index === undefined) {
  405. index = 0;
  406. }
  407. array[index] = this.r;
  408. array[index + 1] = this.g;
  409. array[index + 2] = this.b;
  410. array[index + 3] = this.a;
  411. return this;
  412. };
  413. /**
  414. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  415. */
  416. Color4.prototype.add = function (right) {
  417. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  418. };
  419. /**
  420. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  421. */
  422. Color4.prototype.subtract = function (right) {
  423. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  424. };
  425. /**
  426. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  427. * Returns the Color4.
  428. */
  429. Color4.prototype.subtractToRef = function (right, result) {
  430. result.r = this.r - right.r;
  431. result.g = this.g - right.g;
  432. result.b = this.b - right.b;
  433. result.a = this.a - right.a;
  434. return this;
  435. };
  436. /**
  437. * Creates a new Color4 with the current Color4 values multiplied by scale.
  438. */
  439. Color4.prototype.scale = function (scale) {
  440. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  441. };
  442. /**
  443. * Multiplies the current Color4 values by scale and stores the result in "result".
  444. * Returns the Color4.
  445. */
  446. Color4.prototype.scaleToRef = function (scale, result) {
  447. result.r = this.r * scale;
  448. result.g = this.g * scale;
  449. result.b = this.b * scale;
  450. result.a = this.a * scale;
  451. return this;
  452. };
  453. /**
  454. * Multipy an RGBA Color4 value by another and return a new Color4 object
  455. * @param color The Color4 (RGBA) value to multiply by
  456. * @returns A new Color4.
  457. */
  458. Color4.prototype.multiply = function (color) {
  459. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  460. };
  461. /**
  462. * Multipy an RGBA Color4 value by another and push the result in a reference value
  463. * @param color The Color4 (RGBA) value to multiply by
  464. * @param result The Color4 (RGBA) to fill the result in
  465. * @returns the result Color4.
  466. */
  467. Color4.prototype.multiplyToRef = function (color, result) {
  468. result.r = this.r * color.r;
  469. result.g = this.g * color.g;
  470. result.b = this.b * color.b;
  471. result.a = this.a * color.a;
  472. return result;
  473. };
  474. /**
  475. * Returns a string with the Color4 values.
  476. */
  477. Color4.prototype.toString = function () {
  478. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  479. };
  480. /**
  481. * Returns the string "Color4"
  482. */
  483. Color4.prototype.getClassName = function () {
  484. return "Color4";
  485. };
  486. /**
  487. * Return the Color4 hash code as a number.
  488. */
  489. Color4.prototype.getHashCode = function () {
  490. var hash = this.r || 0;
  491. hash = (hash * 397) ^ (this.g || 0);
  492. hash = (hash * 397) ^ (this.b || 0);
  493. hash = (hash * 397) ^ (this.a || 0);
  494. return hash;
  495. };
  496. /**
  497. * Creates a new Color4 copied from the current one.
  498. */
  499. Color4.prototype.clone = function () {
  500. return new Color4(this.r, this.g, this.b, this.a);
  501. };
  502. /**
  503. * Copies the passed Color4 values into the current one.
  504. * Returns the updated Color4.
  505. */
  506. Color4.prototype.copyFrom = function (source) {
  507. this.r = source.r;
  508. this.g = source.g;
  509. this.b = source.b;
  510. this.a = source.a;
  511. return this;
  512. };
  513. /**
  514. * Copies the passed float values into the current one.
  515. * Returns the updated Color4.
  516. */
  517. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  518. this.r = r;
  519. this.g = g;
  520. this.b = b;
  521. this.a = a;
  522. return this;
  523. };
  524. /**
  525. * Copies the passed float values into the current one.
  526. * Returns the updated Color4.
  527. */
  528. Color4.prototype.set = function (r, g, b, a) {
  529. return this.copyFromFloats(r, g, b, a);
  530. };
  531. /**
  532. * Returns a string containing the hexadecimal Color4 code.
  533. */
  534. Color4.prototype.toHexString = function () {
  535. var intR = (this.r * 255) | 0;
  536. var intG = (this.g * 255) | 0;
  537. var intB = (this.b * 255) | 0;
  538. var intA = (this.a * 255) | 0;
  539. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  540. };
  541. // Statics
  542. /**
  543. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  544. */
  545. Color4.FromHexString = function (hex) {
  546. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  547. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  548. return new Color4(0.0, 0.0, 0.0, 0.0);
  549. }
  550. var r = parseInt(hex.substring(1, 3), 16);
  551. var g = parseInt(hex.substring(3, 5), 16);
  552. var b = parseInt(hex.substring(5, 7), 16);
  553. var a = parseInt(hex.substring(7, 9), 16);
  554. return Color4.FromInts(r, g, b, a);
  555. };
  556. /**
  557. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  558. */
  559. Color4.Lerp = function (left, right, amount) {
  560. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  561. Color4.LerpToRef(left, right, amount, result);
  562. return result;
  563. };
  564. /**
  565. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  566. */
  567. Color4.LerpToRef = function (left, right, amount, result) {
  568. result.r = left.r + (right.r - left.r) * amount;
  569. result.g = left.g + (right.g - left.g) * amount;
  570. result.b = left.b + (right.b - left.b) * amount;
  571. result.a = left.a + (right.a - left.a) * amount;
  572. };
  573. /**
  574. * Creates a new Color4 from the starting index element of the passed array.
  575. */
  576. Color4.FromArray = function (array, offset) {
  577. if (offset === void 0) { offset = 0; }
  578. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  579. };
  580. /**
  581. * Creates a new Color4 from the passed integers ( < 256 ).
  582. */
  583. Color4.FromInts = function (r, g, b, a) {
  584. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  585. };
  586. Color4.CheckColors4 = function (colors, count) {
  587. // Check if color3 was used
  588. if (colors.length === count * 3) {
  589. var colors4 = [];
  590. for (var index = 0; index < colors.length; index += 3) {
  591. var newIndex = (index / 3) * 4;
  592. colors4[newIndex] = colors[index];
  593. colors4[newIndex + 1] = colors[index + 1];
  594. colors4[newIndex + 2] = colors[index + 2];
  595. colors4[newIndex + 3] = 1.0;
  596. }
  597. return colors4;
  598. }
  599. return colors;
  600. };
  601. return Color4;
  602. }());
  603. BABYLON.Color4 = Color4;
  604. var Vector2 = (function () {
  605. /**
  606. * Creates a new Vector2 from the passed x and y coordinates.
  607. */
  608. function Vector2(x, y) {
  609. this.x = x;
  610. this.y = y;
  611. }
  612. /**
  613. * Returns a string with the Vector2 coordinates.
  614. */
  615. Vector2.prototype.toString = function () {
  616. return "{X: " + this.x + " Y:" + this.y + "}";
  617. };
  618. /**
  619. * Returns the string "Vector2"
  620. */
  621. Vector2.prototype.getClassName = function () {
  622. return "Vector2";
  623. };
  624. /**
  625. * Returns the Vector2 hash code as a number.
  626. */
  627. Vector2.prototype.getHashCode = function () {
  628. var hash = this.x || 0;
  629. hash = (hash * 397) ^ (this.y || 0);
  630. return hash;
  631. };
  632. // Operators
  633. /**
  634. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  635. * Returns the Vector2.
  636. */
  637. Vector2.prototype.toArray = function (array, index) {
  638. if (index === void 0) { index = 0; }
  639. array[index] = this.x;
  640. array[index + 1] = this.y;
  641. return this;
  642. };
  643. /**
  644. * Returns a new array with 2 elements : the Vector2 coordinates.
  645. */
  646. Vector2.prototype.asArray = function () {
  647. var result = [];
  648. this.toArray(result, 0);
  649. return result;
  650. };
  651. /**
  652. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  653. * Returns the updated Vector2.
  654. */
  655. Vector2.prototype.copyFrom = function (source) {
  656. this.x = source.x;
  657. this.y = source.y;
  658. return this;
  659. };
  660. /**
  661. * Sets the Vector2 coordinates with the passed floats.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.copyFromFloats = function (x, y) {
  665. this.x = x;
  666. this.y = y;
  667. return this;
  668. };
  669. /**
  670. * Sets the Vector2 coordinates with the passed floats.
  671. * Returns the updated Vector2.
  672. */
  673. Vector2.prototype.set = function (x, y) {
  674. return this.copyFromFloats(x, y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  678. */
  679. Vector2.prototype.add = function (otherVector) {
  680. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.addToRef = function (otherVector, result) {
  687. result.x = this.x + otherVector.x;
  688. result.y = this.y + otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.addInPlace = function (otherVector) {
  696. this.x += otherVector.x;
  697. this.y += otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  702. */
  703. Vector2.prototype.addVector3 = function (otherVector) {
  704. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  705. };
  706. /**
  707. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  708. */
  709. Vector2.prototype.subtract = function (otherVector) {
  710. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  711. };
  712. /**
  713. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  714. * Returns the Vector2.
  715. */
  716. Vector2.prototype.subtractToRef = function (otherVector, result) {
  717. result.x = this.x - otherVector.x;
  718. result.y = this.y - otherVector.y;
  719. return this;
  720. };
  721. /**
  722. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  723. * Returns the updated Vector2.
  724. */
  725. Vector2.prototype.subtractInPlace = function (otherVector) {
  726. this.x -= otherVector.x;
  727. this.y -= otherVector.y;
  728. return this;
  729. };
  730. /**
  731. * Multiplies in place the current Vector2 coordinates by the passed ones.
  732. * Returns the updated Vector2.
  733. */
  734. Vector2.prototype.multiplyInPlace = function (otherVector) {
  735. this.x *= otherVector.x;
  736. this.y *= otherVector.y;
  737. return this;
  738. };
  739. /**
  740. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  741. */
  742. Vector2.prototype.multiply = function (otherVector) {
  743. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  744. };
  745. /**
  746. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  747. * Returns the Vector2.
  748. */
  749. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  750. result.x = this.x * otherVector.x;
  751. result.y = this.y * otherVector.y;
  752. return this;
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  756. */
  757. Vector2.prototype.multiplyByFloats = function (x, y) {
  758. return new Vector2(this.x * x, this.y * y);
  759. };
  760. /**
  761. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  762. */
  763. Vector2.prototype.divide = function (otherVector) {
  764. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  765. };
  766. /**
  767. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  768. * Returns the Vector2.
  769. */
  770. Vector2.prototype.divideToRef = function (otherVector, result) {
  771. result.x = this.x / otherVector.x;
  772. result.y = this.y / otherVector.y;
  773. return this;
  774. };
  775. /**
  776. * Returns a new Vector2 with current Vector2 negated coordinates.
  777. */
  778. Vector2.prototype.negate = function () {
  779. return new Vector2(-this.x, -this.y);
  780. };
  781. /**
  782. * Multiply the Vector2 coordinates by scale.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.scaleInPlace = function (scale) {
  786. this.x *= scale;
  787. this.y *= scale;
  788. return this;
  789. };
  790. /**
  791. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  792. */
  793. Vector2.prototype.scale = function (scale) {
  794. return new Vector2(this.x * scale, this.y * scale);
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  798. */
  799. Vector2.prototype.equals = function (otherVector) {
  800. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  801. };
  802. /**
  803. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  804. */
  805. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  806. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  807. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  808. };
  809. // Properties
  810. /**
  811. * Returns the vector length (float).
  812. */
  813. Vector2.prototype.length = function () {
  814. return Math.sqrt(this.x * this.x + this.y * this.y);
  815. };
  816. /**
  817. * Returns the vector squared length (float);
  818. */
  819. Vector2.prototype.lengthSquared = function () {
  820. return (this.x * this.x + this.y * this.y);
  821. };
  822. // Methods
  823. /**
  824. * Normalize the vector.
  825. * Returns the updated Vector2.
  826. */
  827. Vector2.prototype.normalize = function () {
  828. var len = this.length();
  829. if (len === 0)
  830. return this;
  831. var num = 1.0 / len;
  832. this.x *= num;
  833. this.y *= num;
  834. return this;
  835. };
  836. /**
  837. * Returns a new Vector2 copied from the Vector2.
  838. */
  839. Vector2.prototype.clone = function () {
  840. return new Vector2(this.x, this.y);
  841. };
  842. // Statics
  843. /**
  844. * Returns a new Vector2(0, 0)
  845. */
  846. Vector2.Zero = function () {
  847. return new Vector2(0, 0);
  848. };
  849. /**
  850. * Returns a new Vector2(1, 1)
  851. */
  852. Vector2.One = function () {
  853. return new Vector2(1, 1);
  854. };
  855. /**
  856. * Returns a new Vector2 set from the passed index element of the passed array.
  857. */
  858. Vector2.FromArray = function (array, offset) {
  859. if (offset === void 0) { offset = 0; }
  860. return new Vector2(array[offset], array[offset + 1]);
  861. };
  862. /**
  863. * Sets "result" from the passed index element of the passed array.
  864. */
  865. Vector2.FromArrayToRef = function (array, offset, result) {
  866. result.x = array[offset];
  867. result.y = array[offset + 1];
  868. };
  869. /**
  870. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  871. */
  872. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  873. var squared = amount * amount;
  874. var cubed = amount * squared;
  875. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  876. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  877. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  878. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  879. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  880. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  881. return new Vector2(x, y);
  882. };
  883. /**
  884. * 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".
  885. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  886. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  887. */
  888. Vector2.Clamp = function (value, min, max) {
  889. var x = value.x;
  890. x = (x > max.x) ? max.x : x;
  891. x = (x < min.x) ? min.x : x;
  892. var y = value.y;
  893. y = (y > max.y) ? max.y : y;
  894. y = (y < min.y) ? min.y : y;
  895. return new Vector2(x, y);
  896. };
  897. /**
  898. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  899. */
  900. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  901. var squared = amount * amount;
  902. var cubed = amount * squared;
  903. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  904. var part2 = (-2.0 * cubed) + (3.0 * squared);
  905. var part3 = (cubed - (2.0 * squared)) + amount;
  906. var part4 = cubed - squared;
  907. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  908. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  909. return new Vector2(x, y);
  910. };
  911. /**
  912. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  913. */
  914. Vector2.Lerp = function (start, end, amount) {
  915. var x = start.x + ((end.x - start.x) * amount);
  916. var y = start.y + ((end.y - start.y) * amount);
  917. return new Vector2(x, y);
  918. };
  919. /**
  920. * Returns the dot product (float) of the vector "left" and the vector "right".
  921. */
  922. Vector2.Dot = function (left, right) {
  923. return left.x * right.x + left.y * right.y;
  924. };
  925. /**
  926. * Returns a new Vector2 equal to the normalized passed vector.
  927. */
  928. Vector2.Normalize = function (vector) {
  929. var newVector = vector.clone();
  930. newVector.normalize();
  931. return newVector;
  932. };
  933. /**
  934. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  935. */
  936. Vector2.Minimize = function (left, right) {
  937. var x = (left.x < right.x) ? left.x : right.x;
  938. var y = (left.y < right.y) ? left.y : right.y;
  939. return new Vector2(x, y);
  940. };
  941. /**
  942. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  943. */
  944. Vector2.Maximize = function (left, right) {
  945. var x = (left.x > right.x) ? left.x : right.x;
  946. var y = (left.y > right.y) ? left.y : right.y;
  947. return new Vector2(x, y);
  948. };
  949. /**
  950. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  951. */
  952. Vector2.Transform = function (vector, transformation) {
  953. var r = Vector2.Zero();
  954. Vector2.TransformToRef(vector, transformation, r);
  955. return r;
  956. };
  957. /**
  958. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  959. */
  960. Vector2.TransformToRef = function (vector, transformation, result) {
  961. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  962. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  963. result.x = x;
  964. result.y = y;
  965. };
  966. /**
  967. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  968. */
  969. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  970. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  971. var sign = a < 0 ? -1 : 1;
  972. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  973. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  974. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  975. };
  976. /**
  977. * Returns the distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.Distance = function (value1, value2) {
  980. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  981. };
  982. /**
  983. * Returns the squared distance (float) between the vectors "value1" and "value2".
  984. */
  985. Vector2.DistanceSquared = function (value1, value2) {
  986. var x = value1.x - value2.x;
  987. var y = value1.y - value2.y;
  988. return (x * x) + (y * y);
  989. };
  990. /**
  991. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  992. */
  993. Vector2.Center = function (value1, value2) {
  994. var center = value1.add(value2);
  995. center.scaleInPlace(0.5);
  996. return center;
  997. };
  998. /**
  999. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1000. */
  1001. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1002. var l2 = Vector2.DistanceSquared(segA, segB);
  1003. if (l2 === 0.0) {
  1004. return Vector2.Distance(p, segA);
  1005. }
  1006. var v = segB.subtract(segA);
  1007. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1008. var proj = segA.add(v.multiplyByFloats(t, t));
  1009. return Vector2.Distance(p, proj);
  1010. };
  1011. return Vector2;
  1012. }());
  1013. BABYLON.Vector2 = Vector2;
  1014. var Vector3 = (function () {
  1015. /**
  1016. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1017. * A Vector3 is the main object used in 3D geometry.
  1018. * It can represent etiher the coordinates of a point the space, either a direction.
  1019. */
  1020. function Vector3(x, y, z) {
  1021. this.x = x;
  1022. this.y = y;
  1023. this.z = z;
  1024. }
  1025. /**
  1026. * Returns a string with the Vector3 coordinates.
  1027. */
  1028. Vector3.prototype.toString = function () {
  1029. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1030. };
  1031. /**
  1032. * Returns the string "Vector3"
  1033. */
  1034. Vector3.prototype.getClassName = function () {
  1035. return "Vector3";
  1036. };
  1037. /**
  1038. * Returns the Vector hash code.
  1039. */
  1040. Vector3.prototype.getHashCode = function () {
  1041. var hash = this.x || 0;
  1042. hash = (hash * 397) ^ (this.y || 0);
  1043. hash = (hash * 397) ^ (this.z || 0);
  1044. return hash;
  1045. };
  1046. // Operators
  1047. /**
  1048. * Returns a new array with three elements : the coordinates the Vector3.
  1049. */
  1050. Vector3.prototype.asArray = function () {
  1051. var result = [];
  1052. this.toArray(result, 0);
  1053. return result;
  1054. };
  1055. /**
  1056. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1057. * Returns the Vector3.
  1058. */
  1059. Vector3.prototype.toArray = function (array, index) {
  1060. if (index === void 0) { index = 0; }
  1061. array[index] = this.x;
  1062. array[index + 1] = this.y;
  1063. array[index + 2] = this.z;
  1064. return this;
  1065. };
  1066. /**
  1067. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1068. */
  1069. Vector3.prototype.toQuaternion = function () {
  1070. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1071. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1072. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1073. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1074. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1075. var cosy = Math.cos(this.y * 0.5);
  1076. var siny = Math.sin(this.y * 0.5);
  1077. result.x = coszMinusx * siny;
  1078. result.y = -sinzMinusx * siny;
  1079. result.z = sinxPlusz * cosy;
  1080. result.w = cosxPlusz * cosy;
  1081. return result;
  1082. };
  1083. /**
  1084. * Adds the passed vector to the current Vector3.
  1085. * Returns the updated Vector3.
  1086. */
  1087. Vector3.prototype.addInPlace = function (otherVector) {
  1088. this.x += otherVector.x;
  1089. this.y += otherVector.y;
  1090. this.z += otherVector.z;
  1091. return this;
  1092. };
  1093. /**
  1094. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1095. */
  1096. Vector3.prototype.add = function (otherVector) {
  1097. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1098. };
  1099. /**
  1100. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1101. * Returns the current Vector3.
  1102. */
  1103. Vector3.prototype.addToRef = function (otherVector, result) {
  1104. result.x = this.x + otherVector.x;
  1105. result.y = this.y + otherVector.y;
  1106. result.z = this.z + otherVector.z;
  1107. return this;
  1108. };
  1109. /**
  1110. * Subtract the passed vector from the current Vector3.
  1111. * Returns the updated Vector3.
  1112. */
  1113. Vector3.prototype.subtractInPlace = function (otherVector) {
  1114. this.x -= otherVector.x;
  1115. this.y -= otherVector.y;
  1116. this.z -= otherVector.z;
  1117. return this;
  1118. };
  1119. /**
  1120. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1121. */
  1122. Vector3.prototype.subtract = function (otherVector) {
  1123. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1124. };
  1125. /**
  1126. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1127. * Returns the current Vector3.
  1128. */
  1129. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1130. result.x = this.x - otherVector.x;
  1131. result.y = this.y - otherVector.y;
  1132. result.z = this.z - otherVector.z;
  1133. return this;
  1134. };
  1135. /**
  1136. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1137. */
  1138. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1139. return new Vector3(this.x - x, this.y - y, this.z - z);
  1140. };
  1141. /**
  1142. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1143. * Returns the current Vector3.
  1144. */
  1145. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1146. result.x = this.x - x;
  1147. result.y = this.y - y;
  1148. result.z = this.z - z;
  1149. return this;
  1150. };
  1151. /**
  1152. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1153. */
  1154. Vector3.prototype.negate = function () {
  1155. return new Vector3(-this.x, -this.y, -this.z);
  1156. };
  1157. /**
  1158. * Multiplies the Vector3 coordinates by the float "scale".
  1159. * Returns the updated Vector3.
  1160. */
  1161. Vector3.prototype.scaleInPlace = function (scale) {
  1162. this.x *= scale;
  1163. this.y *= scale;
  1164. this.z *= scale;
  1165. return this;
  1166. };
  1167. /**
  1168. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1169. */
  1170. Vector3.prototype.scale = function (scale) {
  1171. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1172. };
  1173. /**
  1174. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1175. * Returns the current Vector3.
  1176. */
  1177. Vector3.prototype.scaleToRef = function (scale, result) {
  1178. result.x = this.x * scale;
  1179. result.y = this.y * scale;
  1180. result.z = this.z * scale;
  1181. return this;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1185. */
  1186. Vector3.prototype.equals = function (otherVector) {
  1187. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1188. };
  1189. /**
  1190. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1191. */
  1192. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1193. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1194. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1195. };
  1196. /**
  1197. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1198. */
  1199. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1200. return this.x === x && this.y === y && this.z === z;
  1201. };
  1202. /**
  1203. * Muliplies the current Vector3 coordinates by the passed ones.
  1204. * Returns the updated Vector3.
  1205. */
  1206. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1207. this.x *= otherVector.x;
  1208. this.y *= otherVector.y;
  1209. this.z *= otherVector.z;
  1210. return this;
  1211. };
  1212. /**
  1213. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1214. */
  1215. Vector3.prototype.multiply = function (otherVector) {
  1216. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1217. };
  1218. /**
  1219. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1220. * Returns the current Vector3.
  1221. */
  1222. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1223. result.x = this.x * otherVector.x;
  1224. result.y = this.y * otherVector.y;
  1225. result.z = this.z * otherVector.z;
  1226. return this;
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1230. */
  1231. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1232. return new Vector3(this.x * x, this.y * y, this.z * z);
  1233. };
  1234. /**
  1235. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1236. */
  1237. Vector3.prototype.divide = function (otherVector) {
  1238. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1239. };
  1240. /**
  1241. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1242. * Returns the current Vector3.
  1243. */
  1244. Vector3.prototype.divideToRef = function (otherVector, result) {
  1245. result.x = this.x / otherVector.x;
  1246. result.y = this.y / otherVector.y;
  1247. result.z = this.z / otherVector.z;
  1248. return this;
  1249. };
  1250. /**
  1251. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1252. * Returns the updated Vector3.
  1253. */
  1254. Vector3.prototype.MinimizeInPlace = function (other) {
  1255. if (other.x < this.x)
  1256. this.x = other.x;
  1257. if (other.y < this.y)
  1258. this.y = other.y;
  1259. if (other.z < this.z)
  1260. this.z = other.z;
  1261. return this;
  1262. };
  1263. /**
  1264. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1265. * Returns the updated Vector3.
  1266. */
  1267. Vector3.prototype.MaximizeInPlace = function (other) {
  1268. if (other.x > this.x)
  1269. this.x = other.x;
  1270. if (other.y > this.y)
  1271. this.y = other.y;
  1272. if (other.z > this.z)
  1273. this.z = other.z;
  1274. return this;
  1275. };
  1276. // Properties
  1277. /**
  1278. * Returns the length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.length = function () {
  1281. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. /**
  1284. * Returns the squared length of the Vector3 (float).
  1285. */
  1286. Vector3.prototype.lengthSquared = function () {
  1287. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1288. };
  1289. // Methods
  1290. /**
  1291. * Normalize the current Vector3.
  1292. * Returns the updated Vector3.
  1293. */
  1294. Vector3.prototype.normalize = function () {
  1295. var len = this.length();
  1296. if (len === 0 || len === 1.0)
  1297. return this;
  1298. var num = 1.0 / len;
  1299. this.x *= num;
  1300. this.y *= num;
  1301. this.z *= num;
  1302. return this;
  1303. };
  1304. /**
  1305. * Returns a new Vector3 copied from the current Vector3.
  1306. */
  1307. Vector3.prototype.clone = function () {
  1308. return new Vector3(this.x, this.y, this.z);
  1309. };
  1310. /**
  1311. * Copies the passed vector coordinates to the current Vector3 ones.
  1312. * Returns the updated Vector3.
  1313. */
  1314. Vector3.prototype.copyFrom = function (source) {
  1315. this.x = source.x;
  1316. this.y = source.y;
  1317. this.z = source.z;
  1318. return this;
  1319. };
  1320. /**
  1321. * Copies the passed floats to the current Vector3 coordinates.
  1322. * Returns the updated Vector3.
  1323. */
  1324. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1325. this.x = x;
  1326. this.y = y;
  1327. this.z = z;
  1328. return this;
  1329. };
  1330. /**
  1331. * Copies the passed floats to the current Vector3 coordinates.
  1332. * Returns the updated Vector3.
  1333. */
  1334. Vector3.prototype.set = function (x, y, z) {
  1335. return this.copyFromFloats(x, y, z);
  1336. };
  1337. // Statics
  1338. /**
  1339. *
  1340. */
  1341. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1342. var d0 = Vector3.Dot(vector0, axis) - size;
  1343. var d1 = Vector3.Dot(vector1, axis) - size;
  1344. var s = d0 / (d0 - d1);
  1345. return s;
  1346. };
  1347. /**
  1348. * Returns a new Vector3 set from the index "offset" of the passed array.
  1349. */
  1350. Vector3.FromArray = function (array, offset) {
  1351. if (!offset) {
  1352. offset = 0;
  1353. }
  1354. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1358. * This function is deprecated. Use FromArray instead.
  1359. */
  1360. Vector3.FromFloatArray = function (array, offset) {
  1361. return Vector3.FromArray(array, offset);
  1362. };
  1363. /**
  1364. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1365. */
  1366. Vector3.FromArrayToRef = function (array, offset, result) {
  1367. result.x = array[offset];
  1368. result.y = array[offset + 1];
  1369. result.z = array[offset + 2];
  1370. };
  1371. /**
  1372. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1373. * This function is deprecated. Use FromArrayToRef instead.
  1374. */
  1375. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1376. return Vector3.FromArrayToRef(array, offset, result);
  1377. };
  1378. /**
  1379. * Sets the passed vector "result" with the passed floats.
  1380. */
  1381. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1382. result.x = x;
  1383. result.y = y;
  1384. result.z = z;
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1388. */
  1389. Vector3.Zero = function () {
  1390. return new Vector3(0.0, 0.0, 0.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1394. */
  1395. Vector3.One = function () {
  1396. return new Vector3(1.0, 1.0, 1.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1400. */
  1401. Vector3.Up = function () {
  1402. return new Vector3(0.0, 1.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1406. */
  1407. Vector3.Forward = function () {
  1408. return new Vector3(0.0, 0.0, 1.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Right = function () {
  1414. return new Vector3(1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1418. */
  1419. Vector3.Left = function () {
  1420. return new Vector3(-1.0, 0.0, 0.0);
  1421. };
  1422. /**
  1423. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1424. * This method computes tranformed coordinates only, not transformed direction vectors.
  1425. */
  1426. Vector3.TransformCoordinates = function (vector, transformation) {
  1427. var result = Vector3.Zero();
  1428. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1429. return result;
  1430. };
  1431. /**
  1432. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1433. * This method computes tranformed coordinates only, not transformed direction vectors.
  1434. */
  1435. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1436. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1437. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1438. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1439. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1440. result.x = x / w;
  1441. result.y = y / w;
  1442. result.z = z / w;
  1443. };
  1444. /**
  1445. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1446. * This method computes tranformed coordinates only, not transformed direction vectors.
  1447. */
  1448. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1449. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1450. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1451. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1452. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1453. result.x = rx / rw;
  1454. result.y = ry / rw;
  1455. result.z = rz / rw;
  1456. };
  1457. /**
  1458. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1459. * This methods computes transformed normalized direction vectors only.
  1460. */
  1461. Vector3.TransformNormal = function (vector, transformation) {
  1462. var result = Vector3.Zero();
  1463. Vector3.TransformNormalToRef(vector, transformation, result);
  1464. return result;
  1465. };
  1466. /**
  1467. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1468. * This methods computes transformed normalized direction vectors only.
  1469. */
  1470. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1471. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1472. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1473. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1474. result.x = x;
  1475. result.y = y;
  1476. result.z = z;
  1477. };
  1478. /**
  1479. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1480. * This methods computes transformed normalized direction vectors only.
  1481. */
  1482. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1483. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1484. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1485. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1486. };
  1487. /**
  1488. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1489. */
  1490. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1491. var squared = amount * amount;
  1492. var cubed = amount * squared;
  1493. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1494. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1495. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1496. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1497. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1498. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1499. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1500. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1501. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1502. return new Vector3(x, y, z);
  1503. };
  1504. /**
  1505. * 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".
  1506. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1507. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1508. */
  1509. Vector3.Clamp = function (value, min, max) {
  1510. var x = value.x;
  1511. x = (x > max.x) ? max.x : x;
  1512. x = (x < min.x) ? min.x : x;
  1513. var y = value.y;
  1514. y = (y > max.y) ? max.y : y;
  1515. y = (y < min.y) ? min.y : y;
  1516. var z = value.z;
  1517. z = (z > max.z) ? max.z : z;
  1518. z = (z < min.z) ? min.z : z;
  1519. return new Vector3(x, y, z);
  1520. };
  1521. /**
  1522. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1523. */
  1524. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1525. var squared = amount * amount;
  1526. var cubed = amount * squared;
  1527. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1528. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1529. var part3 = (cubed - (2.0 * squared)) + amount;
  1530. var part4 = cubed - squared;
  1531. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1532. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1533. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1534. return new Vector3(x, y, z);
  1535. };
  1536. /**
  1537. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1538. */
  1539. Vector3.Lerp = function (start, end, amount) {
  1540. var result = new Vector3(0, 0, 0);
  1541. Vector3.LerpToRef(start, end, amount, result);
  1542. return result;
  1543. };
  1544. /**
  1545. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1546. */
  1547. Vector3.LerpToRef = function (start, end, amount, result) {
  1548. result.x = start.x + ((end.x - start.x) * amount);
  1549. result.y = start.y + ((end.y - start.y) * amount);
  1550. result.z = start.z + ((end.z - start.z) * amount);
  1551. };
  1552. /**
  1553. * Returns the dot product (float) between the vectors "left" and "right".
  1554. */
  1555. Vector3.Dot = function (left, right) {
  1556. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1557. };
  1558. /**
  1559. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1560. * The cross product is then orthogonal to both "left" and "right".
  1561. */
  1562. Vector3.Cross = function (left, right) {
  1563. var result = Vector3.Zero();
  1564. Vector3.CrossToRef(left, right, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the cross product of "left" and "right".
  1569. * The cross product is then orthogonal to both "left" and "right".
  1570. */
  1571. Vector3.CrossToRef = function (left, right, result) {
  1572. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1573. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1574. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1575. result.copyFrom(MathTmp.Vector3[0]);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 as the normalization of the passed vector.
  1579. */
  1580. Vector3.Normalize = function (vector) {
  1581. var result = Vector3.Zero();
  1582. Vector3.NormalizeToRef(vector, result);
  1583. return result;
  1584. };
  1585. /**
  1586. * Sets the passed vector "result" with the normalization of the passed first vector.
  1587. */
  1588. Vector3.NormalizeToRef = function (vector, result) {
  1589. result.copyFrom(vector);
  1590. result.normalize();
  1591. };
  1592. Vector3.Project = function (vector, world, transform, viewport) {
  1593. var cw = viewport.width;
  1594. var ch = viewport.height;
  1595. var cx = viewport.x;
  1596. var cy = viewport.y;
  1597. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1598. 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);
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.multiplyToRef(viewportMatrix, matrix);
  1602. return Vector3.TransformCoordinates(vector, matrix);
  1603. };
  1604. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1605. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1606. world.multiplyToRef(transform, matrix);
  1607. matrix.invert();
  1608. source.x = source.x / viewportWidth * 2 - 1;
  1609. source.y = -(source.y / viewportHeight * 2 - 1);
  1610. var vector = Vector3.TransformCoordinates(source, matrix);
  1611. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1612. if (MathTools.WithinEpsilon(num, 1.0)) {
  1613. vector = vector.scale(1.0 / num);
  1614. }
  1615. return vector;
  1616. };
  1617. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1618. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1619. world.multiplyToRef(view, matrix);
  1620. matrix.multiplyToRef(projection, matrix);
  1621. matrix.invert();
  1622. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1623. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1624. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1625. if (MathTools.WithinEpsilon(num, 1.0)) {
  1626. vector = vector.scale(1.0 / num);
  1627. }
  1628. return vector;
  1629. };
  1630. Vector3.Minimize = function (left, right) {
  1631. var min = left.clone();
  1632. min.MinimizeInPlace(right);
  1633. return min;
  1634. };
  1635. Vector3.Maximize = function (left, right) {
  1636. var max = left.clone();
  1637. max.MaximizeInPlace(right);
  1638. return max;
  1639. };
  1640. /**
  1641. * Returns the distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.Distance = function (value1, value2) {
  1644. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1645. };
  1646. /**
  1647. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1648. */
  1649. Vector3.DistanceSquared = function (value1, value2) {
  1650. var x = value1.x - value2.x;
  1651. var y = value1.y - value2.y;
  1652. var z = value1.z - value2.z;
  1653. return (x * x) + (y * y) + (z * z);
  1654. };
  1655. /**
  1656. * Returns a new Vector3 located at the center between "value1" and "value2".
  1657. */
  1658. Vector3.Center = function (value1, value2) {
  1659. var center = value1.add(value2);
  1660. center.scaleInPlace(0.5);
  1661. return center;
  1662. };
  1663. /**
  1664. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1665. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1666. * to something in order to rotate it from its local system to the given target system.
  1667. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1668. * Returns a new Vector3.
  1669. */
  1670. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1671. var rotation = Vector3.Zero();
  1672. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1673. return rotation;
  1674. };
  1675. /**
  1676. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1677. */
  1678. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1679. var quat = MathTmp.Quaternion[0];
  1680. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1681. quat.toEulerAnglesToRef(ref);
  1682. };
  1683. return Vector3;
  1684. }());
  1685. BABYLON.Vector3 = Vector3;
  1686. //Vector4 class created for EulerAngle class conversion to Quaternion
  1687. var Vector4 = (function () {
  1688. /**
  1689. * Creates a Vector4 object from the passed floats.
  1690. */
  1691. function Vector4(x, y, z, w) {
  1692. this.x = x;
  1693. this.y = y;
  1694. this.z = z;
  1695. this.w = w;
  1696. }
  1697. /**
  1698. * Returns the string with the Vector4 coordinates.
  1699. */
  1700. Vector4.prototype.toString = function () {
  1701. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1702. };
  1703. /**
  1704. * Returns the string "Vector4".
  1705. */
  1706. Vector4.prototype.getClassName = function () {
  1707. return "Vector4";
  1708. };
  1709. /**
  1710. * Returns the Vector4 hash code.
  1711. */
  1712. Vector4.prototype.getHashCode = function () {
  1713. var hash = this.x || 0;
  1714. hash = (hash * 397) ^ (this.y || 0);
  1715. hash = (hash * 397) ^ (this.z || 0);
  1716. hash = (hash * 397) ^ (this.w || 0);
  1717. return hash;
  1718. };
  1719. // Operators
  1720. /**
  1721. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1722. */
  1723. Vector4.prototype.asArray = function () {
  1724. var result = [];
  1725. this.toArray(result, 0);
  1726. return result;
  1727. };
  1728. /**
  1729. * Populates the passed array from the passed index with the Vector4 coordinates.
  1730. * Returns the Vector4.
  1731. */
  1732. Vector4.prototype.toArray = function (array, index) {
  1733. if (index === undefined) {
  1734. index = 0;
  1735. }
  1736. array[index] = this.x;
  1737. array[index + 1] = this.y;
  1738. array[index + 2] = this.z;
  1739. array[index + 3] = this.w;
  1740. return this;
  1741. };
  1742. /**
  1743. * Adds the passed vector to the current Vector4.
  1744. * Returns the updated Vector4.
  1745. */
  1746. Vector4.prototype.addInPlace = function (otherVector) {
  1747. this.x += otherVector.x;
  1748. this.y += otherVector.y;
  1749. this.z += otherVector.z;
  1750. this.w += otherVector.w;
  1751. return this;
  1752. };
  1753. /**
  1754. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1755. */
  1756. Vector4.prototype.add = function (otherVector) {
  1757. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1758. };
  1759. /**
  1760. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1761. * Returns the current Vector4.
  1762. */
  1763. Vector4.prototype.addToRef = function (otherVector, result) {
  1764. result.x = this.x + otherVector.x;
  1765. result.y = this.y + otherVector.y;
  1766. result.z = this.z + otherVector.z;
  1767. result.w = this.w + otherVector.w;
  1768. return this;
  1769. };
  1770. /**
  1771. * Subtract in place the passed vector from the current Vector4.
  1772. * Returns the updated Vector4.
  1773. */
  1774. Vector4.prototype.subtractInPlace = function (otherVector) {
  1775. this.x -= otherVector.x;
  1776. this.y -= otherVector.y;
  1777. this.z -= otherVector.z;
  1778. this.w -= otherVector.w;
  1779. return this;
  1780. };
  1781. /**
  1782. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1783. */
  1784. Vector4.prototype.subtract = function (otherVector) {
  1785. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1786. };
  1787. /**
  1788. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1789. * Returns the current Vector4.
  1790. */
  1791. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1792. result.x = this.x - otherVector.x;
  1793. result.y = this.y - otherVector.y;
  1794. result.z = this.z - otherVector.z;
  1795. result.w = this.w - otherVector.w;
  1796. return this;
  1797. };
  1798. /**
  1799. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. */
  1801. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1802. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1803. };
  1804. /**
  1805. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1806. * Returns the current Vector4.
  1807. */
  1808. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1809. result.x = this.x - x;
  1810. result.y = this.y - y;
  1811. result.z = this.z - z;
  1812. result.w = this.w - w;
  1813. return this;
  1814. };
  1815. /**
  1816. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1817. */
  1818. Vector4.prototype.negate = function () {
  1819. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1820. };
  1821. /**
  1822. * Multiplies the current Vector4 coordinates by scale (float).
  1823. * Returns the updated Vector4.
  1824. */
  1825. Vector4.prototype.scaleInPlace = function (scale) {
  1826. this.x *= scale;
  1827. this.y *= scale;
  1828. this.z *= scale;
  1829. this.w *= scale;
  1830. return this;
  1831. };
  1832. /**
  1833. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1834. */
  1835. Vector4.prototype.scale = function (scale) {
  1836. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1837. };
  1838. /**
  1839. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1840. * Returns the current Vector4.
  1841. */
  1842. Vector4.prototype.scaleToRef = function (scale, result) {
  1843. result.x = this.x * scale;
  1844. result.y = this.y * scale;
  1845. result.z = this.z * scale;
  1846. result.w = this.w * scale;
  1847. return this;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1851. */
  1852. Vector4.prototype.equals = function (otherVector) {
  1853. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1854. };
  1855. /**
  1856. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1857. */
  1858. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1859. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1860. return otherVector
  1861. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1862. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1863. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1864. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1865. };
  1866. /**
  1867. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1868. */
  1869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1870. return this.x === x && this.y === y && this.z === z && this.w === w;
  1871. };
  1872. /**
  1873. * Multiplies in place the current Vector4 by the passed one.
  1874. * Returns the updated Vector4.
  1875. */
  1876. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1877. this.x *= otherVector.x;
  1878. this.y *= otherVector.y;
  1879. this.z *= otherVector.z;
  1880. this.w *= otherVector.w;
  1881. return this;
  1882. };
  1883. /**
  1884. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1885. */
  1886. Vector4.prototype.multiply = function (otherVector) {
  1887. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1888. };
  1889. /**
  1890. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1891. * Returns the current Vector4.
  1892. */
  1893. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1894. result.x = this.x * otherVector.x;
  1895. result.y = this.y * otherVector.y;
  1896. result.z = this.z * otherVector.z;
  1897. result.w = this.w * otherVector.w;
  1898. return this;
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1902. */
  1903. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1904. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1905. };
  1906. /**
  1907. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1908. */
  1909. Vector4.prototype.divide = function (otherVector) {
  1910. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1911. };
  1912. /**
  1913. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1914. * Returns the current Vector4.
  1915. */
  1916. Vector4.prototype.divideToRef = function (otherVector, result) {
  1917. result.x = this.x / otherVector.x;
  1918. result.y = this.y / otherVector.y;
  1919. result.z = this.z / otherVector.z;
  1920. result.w = this.w / otherVector.w;
  1921. return this;
  1922. };
  1923. /**
  1924. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1925. */
  1926. Vector4.prototype.MinimizeInPlace = function (other) {
  1927. if (other.x < this.x)
  1928. this.x = other.x;
  1929. if (other.y < this.y)
  1930. this.y = other.y;
  1931. if (other.z < this.z)
  1932. this.z = other.z;
  1933. if (other.w < this.w)
  1934. this.w = other.w;
  1935. return this;
  1936. };
  1937. /**
  1938. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1939. */
  1940. Vector4.prototype.MaximizeInPlace = function (other) {
  1941. if (other.x > this.x)
  1942. this.x = other.x;
  1943. if (other.y > this.y)
  1944. this.y = other.y;
  1945. if (other.z > this.z)
  1946. this.z = other.z;
  1947. if (other.w > this.w)
  1948. this.w = other.w;
  1949. return this;
  1950. };
  1951. // Properties
  1952. /**
  1953. * Returns the Vector4 length (float).
  1954. */
  1955. Vector4.prototype.length = function () {
  1956. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. /**
  1959. * Returns the Vector4 squared length (float).
  1960. */
  1961. Vector4.prototype.lengthSquared = function () {
  1962. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1963. };
  1964. // Methods
  1965. /**
  1966. * Normalizes in place the Vector4.
  1967. * Returns the updated Vector4.
  1968. */
  1969. Vector4.prototype.normalize = function () {
  1970. var len = this.length();
  1971. if (len === 0)
  1972. return this;
  1973. var num = 1.0 / len;
  1974. this.x *= num;
  1975. this.y *= num;
  1976. this.z *= num;
  1977. this.w *= num;
  1978. return this;
  1979. };
  1980. /**
  1981. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1982. */
  1983. Vector4.prototype.toVector3 = function () {
  1984. return new Vector3(this.x, this.y, this.z);
  1985. };
  1986. /**
  1987. * Returns a new Vector4 copied from the current one.
  1988. */
  1989. Vector4.prototype.clone = function () {
  1990. return new Vector4(this.x, this.y, this.z, this.w);
  1991. };
  1992. /**
  1993. * Updates the current Vector4 with the passed one coordinates.
  1994. * Returns the updated Vector4.
  1995. */
  1996. Vector4.prototype.copyFrom = function (source) {
  1997. this.x = source.x;
  1998. this.y = source.y;
  1999. this.z = source.z;
  2000. this.w = source.w;
  2001. return this;
  2002. };
  2003. /**
  2004. * Updates the current Vector4 coordinates with the passed floats.
  2005. * Returns the updated Vector4.
  2006. */
  2007. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2008. this.x = x;
  2009. this.y = y;
  2010. this.z = z;
  2011. this.w = w;
  2012. return this;
  2013. };
  2014. /**
  2015. * Updates the current Vector4 coordinates with the passed floats.
  2016. * Returns the updated Vector4.
  2017. */
  2018. Vector4.prototype.set = function (x, y, z, w) {
  2019. return this.copyFromFloats(x, y, z, w);
  2020. };
  2021. // Statics
  2022. /**
  2023. * Returns a new Vector4 set from the starting index of the passed array.
  2024. */
  2025. Vector4.FromArray = function (array, offset) {
  2026. if (!offset) {
  2027. offset = 0;
  2028. }
  2029. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2030. };
  2031. /**
  2032. * Updates the passed vector "result" from the starting index of the passed array.
  2033. */
  2034. Vector4.FromArrayToRef = function (array, offset, result) {
  2035. result.x = array[offset];
  2036. result.y = array[offset + 1];
  2037. result.z = array[offset + 2];
  2038. result.w = array[offset + 3];
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2042. */
  2043. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2044. Vector4.FromArrayToRef(array, offset, result);
  2045. };
  2046. /**
  2047. * Updates the passed vector "result" coordinates from the passed floats.
  2048. */
  2049. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2050. result.x = x;
  2051. result.y = y;
  2052. result.z = z;
  2053. result.w = w;
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2057. */
  2058. Vector4.Zero = function () {
  2059. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2060. };
  2061. /**
  2062. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2063. */
  2064. Vector4.One = function () {
  2065. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2066. };
  2067. /**
  2068. * Returns a new normalized Vector4 from the passed one.
  2069. */
  2070. Vector4.Normalize = function (vector) {
  2071. var result = Vector4.Zero();
  2072. Vector4.NormalizeToRef(vector, result);
  2073. return result;
  2074. };
  2075. /**
  2076. * Updates the passed vector "result" from the normalization of the passed one.
  2077. */
  2078. Vector4.NormalizeToRef = function (vector, result) {
  2079. result.copyFrom(vector);
  2080. result.normalize();
  2081. };
  2082. Vector4.Minimize = function (left, right) {
  2083. var min = left.clone();
  2084. min.MinimizeInPlace(right);
  2085. return min;
  2086. };
  2087. Vector4.Maximize = function (left, right) {
  2088. var max = left.clone();
  2089. max.MaximizeInPlace(right);
  2090. return max;
  2091. };
  2092. /**
  2093. * Returns the distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.Distance = function (value1, value2) {
  2096. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2097. };
  2098. /**
  2099. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2100. */
  2101. Vector4.DistanceSquared = function (value1, value2) {
  2102. var x = value1.x - value2.x;
  2103. var y = value1.y - value2.y;
  2104. var z = value1.z - value2.z;
  2105. var w = value1.w - value2.w;
  2106. return (x * x) + (y * y) + (z * z) + (w * w);
  2107. };
  2108. /**
  2109. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2110. */
  2111. Vector4.Center = function (value1, value2) {
  2112. var center = value1.add(value2);
  2113. center.scaleInPlace(0.5);
  2114. return center;
  2115. };
  2116. /**
  2117. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2118. * This methods computes transformed normalized direction vectors only.
  2119. */
  2120. Vector4.TransformNormal = function (vector, transformation) {
  2121. var result = Vector4.Zero();
  2122. Vector4.TransformNormalToRef(vector, transformation, result);
  2123. return result;
  2124. };
  2125. /**
  2126. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2127. * This methods computes transformed normalized direction vectors only.
  2128. */
  2129. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2130. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2131. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2132. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2133. result.x = x;
  2134. result.y = y;
  2135. result.z = z;
  2136. result.w = vector.w;
  2137. };
  2138. /**
  2139. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2140. * This methods computes transformed normalized direction vectors only.
  2141. */
  2142. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2143. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2144. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2145. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2146. result.w = w;
  2147. };
  2148. return Vector4;
  2149. }());
  2150. BABYLON.Vector4 = Vector4;
  2151. var Size = (function () {
  2152. /**
  2153. * Creates a Size object from the passed width and height (floats).
  2154. */
  2155. function Size(width, height) {
  2156. this.width = width;
  2157. this.height = height;
  2158. }
  2159. // Returns a string with the Size width and height.
  2160. Size.prototype.toString = function () {
  2161. return "{W: " + this.width + ", H: " + this.height + "}";
  2162. };
  2163. /**
  2164. * Returns the string "Size"
  2165. */
  2166. Size.prototype.getClassName = function () {
  2167. return "Size";
  2168. };
  2169. /**
  2170. * Returns the Size hash code.
  2171. */
  2172. Size.prototype.getHashCode = function () {
  2173. var hash = this.width || 0;
  2174. hash = (hash * 397) ^ (this.height || 0);
  2175. return hash;
  2176. };
  2177. /**
  2178. * Updates the current size from the passed one.
  2179. * Returns the updated Size.
  2180. */
  2181. Size.prototype.copyFrom = function (src) {
  2182. this.width = src.width;
  2183. this.height = src.height;
  2184. };
  2185. /**
  2186. * Updates in place the current Size from the passed floats.
  2187. * Returns the updated Size.
  2188. */
  2189. Size.prototype.copyFromFloats = function (width, height) {
  2190. this.width = width;
  2191. this.height = height;
  2192. return this;
  2193. };
  2194. /**
  2195. * Updates in place the current Size from the passed floats.
  2196. * Returns the updated Size.
  2197. */
  2198. Size.prototype.set = function (width, height) {
  2199. return this.copyFromFloats(width, height);
  2200. };
  2201. /**
  2202. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2203. */
  2204. Size.prototype.multiplyByFloats = function (w, h) {
  2205. return new Size(this.width * w, this.height * h);
  2206. };
  2207. /**
  2208. * Returns a new Size copied from the passed one.
  2209. */
  2210. Size.prototype.clone = function () {
  2211. return new Size(this.width, this.height);
  2212. };
  2213. /**
  2214. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2215. */
  2216. Size.prototype.equals = function (other) {
  2217. if (!other) {
  2218. return false;
  2219. }
  2220. return (this.width === other.width) && (this.height === other.height);
  2221. };
  2222. Object.defineProperty(Size.prototype, "surface", {
  2223. /**
  2224. * Returns the surface of the Size : width * height (float).
  2225. */
  2226. get: function () {
  2227. return this.width * this.height;
  2228. },
  2229. enumerable: true,
  2230. configurable: true
  2231. });
  2232. /**
  2233. * Returns a new Size set to (0.0, 0.0)
  2234. */
  2235. Size.Zero = function () {
  2236. return new Size(0.0, 0.0);
  2237. };
  2238. /**
  2239. * Returns a new Size set as the addition result of the current Size and the passed one.
  2240. */
  2241. Size.prototype.add = function (otherSize) {
  2242. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2243. return r;
  2244. };
  2245. /**
  2246. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2247. */
  2248. Size.prototype.subtract = function (otherSize) {
  2249. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2250. return r;
  2251. };
  2252. /**
  2253. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2254. */
  2255. Size.Lerp = function (start, end, amount) {
  2256. var w = start.width + ((end.width - start.width) * amount);
  2257. var h = start.height + ((end.height - start.height) * amount);
  2258. return new Size(w, h);
  2259. };
  2260. return Size;
  2261. }());
  2262. BABYLON.Size = Size;
  2263. var Quaternion = (function () {
  2264. /**
  2265. * Creates a new Quaternion from the passed floats.
  2266. */
  2267. function Quaternion(x, y, z, w) {
  2268. if (x === void 0) { x = 0.0; }
  2269. if (y === void 0) { y = 0.0; }
  2270. if (z === void 0) { z = 0.0; }
  2271. if (w === void 0) { w = 1.0; }
  2272. this.x = x;
  2273. this.y = y;
  2274. this.z = z;
  2275. this.w = w;
  2276. }
  2277. /**
  2278. * Returns a string with the Quaternion coordinates.
  2279. */
  2280. Quaternion.prototype.toString = function () {
  2281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2282. };
  2283. /**
  2284. * Returns the string "Quaternion".
  2285. */
  2286. Quaternion.prototype.getClassName = function () {
  2287. return "Quaternion";
  2288. };
  2289. /**
  2290. * Returns the Quaternion hash code.
  2291. */
  2292. Quaternion.prototype.getHashCode = function () {
  2293. var hash = this.x || 0;
  2294. hash = (hash * 397) ^ (this.y || 0);
  2295. hash = (hash * 397) ^ (this.z || 0);
  2296. hash = (hash * 397) ^ (this.w || 0);
  2297. return hash;
  2298. };
  2299. /**
  2300. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2301. */
  2302. Quaternion.prototype.asArray = function () {
  2303. return [this.x, this.y, this.z, this.w];
  2304. };
  2305. /**
  2306. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2307. */
  2308. Quaternion.prototype.equals = function (otherQuaternion) {
  2309. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2310. };
  2311. /**
  2312. * Returns a new Quaternion copied from the current one.
  2313. */
  2314. Quaternion.prototype.clone = function () {
  2315. return new Quaternion(this.x, this.y, this.z, this.w);
  2316. };
  2317. /**
  2318. * Updates the current Quaternion from the passed one coordinates.
  2319. * Returns the updated Quaterion.
  2320. */
  2321. Quaternion.prototype.copyFrom = function (other) {
  2322. this.x = other.x;
  2323. this.y = other.y;
  2324. this.z = other.z;
  2325. this.w = other.w;
  2326. return this;
  2327. };
  2328. /**
  2329. * Updates the current Quaternion from the passed float coordinates.
  2330. * Returns the updated Quaterion.
  2331. */
  2332. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2333. this.x = x;
  2334. this.y = y;
  2335. this.z = z;
  2336. this.w = w;
  2337. return this;
  2338. };
  2339. /**
  2340. * Updates the current Quaternion from the passed float coordinates.
  2341. * Returns the updated Quaterion.
  2342. */
  2343. Quaternion.prototype.set = function (x, y, z, w) {
  2344. return this.copyFromFloats(x, y, z, w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2348. */
  2349. Quaternion.prototype.add = function (other) {
  2350. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2351. };
  2352. /**
  2353. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2354. */
  2355. Quaternion.prototype.subtract = function (other) {
  2356. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2360. */
  2361. Quaternion.prototype.scale = function (value) {
  2362. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2363. };
  2364. /**
  2365. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2366. */
  2367. Quaternion.prototype.multiply = function (q1) {
  2368. var result = new Quaternion(0, 0, 0, 1.0);
  2369. this.multiplyToRef(q1, result);
  2370. return result;
  2371. };
  2372. /**
  2373. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2374. * Returns the current Quaternion.
  2375. */
  2376. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2377. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2378. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2379. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2380. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2381. result.copyFromFloats(x, y, z, w);
  2382. return this;
  2383. };
  2384. /**
  2385. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2386. * Returns the updated Quaternion.
  2387. */
  2388. Quaternion.prototype.multiplyInPlace = function (q1) {
  2389. this.multiplyToRef(q1, this);
  2390. return this;
  2391. };
  2392. /**
  2393. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2394. * Returns the current Quaternion.
  2395. */
  2396. Quaternion.prototype.conjugateToRef = function (ref) {
  2397. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2398. return this;
  2399. };
  2400. /**
  2401. * Conjugates in place the current Quaternion.
  2402. * Returns the updated Quaternion.
  2403. */
  2404. Quaternion.prototype.conjugateInPlace = function () {
  2405. this.x *= -1;
  2406. this.y *= -1;
  2407. this.z *= -1;
  2408. return this;
  2409. };
  2410. /**
  2411. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2412. */
  2413. Quaternion.prototype.conjugate = function () {
  2414. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2415. return result;
  2416. };
  2417. /**
  2418. * Returns the Quaternion length (float).
  2419. */
  2420. Quaternion.prototype.length = function () {
  2421. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2422. };
  2423. /**
  2424. * Normalize in place the current Quaternion.
  2425. * Returns the updated Quaternion.
  2426. */
  2427. Quaternion.prototype.normalize = function () {
  2428. var length = 1.0 / this.length();
  2429. this.x *= length;
  2430. this.y *= length;
  2431. this.z *= length;
  2432. this.w *= length;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2437. */
  2438. Quaternion.prototype.toEulerAngles = function (order) {
  2439. if (order === void 0) { order = "YZX"; }
  2440. var result = Vector3.Zero();
  2441. this.toEulerAnglesToRef(result, order);
  2442. return result;
  2443. };
  2444. /**
  2445. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2446. * Returns the current Quaternion.
  2447. */
  2448. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2449. if (order === void 0) { order = "YZX"; }
  2450. var qz = this.z;
  2451. var qx = this.x;
  2452. var qy = this.y;
  2453. var qw = this.w;
  2454. var sqw = qw * qw;
  2455. var sqz = qz * qz;
  2456. var sqx = qx * qx;
  2457. var sqy = qy * qy;
  2458. var zAxisY = qy * qz - qx * qw;
  2459. var limit = .4999999;
  2460. if (zAxisY < -limit) {
  2461. result.y = 2 * Math.atan2(qy, qw);
  2462. result.x = Math.PI / 2;
  2463. result.z = 0;
  2464. }
  2465. else if (zAxisY > limit) {
  2466. result.y = 2 * Math.atan2(qy, qw);
  2467. result.x = -Math.PI / 2;
  2468. result.z = 0;
  2469. }
  2470. else {
  2471. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2472. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2473. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2474. }
  2475. return this;
  2476. };
  2477. /**
  2478. * Updates the passed rotation matrix with the current Quaternion values.
  2479. * Returns the current Quaternion.
  2480. */
  2481. Quaternion.prototype.toRotationMatrix = function (result) {
  2482. var xx = this.x * this.x;
  2483. var yy = this.y * this.y;
  2484. var zz = this.z * this.z;
  2485. var xy = this.x * this.y;
  2486. var zw = this.z * this.w;
  2487. var zx = this.z * this.x;
  2488. var yw = this.y * this.w;
  2489. var yz = this.y * this.z;
  2490. var xw = this.x * this.w;
  2491. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2492. result.m[1] = 2.0 * (xy + zw);
  2493. result.m[2] = 2.0 * (zx - yw);
  2494. result.m[3] = 0;
  2495. result.m[4] = 2.0 * (xy - zw);
  2496. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2497. result.m[6] = 2.0 * (yz + xw);
  2498. result.m[7] = 0;
  2499. result.m[8] = 2.0 * (zx + yw);
  2500. result.m[9] = 2.0 * (yz - xw);
  2501. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2502. result.m[11] = 0;
  2503. result.m[12] = 0;
  2504. result.m[13] = 0;
  2505. result.m[14] = 0;
  2506. result.m[15] = 1.0;
  2507. result._markAsUpdated();
  2508. return this;
  2509. };
  2510. /**
  2511. * Updates the current Quaternion from the passed rotation matrix values.
  2512. * Returns the updated Quaternion.
  2513. */
  2514. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2515. Quaternion.FromRotationMatrixToRef(matrix, this);
  2516. return this;
  2517. };
  2518. // Statics
  2519. /**
  2520. * Returns a new Quaternion set from the passed rotation matrix values.
  2521. */
  2522. Quaternion.FromRotationMatrix = function (matrix) {
  2523. var result = new Quaternion();
  2524. Quaternion.FromRotationMatrixToRef(matrix, result);
  2525. return result;
  2526. };
  2527. /**
  2528. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2529. */
  2530. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2531. var data = matrix.m;
  2532. var m11 = data[0], m12 = data[4], m13 = data[8];
  2533. var m21 = data[1], m22 = data[5], m23 = data[9];
  2534. var m31 = data[2], m32 = data[6], m33 = data[10];
  2535. var trace = m11 + m22 + m33;
  2536. var s;
  2537. if (trace > 0) {
  2538. s = 0.5 / Math.sqrt(trace + 1.0);
  2539. result.w = 0.25 / s;
  2540. result.x = (m32 - m23) * s;
  2541. result.y = (m13 - m31) * s;
  2542. result.z = (m21 - m12) * s;
  2543. }
  2544. else if (m11 > m22 && m11 > m33) {
  2545. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2546. result.w = (m32 - m23) / s;
  2547. result.x = 0.25 * s;
  2548. result.y = (m12 + m21) / s;
  2549. result.z = (m13 + m31) / s;
  2550. }
  2551. else if (m22 > m33) {
  2552. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2553. result.w = (m13 - m31) / s;
  2554. result.x = (m12 + m21) / s;
  2555. result.y = 0.25 * s;
  2556. result.z = (m23 + m32) / s;
  2557. }
  2558. else {
  2559. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2560. result.w = (m21 - m12) / s;
  2561. result.x = (m13 + m31) / s;
  2562. result.y = (m23 + m32) / s;
  2563. result.z = 0.25 * s;
  2564. }
  2565. };
  2566. /**
  2567. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2568. */
  2569. Quaternion.Zero = function () {
  2570. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2571. };
  2572. /**
  2573. * Returns a new Quaternion as the inverted current Quaternion.
  2574. */
  2575. Quaternion.Inverse = function (q) {
  2576. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2577. };
  2578. /**
  2579. * Returns the identity Quaternion.
  2580. */
  2581. Quaternion.Identity = function () {
  2582. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2583. };
  2584. Quaternion.IsIdentity = function (quaternion) {
  2585. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2586. };
  2587. /**
  2588. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxis = function (axis, angle) {
  2591. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2592. };
  2593. /**
  2594. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2595. */
  2596. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2597. var sin = Math.sin(angle / 2);
  2598. axis.normalize();
  2599. result.w = Math.cos(angle / 2);
  2600. result.x = axis.x * sin;
  2601. result.y = axis.y * sin;
  2602. result.z = axis.z * sin;
  2603. return result;
  2604. };
  2605. /**
  2606. * Retuns a new Quaternion set from the starting index of the passed array.
  2607. */
  2608. Quaternion.FromArray = function (array, offset) {
  2609. if (!offset) {
  2610. offset = 0;
  2611. }
  2612. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2613. };
  2614. /**
  2615. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2616. */
  2617. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2618. var q = new Quaternion();
  2619. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2620. return q;
  2621. };
  2622. /**
  2623. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2624. */
  2625. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2626. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2627. var halfRoll = roll * 0.5;
  2628. var halfPitch = pitch * 0.5;
  2629. var halfYaw = yaw * 0.5;
  2630. var sinRoll = Math.sin(halfRoll);
  2631. var cosRoll = Math.cos(halfRoll);
  2632. var sinPitch = Math.sin(halfPitch);
  2633. var cosPitch = Math.cos(halfPitch);
  2634. var sinYaw = Math.sin(halfYaw);
  2635. var cosYaw = Math.cos(halfYaw);
  2636. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2637. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2638. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2639. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2640. };
  2641. /**
  2642. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2643. */
  2644. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2645. var result = new Quaternion();
  2646. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2647. return result;
  2648. };
  2649. /**
  2650. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2651. */
  2652. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2653. // Produces a quaternion from Euler angles in the z-x-z orientation
  2654. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2655. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2656. var halfBeta = beta * 0.5;
  2657. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2658. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2659. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2660. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2661. };
  2662. /**
  2663. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2664. * cf to Vector3.RotationFromAxis() documentation.
  2665. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2666. */
  2667. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2668. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2669. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2670. return quat;
  2671. };
  2672. /**
  2673. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2674. * cf to Vector3.RotationFromAxis() documentation.
  2675. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2676. */
  2677. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2678. var rotMat = MathTmp.Matrix[0];
  2679. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2680. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2681. };
  2682. Quaternion.Slerp = function (left, right, amount) {
  2683. var result = Quaternion.Identity();
  2684. Quaternion.SlerpToRef(left, right, amount, result);
  2685. return result;
  2686. };
  2687. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2688. var num2;
  2689. var num3;
  2690. var num = amount;
  2691. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2692. var flag = false;
  2693. if (num4 < 0) {
  2694. flag = true;
  2695. num4 = -num4;
  2696. }
  2697. if (num4 > 0.999999) {
  2698. num3 = 1 - num;
  2699. num2 = flag ? -num : num;
  2700. }
  2701. else {
  2702. var num5 = Math.acos(num4);
  2703. var num6 = (1.0 / Math.sin(num5));
  2704. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2705. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2706. }
  2707. result.x = (num3 * left.x) + (num2 * right.x);
  2708. result.y = (num3 * left.y) + (num2 * right.y);
  2709. result.z = (num3 * left.z) + (num2 * right.z);
  2710. result.w = (num3 * left.w) + (num2 * right.w);
  2711. };
  2712. /**
  2713. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2714. */
  2715. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2716. var squared = amount * amount;
  2717. var cubed = amount * squared;
  2718. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2719. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2720. var part3 = (cubed - (2.0 * squared)) + amount;
  2721. var part4 = cubed - squared;
  2722. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2723. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2724. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2725. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2726. return new Quaternion(x, y, z, w);
  2727. };
  2728. return Quaternion;
  2729. }());
  2730. BABYLON.Quaternion = Quaternion;
  2731. var Matrix = (function () {
  2732. function Matrix() {
  2733. this._isIdentity = false;
  2734. this._isIdentityDirty = true;
  2735. this.m = new Float32Array(16);
  2736. this._markAsUpdated();
  2737. }
  2738. Matrix.prototype._markAsUpdated = function () {
  2739. this.updateFlag = Matrix._updateFlagSeed++;
  2740. this._isIdentityDirty = true;
  2741. };
  2742. // Properties
  2743. /**
  2744. * Boolean : True is the matrix is the identity matrix
  2745. */
  2746. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2747. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2748. if (this._isIdentityDirty) {
  2749. this._isIdentityDirty = false;
  2750. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2751. this._isIdentity = false;
  2752. }
  2753. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2754. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2755. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2756. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2757. this._isIdentity = false;
  2758. }
  2759. else {
  2760. this._isIdentity = true;
  2761. }
  2762. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2763. this._isIdentity = false;
  2764. }
  2765. }
  2766. return this._isIdentity;
  2767. };
  2768. /**
  2769. * Returns the matrix determinant (float).
  2770. */
  2771. Matrix.prototype.determinant = function () {
  2772. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2773. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2774. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2775. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2776. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2777. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2778. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2779. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2780. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2781. };
  2782. // Methods
  2783. /**
  2784. * Returns the matrix underlying array.
  2785. */
  2786. Matrix.prototype.toArray = function () {
  2787. return this.m;
  2788. };
  2789. /**
  2790. * Returns the matrix underlying array.
  2791. */
  2792. Matrix.prototype.asArray = function () {
  2793. return this.toArray();
  2794. };
  2795. /**
  2796. * Inverts in place the Matrix.
  2797. * Returns the Matrix inverted.
  2798. */
  2799. Matrix.prototype.invert = function () {
  2800. this.invertToRef(this);
  2801. return this;
  2802. };
  2803. /**
  2804. * Sets all the matrix elements to zero.
  2805. * Returns the Matrix.
  2806. */
  2807. Matrix.prototype.reset = function () {
  2808. for (var index = 0; index < 16; index++) {
  2809. this.m[index] = 0.0;
  2810. }
  2811. this._markAsUpdated();
  2812. return this;
  2813. };
  2814. /**
  2815. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2816. */
  2817. Matrix.prototype.add = function (other) {
  2818. var result = new Matrix();
  2819. this.addToRef(other, result);
  2820. return result;
  2821. };
  2822. /**
  2823. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2824. * Returns the Matrix.
  2825. */
  2826. Matrix.prototype.addToRef = function (other, result) {
  2827. for (var index = 0; index < 16; index++) {
  2828. result.m[index] = this.m[index] + other.m[index];
  2829. }
  2830. result._markAsUpdated();
  2831. return this;
  2832. };
  2833. /**
  2834. * Adds in place the passed matrix to the current Matrix.
  2835. * Returns the updated Matrix.
  2836. */
  2837. Matrix.prototype.addToSelf = function (other) {
  2838. for (var index = 0; index < 16; index++) {
  2839. this.m[index] += other.m[index];
  2840. }
  2841. this._markAsUpdated();
  2842. return this;
  2843. };
  2844. /**
  2845. * Sets the passed matrix with the current inverted Matrix.
  2846. * Returns the unmodified current Matrix.
  2847. */
  2848. Matrix.prototype.invertToRef = function (other) {
  2849. var l1 = this.m[0];
  2850. var l2 = this.m[1];
  2851. var l3 = this.m[2];
  2852. var l4 = this.m[3];
  2853. var l5 = this.m[4];
  2854. var l6 = this.m[5];
  2855. var l7 = this.m[6];
  2856. var l8 = this.m[7];
  2857. var l9 = this.m[8];
  2858. var l10 = this.m[9];
  2859. var l11 = this.m[10];
  2860. var l12 = this.m[11];
  2861. var l13 = this.m[12];
  2862. var l14 = this.m[13];
  2863. var l15 = this.m[14];
  2864. var l16 = this.m[15];
  2865. var l17 = (l11 * l16) - (l12 * l15);
  2866. var l18 = (l10 * l16) - (l12 * l14);
  2867. var l19 = (l10 * l15) - (l11 * l14);
  2868. var l20 = (l9 * l16) - (l12 * l13);
  2869. var l21 = (l9 * l15) - (l11 * l13);
  2870. var l22 = (l9 * l14) - (l10 * l13);
  2871. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2872. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2873. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2874. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2875. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2876. var l28 = (l7 * l16) - (l8 * l15);
  2877. var l29 = (l6 * l16) - (l8 * l14);
  2878. var l30 = (l6 * l15) - (l7 * l14);
  2879. var l31 = (l5 * l16) - (l8 * l13);
  2880. var l32 = (l5 * l15) - (l7 * l13);
  2881. var l33 = (l5 * l14) - (l6 * l13);
  2882. var l34 = (l7 * l12) - (l8 * l11);
  2883. var l35 = (l6 * l12) - (l8 * l10);
  2884. var l36 = (l6 * l11) - (l7 * l10);
  2885. var l37 = (l5 * l12) - (l8 * l9);
  2886. var l38 = (l5 * l11) - (l7 * l9);
  2887. var l39 = (l5 * l10) - (l6 * l9);
  2888. other.m[0] = l23 * l27;
  2889. other.m[4] = l24 * l27;
  2890. other.m[8] = l25 * l27;
  2891. other.m[12] = l26 * l27;
  2892. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2893. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2894. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2895. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2896. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2897. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2898. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2899. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2900. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2901. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2902. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2903. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2904. other._markAsUpdated();
  2905. return this;
  2906. };
  2907. /**
  2908. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2909. * Returns the updated Matrix.
  2910. */
  2911. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2912. this.m[12] = x;
  2913. this.m[13] = y;
  2914. this.m[14] = z;
  2915. this._markAsUpdated();
  2916. return this;
  2917. };
  2918. /**
  2919. * Inserts the translation vector in the current Matrix.
  2920. * Returns the updated Matrix.
  2921. */
  2922. Matrix.prototype.setTranslation = function (vector3) {
  2923. this.m[12] = vector3.x;
  2924. this.m[13] = vector3.y;
  2925. this.m[14] = vector3.z;
  2926. this._markAsUpdated();
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 as the extracted translation from the Matrix.
  2931. */
  2932. Matrix.prototype.getTranslation = function () {
  2933. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2934. };
  2935. /**
  2936. * Fill a Vector3 with the extracted translation from the Matrix.
  2937. */
  2938. Matrix.prototype.getTranslationToRef = function (result) {
  2939. result.x = this.m[12];
  2940. result.y = this.m[13];
  2941. result.z = this.m[14];
  2942. return this;
  2943. };
  2944. /**
  2945. * Remove rotation and scaling part from the Matrix.
  2946. * Returns the updated Matrix.
  2947. */
  2948. Matrix.prototype.removeRotationAndScaling = function () {
  2949. this.setRowFromFloats(0, 1, 0, 0, 0);
  2950. this.setRowFromFloats(1, 0, 1, 0, 0);
  2951. this.setRowFromFloats(2, 0, 0, 1, 0);
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2956. */
  2957. Matrix.prototype.multiply = function (other) {
  2958. var result = new Matrix();
  2959. this.multiplyToRef(other, result);
  2960. return result;
  2961. };
  2962. /**
  2963. * Updates the current Matrix from the passed one values.
  2964. * Returns the updated Matrix.
  2965. */
  2966. Matrix.prototype.copyFrom = function (other) {
  2967. for (var index = 0; index < 16; index++) {
  2968. this.m[index] = other.m[index];
  2969. }
  2970. this._markAsUpdated();
  2971. return this;
  2972. };
  2973. /**
  2974. * Populates the passed array from the starting index with the Matrix values.
  2975. * Returns the Matrix.
  2976. */
  2977. Matrix.prototype.copyToArray = function (array, offset) {
  2978. if (offset === void 0) { offset = 0; }
  2979. for (var index = 0; index < 16; index++) {
  2980. array[offset + index] = this.m[index];
  2981. }
  2982. return this;
  2983. };
  2984. /**
  2985. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2986. */
  2987. Matrix.prototype.multiplyToRef = function (other, result) {
  2988. this.multiplyToArray(other, result.m, 0);
  2989. result._markAsUpdated();
  2990. return this;
  2991. };
  2992. /**
  2993. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2994. */
  2995. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2996. var tm0 = this.m[0];
  2997. var tm1 = this.m[1];
  2998. var tm2 = this.m[2];
  2999. var tm3 = this.m[3];
  3000. var tm4 = this.m[4];
  3001. var tm5 = this.m[5];
  3002. var tm6 = this.m[6];
  3003. var tm7 = this.m[7];
  3004. var tm8 = this.m[8];
  3005. var tm9 = this.m[9];
  3006. var tm10 = this.m[10];
  3007. var tm11 = this.m[11];
  3008. var tm12 = this.m[12];
  3009. var tm13 = this.m[13];
  3010. var tm14 = this.m[14];
  3011. var tm15 = this.m[15];
  3012. var om0 = other.m[0];
  3013. var om1 = other.m[1];
  3014. var om2 = other.m[2];
  3015. var om3 = other.m[3];
  3016. var om4 = other.m[4];
  3017. var om5 = other.m[5];
  3018. var om6 = other.m[6];
  3019. var om7 = other.m[7];
  3020. var om8 = other.m[8];
  3021. var om9 = other.m[9];
  3022. var om10 = other.m[10];
  3023. var om11 = other.m[11];
  3024. var om12 = other.m[12];
  3025. var om13 = other.m[13];
  3026. var om14 = other.m[14];
  3027. var om15 = other.m[15];
  3028. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3029. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3030. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3031. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3032. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3033. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3034. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3035. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3036. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3037. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3038. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3039. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3040. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3041. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3042. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3043. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3044. return this;
  3045. };
  3046. /**
  3047. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3048. */
  3049. Matrix.prototype.equals = function (value) {
  3050. return value &&
  3051. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3052. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3053. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3054. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3055. };
  3056. /**
  3057. * Returns a new Matrix from the current Matrix.
  3058. */
  3059. Matrix.prototype.clone = function () {
  3060. 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]);
  3061. };
  3062. /**
  3063. * Returns the string "Matrix"
  3064. */
  3065. Matrix.prototype.getClassName = function () {
  3066. return "Matrix";
  3067. };
  3068. /**
  3069. * Returns the Matrix hash code.
  3070. */
  3071. Matrix.prototype.getHashCode = function () {
  3072. var hash = this.m[0] || 0;
  3073. for (var i = 1; i < 16; i++) {
  3074. hash = (hash * 397) ^ (this.m[i] || 0);
  3075. }
  3076. return hash;
  3077. };
  3078. /**
  3079. * Decomposes the current Matrix into :
  3080. * - a scale vector3 passed as a reference to update,
  3081. * - a rotation quaternion passed as a reference to update,
  3082. * - a translation vector3 passed as a reference to update.
  3083. * Returns the boolean `true`.
  3084. */
  3085. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3086. translation.x = this.m[12];
  3087. translation.y = this.m[13];
  3088. translation.z = this.m[14];
  3089. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3090. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3091. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3092. if (this.determinant() <= 0) {
  3093. scale.y *= -1;
  3094. }
  3095. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3096. rotation.x = 0;
  3097. rotation.y = 0;
  3098. rotation.z = 0;
  3099. rotation.w = 1;
  3100. return false;
  3101. }
  3102. 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]);
  3103. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3104. return true;
  3105. };
  3106. /**
  3107. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3108. */
  3109. Matrix.prototype.getRotationMatrix = function () {
  3110. var result = Matrix.Identity();
  3111. this.getRotationMatrixToRef(result);
  3112. return result;
  3113. };
  3114. /**
  3115. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3116. * Returns the current Matrix.
  3117. */
  3118. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3119. var m = this.m;
  3120. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3121. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3122. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3123. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3124. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3125. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3126. 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);
  3127. return this;
  3128. };
  3129. // Statics
  3130. /**
  3131. * Returns a new Matrix set from the starting index of the passed array.
  3132. */
  3133. Matrix.FromArray = function (array, offset) {
  3134. var result = new Matrix();
  3135. if (!offset) {
  3136. offset = 0;
  3137. }
  3138. Matrix.FromArrayToRef(array, offset, result);
  3139. return result;
  3140. };
  3141. /**
  3142. * Sets the passed "result" matrix from the starting index of the passed array.
  3143. */
  3144. Matrix.FromArrayToRef = function (array, offset, result) {
  3145. for (var index = 0; index < 16; index++) {
  3146. result.m[index] = array[index + offset];
  3147. }
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3152. */
  3153. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3154. for (var index = 0; index < 16; index++) {
  3155. result.m[index] = array[index + offset] * scale;
  3156. }
  3157. result._markAsUpdated();
  3158. };
  3159. /**
  3160. * Sets the passed matrix "result" with the 16 passed floats.
  3161. */
  3162. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3163. result.m[0] = initialM11;
  3164. result.m[1] = initialM12;
  3165. result.m[2] = initialM13;
  3166. result.m[3] = initialM14;
  3167. result.m[4] = initialM21;
  3168. result.m[5] = initialM22;
  3169. result.m[6] = initialM23;
  3170. result.m[7] = initialM24;
  3171. result.m[8] = initialM31;
  3172. result.m[9] = initialM32;
  3173. result.m[10] = initialM33;
  3174. result.m[11] = initialM34;
  3175. result.m[12] = initialM41;
  3176. result.m[13] = initialM42;
  3177. result.m[14] = initialM43;
  3178. result.m[15] = initialM44;
  3179. result._markAsUpdated();
  3180. };
  3181. /**
  3182. * Returns the index-th row of the current matrix as a new Vector4.
  3183. */
  3184. Matrix.prototype.getRow = function (index) {
  3185. if (index < 0 || index > 3) {
  3186. return null;
  3187. }
  3188. var i = index * 4;
  3189. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3190. };
  3191. /**
  3192. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3193. * Returns the updated Matrix.
  3194. */
  3195. Matrix.prototype.setRow = function (index, row) {
  3196. if (index < 0 || index > 3) {
  3197. return this;
  3198. }
  3199. var i = index * 4;
  3200. this.m[i + 0] = row.x;
  3201. this.m[i + 1] = row.y;
  3202. this.m[i + 2] = row.z;
  3203. this.m[i + 3] = row.w;
  3204. this._markAsUpdated();
  3205. return this;
  3206. };
  3207. /**
  3208. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3209. * Returns the updated Matrix.
  3210. */
  3211. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3212. if (index < 0 || index > 3) {
  3213. return this;
  3214. }
  3215. var i = index * 4;
  3216. this.m[i + 0] = x;
  3217. this.m[i + 1] = y;
  3218. this.m[i + 2] = z;
  3219. this.m[i + 3] = w;
  3220. this._markAsUpdated();
  3221. return this;
  3222. };
  3223. /**
  3224. * Returns a new Matrix set from the 16 passed floats.
  3225. */
  3226. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3227. var result = new Matrix();
  3228. result.m[0] = initialM11;
  3229. result.m[1] = initialM12;
  3230. result.m[2] = initialM13;
  3231. result.m[3] = initialM14;
  3232. result.m[4] = initialM21;
  3233. result.m[5] = initialM22;
  3234. result.m[6] = initialM23;
  3235. result.m[7] = initialM24;
  3236. result.m[8] = initialM31;
  3237. result.m[9] = initialM32;
  3238. result.m[10] = initialM33;
  3239. result.m[11] = initialM34;
  3240. result.m[12] = initialM41;
  3241. result.m[13] = initialM42;
  3242. result.m[14] = initialM43;
  3243. result.m[15] = initialM44;
  3244. return result;
  3245. };
  3246. /**
  3247. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3248. */
  3249. Matrix.Compose = function (scale, rotation, translation) {
  3250. var result = Matrix.Identity();
  3251. Matrix.ComposeToRef(scale, rotation, translation, result);
  3252. return result;
  3253. };
  3254. /**
  3255. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3256. */
  3257. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3258. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3259. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3260. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3261. result.setTranslation(translation);
  3262. };
  3263. /**
  3264. * Returns a new indentity Matrix.
  3265. */
  3266. Matrix.Identity = function () {
  3267. 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);
  3268. };
  3269. /**
  3270. * Sets the passed "result" as an identity matrix.
  3271. */
  3272. Matrix.IdentityToRef = function (result) {
  3273. 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);
  3274. };
  3275. /**
  3276. * Returns a new zero Matrix.
  3277. */
  3278. Matrix.Zero = function () {
  3279. 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);
  3280. };
  3281. /**
  3282. * Returns a new rotation matrix for "angle" radians around the X axis.
  3283. */
  3284. Matrix.RotationX = function (angle) {
  3285. var result = new Matrix();
  3286. Matrix.RotationXToRef(angle, result);
  3287. return result;
  3288. };
  3289. /**
  3290. * Returns a new Matrix as the passed inverted one.
  3291. */
  3292. Matrix.Invert = function (source) {
  3293. var result = new Matrix();
  3294. source.invertToRef(result);
  3295. return result;
  3296. };
  3297. /**
  3298. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3299. */
  3300. Matrix.RotationXToRef = function (angle, result) {
  3301. var s = Math.sin(angle);
  3302. var c = Math.cos(angle);
  3303. result.m[0] = 1.0;
  3304. result.m[15] = 1.0;
  3305. result.m[5] = c;
  3306. result.m[10] = c;
  3307. result.m[9] = -s;
  3308. result.m[6] = s;
  3309. result.m[1] = 0.0;
  3310. result.m[2] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[7] = 0.0;
  3314. result.m[8] = 0.0;
  3315. result.m[11] = 0.0;
  3316. result.m[12] = 0.0;
  3317. result.m[13] = 0.0;
  3318. result.m[14] = 0.0;
  3319. result._markAsUpdated();
  3320. };
  3321. /**
  3322. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3323. */
  3324. Matrix.RotationY = function (angle) {
  3325. var result = new Matrix();
  3326. Matrix.RotationYToRef(angle, result);
  3327. return result;
  3328. };
  3329. /**
  3330. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3331. */
  3332. Matrix.RotationYToRef = function (angle, result) {
  3333. var s = Math.sin(angle);
  3334. var c = Math.cos(angle);
  3335. result.m[5] = 1.0;
  3336. result.m[15] = 1.0;
  3337. result.m[0] = c;
  3338. result.m[2] = -s;
  3339. result.m[8] = s;
  3340. result.m[10] = c;
  3341. result.m[1] = 0.0;
  3342. result.m[3] = 0.0;
  3343. result.m[4] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[9] = 0.0;
  3347. result.m[11] = 0.0;
  3348. result.m[12] = 0.0;
  3349. result.m[13] = 0.0;
  3350. result.m[14] = 0.0;
  3351. result._markAsUpdated();
  3352. };
  3353. /**
  3354. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3355. */
  3356. Matrix.RotationZ = function (angle) {
  3357. var result = new Matrix();
  3358. Matrix.RotationZToRef(angle, result);
  3359. return result;
  3360. };
  3361. /**
  3362. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3363. */
  3364. Matrix.RotationZToRef = function (angle, result) {
  3365. var s = Math.sin(angle);
  3366. var c = Math.cos(angle);
  3367. result.m[10] = 1.0;
  3368. result.m[15] = 1.0;
  3369. result.m[0] = c;
  3370. result.m[1] = s;
  3371. result.m[4] = -s;
  3372. result.m[5] = c;
  3373. result.m[2] = 0.0;
  3374. result.m[3] = 0.0;
  3375. result.m[6] = 0.0;
  3376. result.m[7] = 0.0;
  3377. result.m[8] = 0.0;
  3378. result.m[9] = 0.0;
  3379. result.m[11] = 0.0;
  3380. result.m[12] = 0.0;
  3381. result.m[13] = 0.0;
  3382. result.m[14] = 0.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3387. */
  3388. Matrix.RotationAxis = function (axis, angle) {
  3389. var result = Matrix.Zero();
  3390. Matrix.RotationAxisToRef(axis, angle, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3395. */
  3396. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3397. var s = Math.sin(-angle);
  3398. var c = Math.cos(-angle);
  3399. var c1 = 1 - c;
  3400. axis.normalize();
  3401. result.m[0] = (axis.x * axis.x) * c1 + c;
  3402. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3403. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3404. result.m[3] = 0.0;
  3405. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3406. result.m[5] = (axis.y * axis.y) * c1 + c;
  3407. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3408. result.m[7] = 0.0;
  3409. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3410. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3411. result.m[10] = (axis.z * axis.z) * c1 + c;
  3412. result.m[11] = 0.0;
  3413. result.m[15] = 1.0;
  3414. result._markAsUpdated();
  3415. };
  3416. /**
  3417. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3418. */
  3419. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3420. var result = new Matrix();
  3421. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3422. return result;
  3423. };
  3424. /**
  3425. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3426. */
  3427. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3428. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3429. this._tempQuaternion.toRotationMatrix(result);
  3430. };
  3431. /**
  3432. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3433. */
  3434. Matrix.Scaling = function (x, y, z) {
  3435. var result = Matrix.Zero();
  3436. Matrix.ScalingToRef(x, y, z, result);
  3437. return result;
  3438. };
  3439. /**
  3440. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3441. */
  3442. Matrix.ScalingToRef = function (x, y, z, result) {
  3443. result.m[0] = x;
  3444. result.m[1] = 0.0;
  3445. result.m[2] = 0.0;
  3446. result.m[3] = 0.0;
  3447. result.m[4] = 0.0;
  3448. result.m[5] = y;
  3449. result.m[6] = 0.0;
  3450. result.m[7] = 0.0;
  3451. result.m[8] = 0.0;
  3452. result.m[9] = 0.0;
  3453. result.m[10] = z;
  3454. result.m[11] = 0.0;
  3455. result.m[12] = 0.0;
  3456. result.m[13] = 0.0;
  3457. result.m[14] = 0.0;
  3458. result.m[15] = 1.0;
  3459. result._markAsUpdated();
  3460. };
  3461. /**
  3462. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3463. */
  3464. Matrix.Translation = function (x, y, z) {
  3465. var result = Matrix.Identity();
  3466. Matrix.TranslationToRef(x, y, z, result);
  3467. return result;
  3468. };
  3469. /**
  3470. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3471. */
  3472. Matrix.TranslationToRef = function (x, y, z, result) {
  3473. 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);
  3474. };
  3475. /**
  3476. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3477. */
  3478. Matrix.Lerp = function (startValue, endValue, gradient) {
  3479. var result = Matrix.Zero();
  3480. for (var index = 0; index < 16; index++) {
  3481. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3482. }
  3483. result._markAsUpdated();
  3484. return result;
  3485. };
  3486. /**
  3487. * Returns a new Matrix whose values are computed by :
  3488. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3489. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3490. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3491. */
  3492. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3493. var startScale = new Vector3(0, 0, 0);
  3494. var startRotation = new Quaternion();
  3495. var startTranslation = new Vector3(0, 0, 0);
  3496. startValue.decompose(startScale, startRotation, startTranslation);
  3497. var endScale = new Vector3(0, 0, 0);
  3498. var endRotation = new Quaternion();
  3499. var endTranslation = new Vector3(0, 0, 0);
  3500. endValue.decompose(endScale, endRotation, endTranslation);
  3501. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3502. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3503. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3504. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3505. };
  3506. /**
  3507. * 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".
  3508. * This methods works for a Left-Handed system.
  3509. */
  3510. Matrix.LookAtLH = function (eye, target, up) {
  3511. var result = Matrix.Zero();
  3512. Matrix.LookAtLHToRef(eye, target, up, result);
  3513. return result;
  3514. };
  3515. /**
  3516. * 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".
  3517. * This methods works for a Left-Handed system.
  3518. */
  3519. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3520. // Z axis
  3521. target.subtractToRef(eye, this._zAxis);
  3522. this._zAxis.normalize();
  3523. // X axis
  3524. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3525. if (this._xAxis.lengthSquared() === 0) {
  3526. this._xAxis.x = 1.0;
  3527. }
  3528. else {
  3529. this._xAxis.normalize();
  3530. }
  3531. // Y axis
  3532. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3533. this._yAxis.normalize();
  3534. // Eye angles
  3535. var ex = -Vector3.Dot(this._xAxis, eye);
  3536. var ey = -Vector3.Dot(this._yAxis, eye);
  3537. var ez = -Vector3.Dot(this._zAxis, eye);
  3538. 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);
  3539. };
  3540. /**
  3541. * 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".
  3542. * This methods works for a Right-Handed system.
  3543. */
  3544. Matrix.LookAtRH = function (eye, target, up) {
  3545. var result = Matrix.Zero();
  3546. Matrix.LookAtRHToRef(eye, target, up, result);
  3547. return result;
  3548. };
  3549. /**
  3550. * 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".
  3551. * This methods works for a Left-Handed system.
  3552. */
  3553. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3554. // Z axis
  3555. eye.subtractToRef(target, this._zAxis);
  3556. this._zAxis.normalize();
  3557. // X axis
  3558. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3559. if (this._xAxis.lengthSquared() === 0) {
  3560. this._xAxis.x = 1.0;
  3561. }
  3562. else {
  3563. this._xAxis.normalize();
  3564. }
  3565. // Y axis
  3566. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3567. this._yAxis.normalize();
  3568. // Eye angles
  3569. var ex = -Vector3.Dot(this._xAxis, eye);
  3570. var ey = -Vector3.Dot(this._yAxis, eye);
  3571. var ez = -Vector3.Dot(this._zAxis, eye);
  3572. 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);
  3573. };
  3574. /**
  3575. * 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.
  3576. */
  3577. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3578. var matrix = Matrix.Zero();
  3579. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3580. return matrix;
  3581. };
  3582. /**
  3583. * 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.
  3584. */
  3585. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3586. var n = znear;
  3587. var f = zfar;
  3588. var a = 2.0 / width;
  3589. var b = 2.0 / height;
  3590. var c = 2.0 / (f - n);
  3591. var d = -(f + n) / (f - n);
  3592. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3593. };
  3594. /**
  3595. * 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.
  3596. */
  3597. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3598. var matrix = Matrix.Zero();
  3599. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3600. return matrix;
  3601. };
  3602. /**
  3603. * 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.
  3604. */
  3605. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3606. var n = znear;
  3607. var f = zfar;
  3608. var a = 2.0 / (right - left);
  3609. var b = 2.0 / (top - bottom);
  3610. var c = 2.0 / (f - n);
  3611. var d = -(f + n) / (f - n);
  3612. var i0 = (left + right) / (left - right);
  3613. var i1 = (top + bottom) / (bottom - top);
  3614. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3615. };
  3616. /**
  3617. * 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.
  3618. */
  3619. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3620. var matrix = Matrix.Zero();
  3621. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * 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.
  3626. */
  3627. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3628. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3629. result.m[10] *= -1.0;
  3630. };
  3631. /**
  3632. * 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.
  3633. */
  3634. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3635. var matrix = Matrix.Zero();
  3636. var n = znear;
  3637. var f = zfar;
  3638. var a = 2.0 * n / width;
  3639. var b = 2.0 * n / height;
  3640. var c = (f + n) / (f - n);
  3641. var d = -2.0 * f * n / (f - n);
  3642. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3643. return matrix;
  3644. };
  3645. /**
  3646. * 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.
  3647. */
  3648. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3649. var matrix = Matrix.Zero();
  3650. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3651. return matrix;
  3652. };
  3653. /**
  3654. * 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.
  3655. */
  3656. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3657. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3658. var n = znear;
  3659. var f = zfar;
  3660. var t = 1.0 / (Math.tan(fov * 0.5));
  3661. var a = isVerticalFovFixed ? (t / aspect) : t;
  3662. var b = isVerticalFovFixed ? t : (t * aspect);
  3663. var c = (f + n) / (f - n);
  3664. var d = -2.0 * f * n / (f - n);
  3665. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3666. };
  3667. /**
  3668. * 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.
  3669. */
  3670. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3671. var matrix = Matrix.Zero();
  3672. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3673. return matrix;
  3674. };
  3675. /**
  3676. * 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.
  3677. */
  3678. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3679. //alternatively this could be expressed as:
  3680. // m = PerspectiveFovLHToRef
  3681. // m[10] *= -1.0;
  3682. // m[11] *= -1.0;
  3683. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3684. var n = znear;
  3685. var f = zfar;
  3686. var t = 1.0 / (Math.tan(fov * 0.5));
  3687. var a = isVerticalFovFixed ? (t / aspect) : t;
  3688. var b = isVerticalFovFixed ? t : (t * aspect);
  3689. var c = -(f + n) / (f - n);
  3690. var d = -2 * f * n / (f - n);
  3691. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3692. };
  3693. /**
  3694. * 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.
  3695. */
  3696. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3697. if (rightHanded === void 0) { rightHanded = false; }
  3698. var rightHandedFactor = rightHanded ? -1 : 1;
  3699. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3700. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3701. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3702. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3703. var xScale = 2.0 / (leftTan + rightTan);
  3704. var yScale = 2.0 / (upTan + downTan);
  3705. result.m[0] = xScale;
  3706. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3707. result.m[5] = yScale;
  3708. result.m[6] = result.m[7] = 0.0;
  3709. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3710. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3711. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3712. result.m[10] = -zfar / (znear - zfar);
  3713. result.m[11] = 1.0 * rightHandedFactor;
  3714. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3715. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3716. // result.m[14] = (znear * zfar) / (znear - zfar);
  3717. result._markAsUpdated();
  3718. };
  3719. /**
  3720. * Returns the final transformation matrix : world * view * projection * viewport
  3721. */
  3722. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3723. var cw = viewport.width;
  3724. var ch = viewport.height;
  3725. var cx = viewport.x;
  3726. var cy = viewport.y;
  3727. 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);
  3728. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3729. };
  3730. /**
  3731. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3732. */
  3733. Matrix.GetAsMatrix2x2 = function (matrix) {
  3734. return new Float32Array([
  3735. matrix.m[0], matrix.m[1],
  3736. matrix.m[4], matrix.m[5]
  3737. ]);
  3738. };
  3739. /**
  3740. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3741. */
  3742. Matrix.GetAsMatrix3x3 = function (matrix) {
  3743. return new Float32Array([
  3744. matrix.m[0], matrix.m[1], matrix.m[2],
  3745. matrix.m[4], matrix.m[5], matrix.m[6],
  3746. matrix.m[8], matrix.m[9], matrix.m[10]
  3747. ]);
  3748. };
  3749. /**
  3750. * Compute the transpose of the passed Matrix.
  3751. * Returns a new Matrix.
  3752. */
  3753. Matrix.Transpose = function (matrix) {
  3754. var result = new Matrix();
  3755. result.m[0] = matrix.m[0];
  3756. result.m[1] = matrix.m[4];
  3757. result.m[2] = matrix.m[8];
  3758. result.m[3] = matrix.m[12];
  3759. result.m[4] = matrix.m[1];
  3760. result.m[5] = matrix.m[5];
  3761. result.m[6] = matrix.m[9];
  3762. result.m[7] = matrix.m[13];
  3763. result.m[8] = matrix.m[2];
  3764. result.m[9] = matrix.m[6];
  3765. result.m[10] = matrix.m[10];
  3766. result.m[11] = matrix.m[14];
  3767. result.m[12] = matrix.m[3];
  3768. result.m[13] = matrix.m[7];
  3769. result.m[14] = matrix.m[11];
  3770. result.m[15] = matrix.m[15];
  3771. return result;
  3772. };
  3773. /**
  3774. * Returns a new Matrix as the reflection matrix across the passed plane.
  3775. */
  3776. Matrix.Reflection = function (plane) {
  3777. var matrix = new Matrix();
  3778. Matrix.ReflectionToRef(plane, matrix);
  3779. return matrix;
  3780. };
  3781. /**
  3782. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3783. */
  3784. Matrix.ReflectionToRef = function (plane, result) {
  3785. plane.normalize();
  3786. var x = plane.normal.x;
  3787. var y = plane.normal.y;
  3788. var z = plane.normal.z;
  3789. var temp = -2 * x;
  3790. var temp2 = -2 * y;
  3791. var temp3 = -2 * z;
  3792. result.m[0] = (temp * x) + 1;
  3793. result.m[1] = temp2 * x;
  3794. result.m[2] = temp3 * x;
  3795. result.m[3] = 0.0;
  3796. result.m[4] = temp * y;
  3797. result.m[5] = (temp2 * y) + 1;
  3798. result.m[6] = temp3 * y;
  3799. result.m[7] = 0.0;
  3800. result.m[8] = temp * z;
  3801. result.m[9] = temp2 * z;
  3802. result.m[10] = (temp3 * z) + 1;
  3803. result.m[11] = 0.0;
  3804. result.m[12] = temp * plane.d;
  3805. result.m[13] = temp2 * plane.d;
  3806. result.m[14] = temp3 * plane.d;
  3807. result.m[15] = 1.0;
  3808. result._markAsUpdated();
  3809. };
  3810. /**
  3811. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3812. */
  3813. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3814. result.m[0] = xaxis.x;
  3815. result.m[1] = xaxis.y;
  3816. result.m[2] = xaxis.z;
  3817. result.m[3] = 0.0;
  3818. result.m[4] = yaxis.x;
  3819. result.m[5] = yaxis.y;
  3820. result.m[6] = yaxis.z;
  3821. result.m[7] = 0.0;
  3822. result.m[8] = zaxis.x;
  3823. result.m[9] = zaxis.y;
  3824. result.m[10] = zaxis.z;
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. /**
  3833. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3834. */
  3835. Matrix.FromQuaternionToRef = function (quat, result) {
  3836. var xx = quat.x * quat.x;
  3837. var yy = quat.y * quat.y;
  3838. var zz = quat.z * quat.z;
  3839. var xy = quat.x * quat.y;
  3840. var zw = quat.z * quat.w;
  3841. var zx = quat.z * quat.x;
  3842. var yw = quat.y * quat.w;
  3843. var yz = quat.y * quat.z;
  3844. var xw = quat.x * quat.w;
  3845. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3846. result.m[1] = 2.0 * (xy + zw);
  3847. result.m[2] = 2.0 * (zx - yw);
  3848. result.m[3] = 0.0;
  3849. result.m[4] = 2.0 * (xy - zw);
  3850. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3851. result.m[6] = 2.0 * (yz + xw);
  3852. result.m[7] = 0.0;
  3853. result.m[8] = 2.0 * (zx + yw);
  3854. result.m[9] = 2.0 * (yz - xw);
  3855. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3856. result.m[11] = 0.0;
  3857. result.m[12] = 0.0;
  3858. result.m[13] = 0.0;
  3859. result.m[14] = 0.0;
  3860. result.m[15] = 1.0;
  3861. result._markAsUpdated();
  3862. };
  3863. return Matrix;
  3864. }());
  3865. Matrix._tempQuaternion = new Quaternion();
  3866. Matrix._xAxis = Vector3.Zero();
  3867. Matrix._yAxis = Vector3.Zero();
  3868. Matrix._zAxis = Vector3.Zero();
  3869. Matrix._updateFlagSeed = 0;
  3870. BABYLON.Matrix = Matrix;
  3871. var Plane = (function () {
  3872. /**
  3873. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3874. */
  3875. function Plane(a, b, c, d) {
  3876. this.normal = new Vector3(a, b, c);
  3877. this.d = d;
  3878. }
  3879. /**
  3880. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3881. */
  3882. Plane.prototype.asArray = function () {
  3883. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3884. };
  3885. // Methods
  3886. /**
  3887. * Returns a new plane copied from the current Plane.
  3888. */
  3889. Plane.prototype.clone = function () {
  3890. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3891. };
  3892. /**
  3893. * Returns the string "Plane".
  3894. */
  3895. Plane.prototype.getClassName = function () {
  3896. return "Plane";
  3897. };
  3898. /**
  3899. * Returns the Plane hash code.
  3900. */
  3901. Plane.prototype.getHashCode = function () {
  3902. var hash = this.normal.getHashCode();
  3903. hash = (hash * 397) ^ (this.d || 0);
  3904. return hash;
  3905. };
  3906. /**
  3907. * Normalize the current Plane in place.
  3908. * Returns the updated Plane.
  3909. */
  3910. Plane.prototype.normalize = function () {
  3911. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3912. var magnitude = 0.0;
  3913. if (norm !== 0) {
  3914. magnitude = 1.0 / norm;
  3915. }
  3916. this.normal.x *= magnitude;
  3917. this.normal.y *= magnitude;
  3918. this.normal.z *= magnitude;
  3919. this.d *= magnitude;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3924. */
  3925. Plane.prototype.transform = function (transformation) {
  3926. var transposedMatrix = Matrix.Transpose(transformation);
  3927. var x = this.normal.x;
  3928. var y = this.normal.y;
  3929. var z = this.normal.z;
  3930. var d = this.d;
  3931. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3932. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3933. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3934. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3935. return new Plane(normalX, normalY, normalZ, finalD);
  3936. };
  3937. /**
  3938. * Returns the dot product (float) of the point coordinates and the plane normal.
  3939. */
  3940. Plane.prototype.dotCoordinate = function (point) {
  3941. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3942. };
  3943. /**
  3944. * Updates the current Plane from the plane defined by the three passed points.
  3945. * Returns the updated Plane.
  3946. */
  3947. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3948. var x1 = point2.x - point1.x;
  3949. var y1 = point2.y - point1.y;
  3950. var z1 = point2.z - point1.z;
  3951. var x2 = point3.x - point1.x;
  3952. var y2 = point3.y - point1.y;
  3953. var z2 = point3.z - point1.z;
  3954. var yz = (y1 * z2) - (z1 * y2);
  3955. var xz = (z1 * x2) - (x1 * z2);
  3956. var xy = (x1 * y2) - (y1 * x2);
  3957. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3958. var invPyth;
  3959. if (pyth !== 0) {
  3960. invPyth = 1.0 / pyth;
  3961. }
  3962. else {
  3963. invPyth = 0.0;
  3964. }
  3965. this.normal.x = yz * invPyth;
  3966. this.normal.y = xz * invPyth;
  3967. this.normal.z = xy * invPyth;
  3968. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3969. return this;
  3970. };
  3971. /**
  3972. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3973. */
  3974. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3975. var dot = Vector3.Dot(this.normal, direction);
  3976. return (dot <= epsilon);
  3977. };
  3978. /**
  3979. * Returns the signed distance (float) from the passed point to the Plane.
  3980. */
  3981. Plane.prototype.signedDistanceTo = function (point) {
  3982. return Vector3.Dot(point, this.normal) + this.d;
  3983. };
  3984. // Statics
  3985. /**
  3986. * Returns a new Plane from the passed array.
  3987. */
  3988. Plane.FromArray = function (array) {
  3989. return new Plane(array[0], array[1], array[2], array[3]);
  3990. };
  3991. /**
  3992. * Returns a new Plane defined by the three passed points.
  3993. */
  3994. Plane.FromPoints = function (point1, point2, point3) {
  3995. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3996. result.copyFromPoints(point1, point2, point3);
  3997. return result;
  3998. };
  3999. /**
  4000. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4001. * Note : the vector "normal" is updated because normalized.
  4002. */
  4003. Plane.FromPositionAndNormal = function (origin, normal) {
  4004. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4005. normal.normalize();
  4006. result.normal = normal;
  4007. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4008. return result;
  4009. };
  4010. /**
  4011. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4012. */
  4013. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4014. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4015. return Vector3.Dot(point, normal) + d;
  4016. };
  4017. return Plane;
  4018. }());
  4019. BABYLON.Plane = Plane;
  4020. var Viewport = (function () {
  4021. /**
  4022. * Creates a Viewport object located at (x, y) and sized (width, height).
  4023. */
  4024. function Viewport(x, y, width, height) {
  4025. this.x = x;
  4026. this.y = y;
  4027. this.width = width;
  4028. this.height = height;
  4029. }
  4030. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4031. if (renderWidthOrEngine._gl) {
  4032. var engine = renderWidthOrEngine;
  4033. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4034. }
  4035. var renderWidth = renderWidthOrEngine;
  4036. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4037. };
  4038. /**
  4039. * Returns a new Viewport copied from the current one.
  4040. */
  4041. Viewport.prototype.clone = function () {
  4042. return new Viewport(this.x, this.y, this.width, this.height);
  4043. };
  4044. return Viewport;
  4045. }());
  4046. BABYLON.Viewport = Viewport;
  4047. var Frustum = (function () {
  4048. function Frustum() {
  4049. }
  4050. /**
  4051. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4052. */
  4053. Frustum.GetPlanes = function (transform) {
  4054. var frustumPlanes = [];
  4055. for (var index = 0; index < 6; index++) {
  4056. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4057. }
  4058. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4059. return frustumPlanes;
  4060. };
  4061. /**
  4062. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4063. */
  4064. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4065. // Near
  4066. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4067. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4068. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4069. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4070. frustumPlanes[0].normalize();
  4071. // Far
  4072. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4073. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4074. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4075. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4076. frustumPlanes[1].normalize();
  4077. // Left
  4078. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4079. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4080. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4081. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4082. frustumPlanes[2].normalize();
  4083. // Right
  4084. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4085. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4086. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4087. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4088. frustumPlanes[3].normalize();
  4089. // Top
  4090. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4091. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4092. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4093. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4094. frustumPlanes[4].normalize();
  4095. // Bottom
  4096. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4097. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4098. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4099. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4100. frustumPlanes[5].normalize();
  4101. };
  4102. return Frustum;
  4103. }());
  4104. BABYLON.Frustum = Frustum;
  4105. var Space;
  4106. (function (Space) {
  4107. Space[Space["LOCAL"] = 0] = "LOCAL";
  4108. Space[Space["WORLD"] = 1] = "WORLD";
  4109. Space[Space["BONE"] = 2] = "BONE";
  4110. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4111. var Axis = (function () {
  4112. function Axis() {
  4113. }
  4114. return Axis;
  4115. }());
  4116. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4117. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4118. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4119. BABYLON.Axis = Axis;
  4120. ;
  4121. var BezierCurve = (function () {
  4122. function BezierCurve() {
  4123. }
  4124. /**
  4125. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4126. */
  4127. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4128. // Extract X (which is equal to time here)
  4129. var f0 = 1 - 3 * x2 + 3 * x1;
  4130. var f1 = 3 * x2 - 6 * x1;
  4131. var f2 = 3 * x1;
  4132. var refinedT = t;
  4133. for (var i = 0; i < 5; i++) {
  4134. var refinedT2 = refinedT * refinedT;
  4135. var refinedT3 = refinedT2 * refinedT;
  4136. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4137. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4138. refinedT -= (x - t) * slope;
  4139. refinedT = Math.min(1, Math.max(0, refinedT));
  4140. }
  4141. // Resolve cubic bezier for the given x
  4142. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4143. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4144. Math.pow(refinedT, 3);
  4145. };
  4146. return BezierCurve;
  4147. }());
  4148. BABYLON.BezierCurve = BezierCurve;
  4149. var Orientation;
  4150. (function (Orientation) {
  4151. Orientation[Orientation["CW"] = 0] = "CW";
  4152. Orientation[Orientation["CCW"] = 1] = "CCW";
  4153. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4154. var Angle = (function () {
  4155. /**
  4156. * Creates an Angle object of "radians" radians (float).
  4157. */
  4158. function Angle(radians) {
  4159. var _this = this;
  4160. /**
  4161. * Returns the Angle value in degrees (float).
  4162. */
  4163. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4164. /**
  4165. * Returns the Angle value in radians (float).
  4166. */
  4167. this.radians = function () { return _this._radians; };
  4168. this._radians = radians;
  4169. if (this._radians < 0.0)
  4170. this._radians += (2.0 * Math.PI);
  4171. }
  4172. /**
  4173. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4174. */
  4175. Angle.BetweenTwoPoints = function (a, b) {
  4176. var delta = b.subtract(a);
  4177. var theta = Math.atan2(delta.y, delta.x);
  4178. return new Angle(theta);
  4179. };
  4180. /**
  4181. * Returns a new Angle object from the passed float in radians.
  4182. */
  4183. Angle.FromRadians = function (radians) {
  4184. return new Angle(radians);
  4185. };
  4186. /**
  4187. * Returns a new Angle object from the passed float in degrees.
  4188. */
  4189. Angle.FromDegrees = function (degrees) {
  4190. return new Angle(degrees * Math.PI / 180.0);
  4191. };
  4192. return Angle;
  4193. }());
  4194. BABYLON.Angle = Angle;
  4195. var Arc2 = (function () {
  4196. /**
  4197. * Creates an Arc object from the three passed points : start, middle and end.
  4198. */
  4199. function Arc2(startPoint, midPoint, endPoint) {
  4200. this.startPoint = startPoint;
  4201. this.midPoint = midPoint;
  4202. this.endPoint = endPoint;
  4203. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4204. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4205. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4206. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4207. 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);
  4208. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4209. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4210. var a1 = this.startAngle.degrees();
  4211. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4212. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4213. // angles correction
  4214. if (a2 - a1 > +180.0)
  4215. a2 -= 360.0;
  4216. if (a2 - a1 < -180.0)
  4217. a2 += 360.0;
  4218. if (a3 - a2 > +180.0)
  4219. a3 -= 360.0;
  4220. if (a3 - a2 < -180.0)
  4221. a3 += 360.0;
  4222. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4223. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4224. }
  4225. return Arc2;
  4226. }());
  4227. BABYLON.Arc2 = Arc2;
  4228. var Path2 = (function () {
  4229. /**
  4230. * Creates a Path2 object from the starting 2D coordinates x and y.
  4231. */
  4232. function Path2(x, y) {
  4233. this._points = new Array();
  4234. this._length = 0.0;
  4235. this.closed = false;
  4236. this._points.push(new Vector2(x, y));
  4237. }
  4238. /**
  4239. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4240. * Returns the updated Path2.
  4241. */
  4242. Path2.prototype.addLineTo = function (x, y) {
  4243. if (closed) {
  4244. //Tools.Error("cannot add lines to closed paths");
  4245. return this;
  4246. }
  4247. var newPoint = new Vector2(x, y);
  4248. var previousPoint = this._points[this._points.length - 1];
  4249. this._points.push(newPoint);
  4250. this._length += newPoint.subtract(previousPoint).length();
  4251. return this;
  4252. };
  4253. /**
  4254. * 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.
  4255. * Returns the updated Path2.
  4256. */
  4257. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4258. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4259. if (closed) {
  4260. //Tools.Error("cannot add arcs to closed paths");
  4261. return this;
  4262. }
  4263. var startPoint = this._points[this._points.length - 1];
  4264. var midPoint = new Vector2(midX, midY);
  4265. var endPoint = new Vector2(endX, endY);
  4266. var arc = new Arc2(startPoint, midPoint, endPoint);
  4267. var increment = arc.angle.radians() / numberOfSegments;
  4268. if (arc.orientation === Orientation.CW)
  4269. increment *= -1;
  4270. var currentAngle = arc.startAngle.radians() + increment;
  4271. for (var i = 0; i < numberOfSegments; i++) {
  4272. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4273. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4274. this.addLineTo(x, y);
  4275. currentAngle += increment;
  4276. }
  4277. return this;
  4278. };
  4279. /**
  4280. * Closes the Path2.
  4281. * Returns the Path2.
  4282. */
  4283. Path2.prototype.close = function () {
  4284. this.closed = true;
  4285. return this;
  4286. };
  4287. /**
  4288. * Returns the Path2 total length (float).
  4289. */
  4290. Path2.prototype.length = function () {
  4291. var result = this._length;
  4292. if (!this.closed) {
  4293. var lastPoint = this._points[this._points.length - 1];
  4294. var firstPoint = this._points[0];
  4295. result += (firstPoint.subtract(lastPoint).length());
  4296. }
  4297. return result;
  4298. };
  4299. /**
  4300. * Returns the Path2 internal array of points.
  4301. */
  4302. Path2.prototype.getPoints = function () {
  4303. return this._points;
  4304. };
  4305. /**
  4306. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4307. */
  4308. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4309. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4310. //Tools.Error("normalized length position should be between 0 and 1.");
  4311. return Vector2.Zero();
  4312. }
  4313. var lengthPosition = normalizedLengthPosition * this.length();
  4314. var previousOffset = 0;
  4315. for (var i = 0; i < this._points.length; i++) {
  4316. var j = (i + 1) % this._points.length;
  4317. var a = this._points[i];
  4318. var b = this._points[j];
  4319. var bToA = b.subtract(a);
  4320. var nextOffset = (bToA.length() + previousOffset);
  4321. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4322. var dir = bToA.normalize();
  4323. var localOffset = lengthPosition - previousOffset;
  4324. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4325. }
  4326. previousOffset = nextOffset;
  4327. }
  4328. //Tools.Error("internal error");
  4329. return Vector2.Zero();
  4330. };
  4331. /**
  4332. * Returns a new Path2 starting at the coordinates (x, y).
  4333. */
  4334. Path2.StartingAt = function (x, y) {
  4335. return new Path2(x, y);
  4336. };
  4337. return Path2;
  4338. }());
  4339. BABYLON.Path2 = Path2;
  4340. var Path3D = (function () {
  4341. /**
  4342. * new Path3D(path, normal, raw)
  4343. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4344. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4345. * path : an array of Vector3, the curve axis of the Path3D
  4346. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4347. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4348. */
  4349. function Path3D(path, firstNormal, raw) {
  4350. this.path = path;
  4351. this._curve = new Array();
  4352. this._distances = new Array();
  4353. this._tangents = new Array();
  4354. this._normals = new Array();
  4355. this._binormals = new Array();
  4356. for (var p = 0; p < path.length; p++) {
  4357. this._curve[p] = path[p].clone(); // hard copy
  4358. }
  4359. this._raw = raw || false;
  4360. this._compute(firstNormal);
  4361. }
  4362. /**
  4363. * Returns the Path3D array of successive Vector3 designing its curve.
  4364. */
  4365. Path3D.prototype.getCurve = function () {
  4366. return this._curve;
  4367. };
  4368. /**
  4369. * Returns an array populated with tangent vectors on each Path3D curve point.
  4370. */
  4371. Path3D.prototype.getTangents = function () {
  4372. return this._tangents;
  4373. };
  4374. /**
  4375. * Returns an array populated with normal vectors on each Path3D curve point.
  4376. */
  4377. Path3D.prototype.getNormals = function () {
  4378. return this._normals;
  4379. };
  4380. /**
  4381. * Returns an array populated with binormal vectors on each Path3D curve point.
  4382. */
  4383. Path3D.prototype.getBinormals = function () {
  4384. return this._binormals;
  4385. };
  4386. /**
  4387. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4388. */
  4389. Path3D.prototype.getDistances = function () {
  4390. return this._distances;
  4391. };
  4392. /**
  4393. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4394. * Returns the same object updated.
  4395. */
  4396. Path3D.prototype.update = function (path, firstNormal) {
  4397. for (var p = 0; p < path.length; p++) {
  4398. this._curve[p].x = path[p].x;
  4399. this._curve[p].y = path[p].y;
  4400. this._curve[p].z = path[p].z;
  4401. }
  4402. this._compute(firstNormal);
  4403. return this;
  4404. };
  4405. // private function compute() : computes tangents, normals and binormals
  4406. Path3D.prototype._compute = function (firstNormal) {
  4407. var l = this._curve.length;
  4408. // first and last tangents
  4409. this._tangents[0] = this._getFirstNonNullVector(0);
  4410. if (!this._raw) {
  4411. this._tangents[0].normalize();
  4412. }
  4413. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4414. if (!this._raw) {
  4415. this._tangents[l - 1].normalize();
  4416. }
  4417. // normals and binormals at first point : arbitrary vector with _normalVector()
  4418. var tg0 = this._tangents[0];
  4419. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4420. this._normals[0] = pp0;
  4421. if (!this._raw) {
  4422. this._normals[0].normalize();
  4423. }
  4424. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4425. if (!this._raw) {
  4426. this._binormals[0].normalize();
  4427. }
  4428. this._distances[0] = 0.0;
  4429. // normals and binormals : next points
  4430. var prev; // previous vector (segment)
  4431. var cur; // current vector (segment)
  4432. var curTang; // current tangent
  4433. // previous normal
  4434. var prevBinor; // previous binormal
  4435. for (var i = 1; i < l; i++) {
  4436. // tangents
  4437. prev = this._getLastNonNullVector(i);
  4438. if (i < l - 1) {
  4439. cur = this._getFirstNonNullVector(i);
  4440. this._tangents[i] = prev.add(cur);
  4441. this._tangents[i].normalize();
  4442. }
  4443. this._distances[i] = this._distances[i - 1] + prev.length();
  4444. // normals and binormals
  4445. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4446. curTang = this._tangents[i];
  4447. prevBinor = this._binormals[i - 1];
  4448. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4449. if (!this._raw) {
  4450. this._normals[i].normalize();
  4451. }
  4452. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4453. if (!this._raw) {
  4454. this._binormals[i].normalize();
  4455. }
  4456. }
  4457. };
  4458. // private function getFirstNonNullVector(index)
  4459. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4460. Path3D.prototype._getFirstNonNullVector = function (index) {
  4461. var i = 1;
  4462. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4463. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4464. i++;
  4465. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4466. }
  4467. return nNVector;
  4468. };
  4469. // private function getLastNonNullVector(index)
  4470. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4471. Path3D.prototype._getLastNonNullVector = function (index) {
  4472. var i = 1;
  4473. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4474. while (nLVector.length() === 0 && index > i + 1) {
  4475. i++;
  4476. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4477. }
  4478. return nLVector;
  4479. };
  4480. // private function normalVector(v0, vt, va) :
  4481. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4482. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4483. Path3D.prototype._normalVector = function (v0, vt, va) {
  4484. var normal0;
  4485. var tgl = vt.length();
  4486. if (tgl === 0.0) {
  4487. tgl = 1.0;
  4488. }
  4489. if (va === undefined || va === null) {
  4490. var point;
  4491. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4492. point = new Vector3(0.0, -1.0, 0.0);
  4493. }
  4494. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4495. point = new Vector3(1.0, 0.0, 0.0);
  4496. }
  4497. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4498. point = new Vector3(0.0, 0.0, 1.0);
  4499. }
  4500. normal0 = Vector3.Cross(vt, point);
  4501. }
  4502. else {
  4503. normal0 = Vector3.Cross(vt, va);
  4504. Vector3.CrossToRef(normal0, vt, normal0);
  4505. }
  4506. normal0.normalize();
  4507. return normal0;
  4508. };
  4509. return Path3D;
  4510. }());
  4511. BABYLON.Path3D = Path3D;
  4512. var Curve3 = (function () {
  4513. /**
  4514. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4515. * A Curve3 is designed from a series of successive Vector3.
  4516. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4517. */
  4518. function Curve3(points) {
  4519. this._length = 0.0;
  4520. this._points = points;
  4521. this._length = this._computeLength(points);
  4522. }
  4523. /**
  4524. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4525. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4526. * @param v1 (Vector3) the control point
  4527. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4528. * @param nbPoints (integer) the wanted number of points in the curve
  4529. */
  4530. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4531. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4532. var bez = new Array();
  4533. var equation = function (t, val0, val1, val2) {
  4534. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4535. return res;
  4536. };
  4537. for (var i = 0; i <= nbPoints; i++) {
  4538. 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)));
  4539. }
  4540. return new Curve3(bez);
  4541. };
  4542. /**
  4543. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4544. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4545. * @param v1 (Vector3) the first control point
  4546. * @param v2 (Vector3) the second control point
  4547. * @param v3 (Vector3) the end point of the Cubic Bezier
  4548. * @param nbPoints (integer) the wanted number of points in the curve
  4549. */
  4550. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4551. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4552. var bez = new Array();
  4553. var equation = function (t, val0, val1, val2, val3) {
  4554. 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;
  4555. return res;
  4556. };
  4557. for (var i = 0; i <= nbPoints; i++) {
  4558. 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)));
  4559. }
  4560. return new Curve3(bez);
  4561. };
  4562. /**
  4563. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4564. * @param p1 (Vector3) the origin point of the Hermite Spline
  4565. * @param t1 (Vector3) the tangent vector at the origin point
  4566. * @param p2 (Vector3) the end point of the Hermite Spline
  4567. * @param t2 (Vector3) the tangent vector at the end point
  4568. * @param nbPoints (integer) the wanted number of points in the curve
  4569. */
  4570. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4571. var hermite = new Array();
  4572. var step = 1.0 / nbPoints;
  4573. for (var i = 0; i <= nbPoints; i++) {
  4574. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4575. }
  4576. return new Curve3(hermite);
  4577. };
  4578. /**
  4579. * Returns a Curve3 object along a CatmullRom Spline curve :
  4580. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4581. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4582. */
  4583. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4584. var totalPoints = new Array();
  4585. totalPoints.push(points[0].clone());
  4586. Array.prototype.push.apply(totalPoints, points);
  4587. totalPoints.push(points[points.length - 1].clone());
  4588. var catmullRom = new Array();
  4589. var step = 1.0 / nbPoints;
  4590. for (var i = 0; i < totalPoints.length - 3; i++) {
  4591. var amount = 0.0;
  4592. for (var c = 0; c < nbPoints; c++) {
  4593. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4594. amount += step;
  4595. }
  4596. }
  4597. i--;
  4598. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4599. return new Curve3(catmullRom);
  4600. };
  4601. /**
  4602. * Returns the Curve3 stored array of successive Vector3
  4603. */
  4604. Curve3.prototype.getPoints = function () {
  4605. return this._points;
  4606. };
  4607. /**
  4608. * Returns the computed length (float) of the curve.
  4609. */
  4610. Curve3.prototype.length = function () {
  4611. return this._length;
  4612. };
  4613. /**
  4614. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4615. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4616. * curveA and curveB keep unchanged.
  4617. */
  4618. Curve3.prototype.continue = function (curve) {
  4619. var lastPoint = this._points[this._points.length - 1];
  4620. var continuedPoints = this._points.slice();
  4621. var curvePoints = curve.getPoints();
  4622. for (var i = 1; i < curvePoints.length; i++) {
  4623. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4624. }
  4625. var continuedCurve = new Curve3(continuedPoints);
  4626. return continuedCurve;
  4627. };
  4628. Curve3.prototype._computeLength = function (path) {
  4629. var l = 0;
  4630. for (var i = 1; i < path.length; i++) {
  4631. l += (path[i].subtract(path[i - 1])).length();
  4632. }
  4633. return l;
  4634. };
  4635. return Curve3;
  4636. }());
  4637. BABYLON.Curve3 = Curve3;
  4638. // Vertex formats
  4639. var PositionNormalVertex = (function () {
  4640. function PositionNormalVertex(position, normal) {
  4641. if (position === void 0) { position = Vector3.Zero(); }
  4642. if (normal === void 0) { normal = Vector3.Up(); }
  4643. this.position = position;
  4644. this.normal = normal;
  4645. }
  4646. PositionNormalVertex.prototype.clone = function () {
  4647. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4648. };
  4649. return PositionNormalVertex;
  4650. }());
  4651. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4652. var PositionNormalTextureVertex = (function () {
  4653. function PositionNormalTextureVertex(position, normal, uv) {
  4654. if (position === void 0) { position = Vector3.Zero(); }
  4655. if (normal === void 0) { normal = Vector3.Up(); }
  4656. if (uv === void 0) { uv = Vector2.Zero(); }
  4657. this.position = position;
  4658. this.normal = normal;
  4659. this.uv = uv;
  4660. }
  4661. PositionNormalTextureVertex.prototype.clone = function () {
  4662. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4663. };
  4664. return PositionNormalTextureVertex;
  4665. }());
  4666. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4667. // Temporary pre-allocated objects for engine internal use
  4668. // usage in any internal function :
  4669. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4670. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4671. var Tmp = (function () {
  4672. function Tmp() {
  4673. }
  4674. return Tmp;
  4675. }());
  4676. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4677. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4678. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4679. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4680. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4681. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4682. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4683. Matrix.Zero(), Matrix.Zero(),
  4684. Matrix.Zero(), Matrix.Zero(),
  4685. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4686. BABYLON.Tmp = Tmp;
  4687. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4688. var MathTmp = (function () {
  4689. function MathTmp() {
  4690. }
  4691. return MathTmp;
  4692. }());
  4693. MathTmp.Vector3 = [Vector3.Zero()];
  4694. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4695. MathTmp.Quaternion = [Quaternion.Zero()];
  4696. })(BABYLON || (BABYLON = {}));
  4697. //# sourceMappingURL=babylon.math.js.map
  4698. //# sourceMappingURL=babylon.mixins.js.map
  4699. var BABYLON;
  4700. (function (BABYLON) {
  4701. function generateSerializableMember(type, sourceName) {
  4702. return function (target, propertyKey) {
  4703. if (!target.__serializableMembers) {
  4704. target.__serializableMembers = {};
  4705. }
  4706. if (!target.__serializableMembers[propertyKey]) {
  4707. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4708. }
  4709. };
  4710. }
  4711. function generateExpandMember(setCallback, targetKey) {
  4712. return function (target, propertyKey) {
  4713. var key = targetKey || ("_" + propertyKey);
  4714. Object.defineProperty(target, propertyKey, {
  4715. get: function () {
  4716. return this[key];
  4717. },
  4718. set: function (value) {
  4719. if (this[key] === value) {
  4720. return;
  4721. }
  4722. this[key] = value;
  4723. target[setCallback].apply(this);
  4724. },
  4725. enumerable: true,
  4726. configurable: true
  4727. });
  4728. };
  4729. }
  4730. function expandToProperty(callback, targetKey) {
  4731. return generateExpandMember(callback, targetKey);
  4732. }
  4733. BABYLON.expandToProperty = expandToProperty;
  4734. function serialize(sourceName) {
  4735. return generateSerializableMember(0, sourceName); // value member
  4736. }
  4737. BABYLON.serialize = serialize;
  4738. function serializeAsTexture(sourceName) {
  4739. return generateSerializableMember(1, sourceName); // texture member
  4740. }
  4741. BABYLON.serializeAsTexture = serializeAsTexture;
  4742. function serializeAsColor3(sourceName) {
  4743. return generateSerializableMember(2, sourceName); // color3 member
  4744. }
  4745. BABYLON.serializeAsColor3 = serializeAsColor3;
  4746. function serializeAsFresnelParameters(sourceName) {
  4747. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4748. }
  4749. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4750. function serializeAsVector2(sourceName) {
  4751. return generateSerializableMember(4, sourceName); // vector2 member
  4752. }
  4753. BABYLON.serializeAsVector2 = serializeAsVector2;
  4754. function serializeAsVector3(sourceName) {
  4755. return generateSerializableMember(5, sourceName); // vector3 member
  4756. }
  4757. BABYLON.serializeAsVector3 = serializeAsVector3;
  4758. function serializeAsMeshReference(sourceName) {
  4759. return generateSerializableMember(6, sourceName); // mesh reference member
  4760. }
  4761. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4762. function serializeAsColorCurves(sourceName) {
  4763. return generateSerializableMember(7, sourceName); // color curves
  4764. }
  4765. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4766. function serializeAsColor4(sourceName) {
  4767. return generateSerializableMember(8, sourceName); // color 4
  4768. }
  4769. BABYLON.serializeAsColor4 = serializeAsColor4;
  4770. function serializeAsImageProcessingConfiguration(sourceName) {
  4771. return generateSerializableMember(9, sourceName); // image processing
  4772. }
  4773. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4774. var SerializationHelper = (function () {
  4775. function SerializationHelper() {
  4776. }
  4777. SerializationHelper.Serialize = function (entity, serializationObject) {
  4778. if (!serializationObject) {
  4779. serializationObject = {};
  4780. }
  4781. // Tags
  4782. if (BABYLON.Tags) {
  4783. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4784. }
  4785. // Properties
  4786. for (var property in entity.__serializableMembers) {
  4787. var propertyDescriptor = entity.__serializableMembers[property];
  4788. var targetPropertyName = propertyDescriptor.sourceName || property;
  4789. var propertyType = propertyDescriptor.type;
  4790. var sourceProperty = entity[property];
  4791. if (sourceProperty !== undefined && sourceProperty !== null) {
  4792. switch (propertyType) {
  4793. case 0:
  4794. serializationObject[targetPropertyName] = sourceProperty;
  4795. break;
  4796. case 1:
  4797. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4798. break;
  4799. case 2:
  4800. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4801. break;
  4802. case 3:
  4803. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4804. break;
  4805. case 4:
  4806. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4807. break;
  4808. case 5:
  4809. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4810. break;
  4811. case 6:
  4812. serializationObject[targetPropertyName] = sourceProperty.id;
  4813. break;
  4814. case 7:
  4815. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4816. break;
  4817. case 8:
  4818. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4819. break;
  4820. case 9:
  4821. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4822. break;
  4823. }
  4824. }
  4825. }
  4826. return serializationObject;
  4827. };
  4828. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4829. var destination = creationFunction();
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4833. }
  4834. // Properties
  4835. for (var property in destination.__serializableMembers) {
  4836. var propertyDescriptor = destination.__serializableMembers[property];
  4837. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4838. var propertyType = propertyDescriptor.type;
  4839. if (sourceProperty !== undefined && sourceProperty !== null) {
  4840. switch (propertyType) {
  4841. case 0:
  4842. destination[property] = sourceProperty;
  4843. break;
  4844. case 1:
  4845. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4846. break;
  4847. case 2:
  4848. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4849. break;
  4850. case 3:
  4851. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4852. break;
  4853. case 4:
  4854. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4855. break;
  4856. case 5:
  4857. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4858. break;
  4859. case 6:
  4860. destination[property] = scene.getLastMeshByID(sourceProperty);
  4861. break;
  4862. case 7:
  4863. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4864. break;
  4865. case 8:
  4866. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4867. break;
  4868. case 9:
  4869. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4870. break;
  4871. }
  4872. }
  4873. }
  4874. return destination;
  4875. };
  4876. SerializationHelper.Clone = function (creationFunction, source) {
  4877. var destination = creationFunction();
  4878. // Tags
  4879. if (BABYLON.Tags) {
  4880. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4881. }
  4882. // Properties
  4883. for (var property in destination.__serializableMembers) {
  4884. var propertyDescriptor = destination.__serializableMembers[property];
  4885. var sourceProperty = source[property];
  4886. var propertyType = propertyDescriptor.type;
  4887. if (sourceProperty !== undefined && sourceProperty !== null) {
  4888. switch (propertyType) {
  4889. case 0: // Value
  4890. case 6:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1: // Texture
  4894. case 2: // Color3
  4895. case 3: // FresnelParameters
  4896. case 4: // Vector2
  4897. case 5: // Vector3
  4898. case 7:
  4899. destination[property] = sourceProperty.clone();
  4900. break;
  4901. }
  4902. }
  4903. }
  4904. return destination;
  4905. };
  4906. return SerializationHelper;
  4907. }());
  4908. BABYLON.SerializationHelper = SerializationHelper;
  4909. })(BABYLON || (BABYLON = {}));
  4910. //# sourceMappingURL=babylon.decorators.js.map
  4911. var BABYLON;
  4912. (function (BABYLON) {
  4913. /**
  4914. * A class serves as a medium between the observable and its observers
  4915. */
  4916. var EventState = (function () {
  4917. /**
  4918. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4919. */
  4920. function EventState(mask, skipNextObservers) {
  4921. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4922. this.initalize(mask, skipNextObservers);
  4923. }
  4924. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4925. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4926. this.mask = mask;
  4927. this.skipNextObservers = skipNextObservers;
  4928. return this;
  4929. };
  4930. return EventState;
  4931. }());
  4932. BABYLON.EventState = EventState;
  4933. /**
  4934. * Represent an Observer registered to a given Observable object.
  4935. */
  4936. var Observer = (function () {
  4937. function Observer(callback, mask) {
  4938. this.callback = callback;
  4939. this.mask = mask;
  4940. }
  4941. return Observer;
  4942. }());
  4943. BABYLON.Observer = Observer;
  4944. /**
  4945. * The Observable class is a simple implementation of the Observable pattern.
  4946. * 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.
  4947. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4948. * 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).
  4949. * 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.
  4950. */
  4951. var Observable = (function () {
  4952. function Observable() {
  4953. this._observers = new Array();
  4954. this._eventState = new EventState(0);
  4955. }
  4956. /**
  4957. * Create a new Observer with the specified callback
  4958. * @param callback the callback that will be executed for that Observer
  4959. * @param mask the mask used to filter observers
  4960. * @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.
  4961. */
  4962. Observable.prototype.add = function (callback, mask, insertFirst) {
  4963. if (mask === void 0) { mask = -1; }
  4964. if (insertFirst === void 0) { insertFirst = false; }
  4965. if (!callback) {
  4966. return null;
  4967. }
  4968. var observer = new Observer(callback, mask);
  4969. if (insertFirst) {
  4970. this._observers.unshift(observer);
  4971. }
  4972. else {
  4973. this._observers.push(observer);
  4974. }
  4975. return observer;
  4976. };
  4977. /**
  4978. * Remove an Observer from the Observable object
  4979. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4980. */
  4981. Observable.prototype.remove = function (observer) {
  4982. var index = this._observers.indexOf(observer);
  4983. if (index !== -1) {
  4984. this._observers.splice(index, 1);
  4985. return true;
  4986. }
  4987. return false;
  4988. };
  4989. /**
  4990. * Remove a callback from the Observable object
  4991. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4992. */
  4993. Observable.prototype.removeCallback = function (callback) {
  4994. for (var index = 0; index < this._observers.length; index++) {
  4995. if (this._observers[index].callback === callback) {
  4996. this._observers.splice(index, 1);
  4997. return true;
  4998. }
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Notify all Observers by calling their respective callback with the given data
  5004. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5005. * @param eventData
  5006. * @param mask
  5007. */
  5008. Observable.prototype.notifyObservers = function (eventData, mask) {
  5009. if (mask === void 0) { mask = -1; }
  5010. var state = this._eventState;
  5011. state.mask = mask;
  5012. state.skipNextObservers = false;
  5013. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5014. var obs = _a[_i];
  5015. if (obs.mask & mask) {
  5016. obs.callback(eventData, state);
  5017. }
  5018. if (state.skipNextObservers) {
  5019. return false;
  5020. }
  5021. }
  5022. return true;
  5023. };
  5024. /**
  5025. * return true is the Observable has at least one Observer registered
  5026. */
  5027. Observable.prototype.hasObservers = function () {
  5028. return this._observers.length > 0;
  5029. };
  5030. /**
  5031. * Clear the list of observers
  5032. */
  5033. Observable.prototype.clear = function () {
  5034. this._observers = new Array();
  5035. };
  5036. /**
  5037. * Clone the current observable
  5038. */
  5039. Observable.prototype.clone = function () {
  5040. var result = new Observable();
  5041. result._observers = this._observers.slice(0);
  5042. return result;
  5043. };
  5044. /**
  5045. * Does this observable handles observer registered with a given mask
  5046. * @param {number} trigger - the mask to be tested
  5047. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5048. **/
  5049. Observable.prototype.hasSpecificMask = function (mask) {
  5050. if (mask === void 0) { mask = -1; }
  5051. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5052. var obs = _a[_i];
  5053. if (obs.mask & mask && obs.mask === mask) {
  5054. return true;
  5055. }
  5056. }
  5057. return false;
  5058. };
  5059. return Observable;
  5060. }());
  5061. BABYLON.Observable = Observable;
  5062. })(BABYLON || (BABYLON = {}));
  5063. //# sourceMappingURL=babylon.observable.js.map
  5064. var BABYLON;
  5065. (function (BABYLON) {
  5066. var SmartArray = (function () {
  5067. function SmartArray(capacity) {
  5068. this.length = 0;
  5069. this._duplicateId = 0;
  5070. this.data = new Array(capacity);
  5071. this._id = SmartArray._GlobalId++;
  5072. }
  5073. SmartArray.prototype.push = function (value) {
  5074. this.data[this.length++] = value;
  5075. if (this.length > this.data.length) {
  5076. this.data.length *= 2;
  5077. }
  5078. if (!value.__smartArrayFlags) {
  5079. value.__smartArrayFlags = {};
  5080. }
  5081. value.__smartArrayFlags[this._id] = this._duplicateId;
  5082. };
  5083. SmartArray.prototype.forEach = function (func) {
  5084. for (var index = 0; index < this.length; index++) {
  5085. func(this.data[index]);
  5086. }
  5087. };
  5088. SmartArray.prototype.pushNoDuplicate = function (value) {
  5089. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5090. return false;
  5091. }
  5092. this.push(value);
  5093. return true;
  5094. };
  5095. SmartArray.prototype.sort = function (compareFn) {
  5096. this.data.sort(compareFn);
  5097. };
  5098. SmartArray.prototype.reset = function () {
  5099. this.length = 0;
  5100. this._duplicateId++;
  5101. };
  5102. SmartArray.prototype.dispose = function () {
  5103. this.reset();
  5104. this.data.length = 0;
  5105. };
  5106. SmartArray.prototype.concat = function (array) {
  5107. if (array.length === 0) {
  5108. return;
  5109. }
  5110. if (this.length + array.length > this.data.length) {
  5111. this.data.length = (this.length + array.length) * 2;
  5112. }
  5113. for (var index = 0; index < array.length; index++) {
  5114. this.data[this.length++] = (array.data || array)[index];
  5115. }
  5116. };
  5117. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5118. if (array.length === 0) {
  5119. return;
  5120. }
  5121. if (this.length + array.length > this.data.length) {
  5122. this.data.length = (this.length + array.length) * 2;
  5123. }
  5124. for (var index = 0; index < array.length; index++) {
  5125. var item = (array.data || array)[index];
  5126. this.pushNoDuplicate(item);
  5127. }
  5128. };
  5129. SmartArray.prototype.indexOf = function (value) {
  5130. var position = this.data.indexOf(value);
  5131. if (position >= this.length) {
  5132. return -1;
  5133. }
  5134. return position;
  5135. };
  5136. SmartArray.prototype.contains = function (value) {
  5137. return this.data.indexOf(value) !== -1;
  5138. };
  5139. return SmartArray;
  5140. }());
  5141. // Statics
  5142. SmartArray._GlobalId = 0;
  5143. BABYLON.SmartArray = SmartArray;
  5144. })(BABYLON || (BABYLON = {}));
  5145. //# sourceMappingURL=babylon.smartArray.js.map
  5146. var BABYLON;
  5147. (function (BABYLON) {
  5148. // Screenshots
  5149. var screenshotCanvas;
  5150. var cloneValue = function (source, destinationObject) {
  5151. if (!source)
  5152. return null;
  5153. if (source instanceof BABYLON.Mesh) {
  5154. return null;
  5155. }
  5156. if (source instanceof BABYLON.SubMesh) {
  5157. return source.clone(destinationObject);
  5158. }
  5159. else if (source.clone) {
  5160. return source.clone();
  5161. }
  5162. return null;
  5163. };
  5164. var Tools = (function () {
  5165. function Tools() {
  5166. }
  5167. ;
  5168. /**
  5169. * Interpolates between a and b via alpha
  5170. * @param a The lower value (returned when alpha = 0)
  5171. * @param b The upper value (returned when alpha = 1)
  5172. * @param alpha The interpolation-factor
  5173. * @return The mixed value
  5174. */
  5175. Tools.Mix = function (a, b, alpha) {
  5176. return a * (1 - alpha) + b * alpha;
  5177. };
  5178. Tools.Instantiate = function (className) {
  5179. var arr = className.split(".");
  5180. var fn = (window || this);
  5181. for (var i = 0, len = arr.length; i < len; i++) {
  5182. fn = fn[arr[i]];
  5183. }
  5184. if (typeof fn !== "function") {
  5185. return null;
  5186. }
  5187. return fn;
  5188. };
  5189. Tools.SetImmediate = function (action) {
  5190. if (window.setImmediate) {
  5191. window.setImmediate(action);
  5192. }
  5193. else {
  5194. setTimeout(action, 1);
  5195. }
  5196. };
  5197. Tools.IsExponentOfTwo = function (value) {
  5198. var count = 1;
  5199. do {
  5200. count *= 2;
  5201. } while (count < value);
  5202. return count === value;
  5203. };
  5204. /**
  5205. * Find the next highest power of two.
  5206. * @param x Number to start search from.
  5207. * @return Next highest power of two.
  5208. */
  5209. Tools.CeilingPOT = function (x) {
  5210. x--;
  5211. x |= x >> 1;
  5212. x |= x >> 2;
  5213. x |= x >> 4;
  5214. x |= x >> 8;
  5215. x |= x >> 16;
  5216. x++;
  5217. return x;
  5218. };
  5219. /**
  5220. * Find the next lowest power of two.
  5221. * @param x Number to start search from.
  5222. * @return Next lowest power of two.
  5223. */
  5224. Tools.FloorPOT = function (x) {
  5225. x = x | (x >> 1);
  5226. x = x | (x >> 2);
  5227. x = x | (x >> 4);
  5228. x = x | (x >> 8);
  5229. x = x | (x >> 16);
  5230. return x - (x >> 1);
  5231. };
  5232. /**
  5233. * Find the nearest power of two.
  5234. * @param x Number to start search from.
  5235. * @return Next nearest power of two.
  5236. */
  5237. Tools.NearestPOT = function (x) {
  5238. var c = Tools.CeilingPOT(x);
  5239. var f = Tools.FloorPOT(x);
  5240. return (c - x) > (x - f) ? f : c;
  5241. };
  5242. Tools.GetExponentOfTwo = function (value, max, mode) {
  5243. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5244. var pot;
  5245. switch (mode) {
  5246. case BABYLON.Engine.SCALEMODE_FLOOR:
  5247. pot = Tools.FloorPOT(value);
  5248. break;
  5249. case BABYLON.Engine.SCALEMODE_NEAREST:
  5250. pot = Tools.NearestPOT(value);
  5251. break;
  5252. case BABYLON.Engine.SCALEMODE_CEILING:
  5253. pot = Tools.CeilingPOT(value);
  5254. break;
  5255. }
  5256. return Math.min(pot, max);
  5257. };
  5258. Tools.GetFilename = function (path) {
  5259. var index = path.lastIndexOf("/");
  5260. if (index < 0)
  5261. return path;
  5262. return path.substring(index + 1);
  5263. };
  5264. Tools.GetDOMTextContent = function (element) {
  5265. var result = "";
  5266. var child = element.firstChild;
  5267. while (child) {
  5268. if (child.nodeType === 3) {
  5269. result += child.textContent;
  5270. }
  5271. child = child.nextSibling;
  5272. }
  5273. return result;
  5274. };
  5275. Tools.ToDegrees = function (angle) {
  5276. return angle * 180 / Math.PI;
  5277. };
  5278. Tools.ToRadians = function (angle) {
  5279. return angle * Math.PI / 180;
  5280. };
  5281. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5282. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5283. var output = "";
  5284. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5285. var i = 0;
  5286. var bytes = new Uint8Array(buffer);
  5287. while (i < bytes.length) {
  5288. chr1 = bytes[i++];
  5289. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5290. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5291. enc1 = chr1 >> 2;
  5292. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5293. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5294. enc4 = chr3 & 63;
  5295. if (isNaN(chr2)) {
  5296. enc3 = enc4 = 64;
  5297. }
  5298. else if (isNaN(chr3)) {
  5299. enc4 = 64;
  5300. }
  5301. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5302. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5303. }
  5304. return "data:image/png;base64," + output;
  5305. };
  5306. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5307. if (bias === void 0) { bias = null; }
  5308. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5309. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5310. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5311. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5312. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5313. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5314. }
  5315. if (bias) {
  5316. minimum.x -= minimum.x * bias.x + bias.y;
  5317. minimum.y -= minimum.y * bias.x + bias.y;
  5318. minimum.z -= minimum.z * bias.x + bias.y;
  5319. maximum.x += maximum.x * bias.x + bias.y;
  5320. maximum.y += maximum.y * bias.x + bias.y;
  5321. maximum.z += maximum.z * bias.x + bias.y;
  5322. }
  5323. return {
  5324. minimum: minimum,
  5325. maximum: maximum
  5326. };
  5327. };
  5328. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5329. if (bias === void 0) { bias = null; }
  5330. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5331. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5332. if (!stride) {
  5333. stride = 3;
  5334. }
  5335. for (var index = start; index < start + count; index++) {
  5336. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5337. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5338. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5339. }
  5340. if (bias) {
  5341. minimum.x -= minimum.x * bias.x + bias.y;
  5342. minimum.y -= minimum.y * bias.x + bias.y;
  5343. minimum.z -= minimum.z * bias.x + bias.y;
  5344. maximum.x += maximum.x * bias.x + bias.y;
  5345. maximum.y += maximum.y * bias.x + bias.y;
  5346. maximum.z += maximum.z * bias.x + bias.y;
  5347. }
  5348. return {
  5349. minimum: minimum,
  5350. maximum: maximum
  5351. };
  5352. };
  5353. Tools.Vector2ArrayFeeder = function (array) {
  5354. return function (index) {
  5355. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5356. var length = isFloatArray ? array.length / 2 : array.length;
  5357. if (index >= length) {
  5358. return null;
  5359. }
  5360. if (isFloatArray) {
  5361. var fa = array;
  5362. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5363. }
  5364. var a = array;
  5365. return a[index];
  5366. };
  5367. };
  5368. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5369. if (bias === void 0) { bias = null; }
  5370. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5371. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5372. var i = 0;
  5373. var cur = feeder(i++);
  5374. while (cur) {
  5375. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5376. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5377. cur = feeder(i++);
  5378. }
  5379. if (bias) {
  5380. minimum.x -= minimum.x * bias.x + bias.y;
  5381. minimum.y -= minimum.y * bias.x + bias.y;
  5382. maximum.x += maximum.x * bias.x + bias.y;
  5383. maximum.y += maximum.y * bias.x + bias.y;
  5384. }
  5385. return {
  5386. minimum: minimum,
  5387. maximum: maximum
  5388. };
  5389. };
  5390. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5391. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5392. return undefined;
  5393. return Array.isArray(obj) ? obj : [obj];
  5394. };
  5395. // Misc.
  5396. Tools.GetPointerPrefix = function () {
  5397. var eventPrefix = "pointer";
  5398. // Check if pointer events are supported
  5399. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5400. eventPrefix = "mouse";
  5401. }
  5402. return eventPrefix;
  5403. };
  5404. /**
  5405. * @param func - the function to be called
  5406. * @param requester - the object that will request the next frame. Falls back to window.
  5407. */
  5408. Tools.QueueNewFrame = function (func, requester) {
  5409. if (requester === void 0) { requester = window; }
  5410. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5411. /*if(requester.isPresenting) {
  5412. return;
  5413. } else*/ if (requester.requestAnimationFrame)
  5414. requester.requestAnimationFrame(func);
  5415. else if (requester.msRequestAnimationFrame)
  5416. requester.msRequestAnimationFrame(func);
  5417. else if (requester.webkitRequestAnimationFrame)
  5418. requester.webkitRequestAnimationFrame(func);
  5419. else if (requester.mozRequestAnimationFrame)
  5420. requester.mozRequestAnimationFrame(func);
  5421. else if (requester.oRequestAnimationFrame)
  5422. requester.oRequestAnimationFrame(func);
  5423. else {
  5424. window.setTimeout(func, 16);
  5425. }
  5426. };
  5427. Tools.RequestFullscreen = function (element) {
  5428. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5429. if (!requestFunction)
  5430. return;
  5431. requestFunction.call(element);
  5432. };
  5433. Tools.ExitFullscreen = function () {
  5434. if (document.exitFullscreen) {
  5435. document.exitFullscreen();
  5436. }
  5437. else if (document.mozCancelFullScreen) {
  5438. document.mozCancelFullScreen();
  5439. }
  5440. else if (document.webkitCancelFullScreen) {
  5441. document.webkitCancelFullScreen();
  5442. }
  5443. else if (document.msCancelFullScreen) {
  5444. document.msCancelFullScreen();
  5445. }
  5446. };
  5447. Tools.SetCorsBehavior = function (url, img) {
  5448. if (Tools.CorsBehavior) {
  5449. switch (typeof (Tools.CorsBehavior)) {
  5450. case "function":
  5451. var result = Tools.CorsBehavior(url);
  5452. if (result) {
  5453. img.crossOrigin = result;
  5454. }
  5455. break;
  5456. case "string":
  5457. default:
  5458. img.crossOrigin = Tools.CorsBehavior;
  5459. break;
  5460. }
  5461. }
  5462. };
  5463. // External files
  5464. Tools.CleanUrl = function (url) {
  5465. url = url.replace(/#/mg, "%23");
  5466. return url;
  5467. };
  5468. Tools.LoadImage = function (url, onload, onerror, database) {
  5469. if (url instanceof ArrayBuffer) {
  5470. url = Tools.EncodeArrayBufferTobase64(url);
  5471. }
  5472. url = Tools.CleanUrl(url);
  5473. var img = new Image();
  5474. if (url.substr(0, 5) !== "data:") {
  5475. Tools.SetCorsBehavior(url, img);
  5476. }
  5477. img.onload = function () {
  5478. onload(img);
  5479. };
  5480. img.onerror = function (err) {
  5481. Tools.Error("Error while trying to load image: " + url);
  5482. if (Tools.UseFallbackTexture) {
  5483. img.src = Tools.fallbackTexture;
  5484. onload(img);
  5485. }
  5486. else {
  5487. onerror();
  5488. }
  5489. };
  5490. var noIndexedDB = function () {
  5491. img.src = url;
  5492. };
  5493. var loadFromIndexedDB = function () {
  5494. database.loadImageFromDB(url, img);
  5495. };
  5496. //ANY database to do!
  5497. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5498. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5499. }
  5500. else {
  5501. if (url.indexOf("file:") !== 0) {
  5502. noIndexedDB();
  5503. }
  5504. else {
  5505. var textureName = url.substring(5).toLowerCase();
  5506. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5507. try {
  5508. var blobURL;
  5509. try {
  5510. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5511. }
  5512. catch (ex) {
  5513. // Chrome doesn't support oneTimeOnly parameter
  5514. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5515. }
  5516. img.src = blobURL;
  5517. }
  5518. catch (e) {
  5519. img.src = null;
  5520. }
  5521. }
  5522. else {
  5523. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5524. img.src = Tools.fallbackTexture;
  5525. }
  5526. }
  5527. }
  5528. return img;
  5529. };
  5530. //ANY
  5531. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5532. url = Tools.CleanUrl(url);
  5533. var noIndexedDB = function () {
  5534. var request = new XMLHttpRequest();
  5535. var loadUrl = Tools.BaseUrl + url;
  5536. request.open('GET', loadUrl, true);
  5537. if (useArrayBuffer) {
  5538. request.responseType = "arraybuffer";
  5539. }
  5540. request.onprogress = progressCallBack;
  5541. request.onreadystatechange = function () {
  5542. // In case of undefined state in some browsers.
  5543. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5544. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5545. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5546. callback(!useArrayBuffer ? request.responseText : request.response);
  5547. }
  5548. else {
  5549. if (onError) {
  5550. onError(request);
  5551. }
  5552. else {
  5553. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5554. }
  5555. }
  5556. }
  5557. };
  5558. request.send(null);
  5559. };
  5560. var loadFromIndexedDB = function () {
  5561. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5562. };
  5563. if (url.indexOf("file:") !== -1) {
  5564. var fileName = url.substring(5).toLowerCase();
  5565. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5566. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5567. }
  5568. else {
  5569. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5570. }
  5571. }
  5572. else {
  5573. // Caching all files
  5574. if (database && database.enableSceneOffline) {
  5575. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5576. }
  5577. else {
  5578. noIndexedDB();
  5579. }
  5580. }
  5581. };
  5582. /**
  5583. * Load a script (identified by an url). When the url returns, the
  5584. * content of this file is added into a new script element, attached to the DOM (body element)
  5585. */
  5586. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5587. var head = document.getElementsByTagName('head')[0];
  5588. var script = document.createElement('script');
  5589. script.type = 'text/javascript';
  5590. script.src = scriptUrl;
  5591. var self = this;
  5592. script.onload = function () {
  5593. if (onSuccess) {
  5594. onSuccess();
  5595. }
  5596. };
  5597. script.onerror = function () {
  5598. if (onError) {
  5599. onError();
  5600. }
  5601. };
  5602. head.appendChild(script);
  5603. };
  5604. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5605. var reader = new FileReader();
  5606. reader.onload = function (e) {
  5607. //target doesn't have result from ts 1.3
  5608. callback(e.target['result']);
  5609. };
  5610. reader.onprogress = progressCallback;
  5611. reader.readAsDataURL(fileToLoad);
  5612. };
  5613. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5614. var reader = new FileReader();
  5615. reader.onerror = function (e) {
  5616. Tools.Log("Error while reading file: " + fileToLoad.name);
  5617. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5618. };
  5619. reader.onload = function (e) {
  5620. //target doesn't have result from ts 1.3
  5621. callback(e.target['result']);
  5622. };
  5623. reader.onprogress = progressCallBack;
  5624. if (!useArrayBuffer) {
  5625. // Asynchronous read
  5626. reader.readAsText(fileToLoad);
  5627. }
  5628. else {
  5629. reader.readAsArrayBuffer(fileToLoad);
  5630. }
  5631. };
  5632. //returns a downloadable url to a file content.
  5633. Tools.FileAsURL = function (content) {
  5634. var fileBlob = new Blob([content]);
  5635. var url = window.URL || window.webkitURL;
  5636. var link = url.createObjectURL(fileBlob);
  5637. return link;
  5638. };
  5639. // Misc.
  5640. Tools.Format = function (value, decimals) {
  5641. if (decimals === void 0) { decimals = 2; }
  5642. return value.toFixed(decimals);
  5643. };
  5644. Tools.CheckExtends = function (v, min, max) {
  5645. if (v.x < min.x)
  5646. min.x = v.x;
  5647. if (v.y < min.y)
  5648. min.y = v.y;
  5649. if (v.z < min.z)
  5650. min.z = v.z;
  5651. if (v.x > max.x)
  5652. max.x = v.x;
  5653. if (v.y > max.y)
  5654. max.y = v.y;
  5655. if (v.z > max.z)
  5656. max.z = v.z;
  5657. };
  5658. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5659. for (var prop in source) {
  5660. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5661. continue;
  5662. }
  5663. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5664. continue;
  5665. }
  5666. var sourceValue = source[prop];
  5667. var typeOfSourceValue = typeof sourceValue;
  5668. if (typeOfSourceValue === "function") {
  5669. continue;
  5670. }
  5671. if (typeOfSourceValue === "object") {
  5672. if (sourceValue instanceof Array) {
  5673. destination[prop] = [];
  5674. if (sourceValue.length > 0) {
  5675. if (typeof sourceValue[0] == "object") {
  5676. for (var index = 0; index < sourceValue.length; index++) {
  5677. var clonedValue = cloneValue(sourceValue[index], destination);
  5678. if (destination[prop].indexOf(clonedValue) === -1) {
  5679. destination[prop].push(clonedValue);
  5680. }
  5681. }
  5682. }
  5683. else {
  5684. destination[prop] = sourceValue.slice(0);
  5685. }
  5686. }
  5687. }
  5688. else {
  5689. destination[prop] = cloneValue(sourceValue, destination);
  5690. }
  5691. }
  5692. else {
  5693. destination[prop] = sourceValue;
  5694. }
  5695. }
  5696. };
  5697. Tools.IsEmpty = function (obj) {
  5698. for (var i in obj) {
  5699. return false;
  5700. }
  5701. return true;
  5702. };
  5703. Tools.RegisterTopRootEvents = function (events) {
  5704. for (var index = 0; index < events.length; index++) {
  5705. var event = events[index];
  5706. window.addEventListener(event.name, event.handler, false);
  5707. try {
  5708. if (window.parent) {
  5709. window.parent.addEventListener(event.name, event.handler, false);
  5710. }
  5711. }
  5712. catch (e) {
  5713. // Silently fails...
  5714. }
  5715. }
  5716. };
  5717. Tools.UnregisterTopRootEvents = function (events) {
  5718. for (var index = 0; index < events.length; index++) {
  5719. var event = events[index];
  5720. window.removeEventListener(event.name, event.handler);
  5721. try {
  5722. if (window.parent) {
  5723. window.parent.removeEventListener(event.name, event.handler);
  5724. }
  5725. }
  5726. catch (e) {
  5727. // Silently fails...
  5728. }
  5729. }
  5730. };
  5731. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5732. if (mimeType === void 0) { mimeType = "image/png"; }
  5733. // Read the contents of the framebuffer
  5734. var numberOfChannelsByLine = width * 4;
  5735. var halfHeight = height / 2;
  5736. //Reading datas from WebGL
  5737. var data = engine.readPixels(0, 0, width, height);
  5738. //To flip image on Y axis.
  5739. for (var i = 0; i < halfHeight; i++) {
  5740. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5741. var currentCell = j + i * numberOfChannelsByLine;
  5742. var targetLine = height - i - 1;
  5743. var targetCell = j + targetLine * numberOfChannelsByLine;
  5744. var temp = data[currentCell];
  5745. data[currentCell] = data[targetCell];
  5746. data[targetCell] = temp;
  5747. }
  5748. }
  5749. // Create a 2D canvas to store the result
  5750. if (!screenshotCanvas) {
  5751. screenshotCanvas = document.createElement('canvas');
  5752. }
  5753. screenshotCanvas.width = width;
  5754. screenshotCanvas.height = height;
  5755. var context = screenshotCanvas.getContext('2d');
  5756. // Copy the pixels to a 2D canvas
  5757. var imageData = context.createImageData(width, height);
  5758. var castData = (imageData.data);
  5759. castData.set(data);
  5760. context.putImageData(imageData, 0, 0);
  5761. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5762. };
  5763. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5764. if (mimeType === void 0) { mimeType = "image/png"; }
  5765. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5766. if (successCallback) {
  5767. successCallback(base64Image);
  5768. }
  5769. else {
  5770. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5771. if (("download" in document.createElement("a"))) {
  5772. var a = window.document.createElement("a");
  5773. a.href = base64Image;
  5774. var date = new Date();
  5775. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5776. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5777. window.document.body.appendChild(a);
  5778. a.addEventListener("click", function () {
  5779. a.parentElement.removeChild(a);
  5780. });
  5781. a.click();
  5782. //Or opening a new tab with the image if it is not possible to automatically start download.
  5783. }
  5784. else {
  5785. var newWindow = window.open("");
  5786. var img = newWindow.document.createElement("img");
  5787. img.src = base64Image;
  5788. newWindow.document.body.appendChild(img);
  5789. }
  5790. }
  5791. };
  5792. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5793. if (mimeType === void 0) { mimeType = "image/png"; }
  5794. var width;
  5795. var height;
  5796. // If a precision value is specified
  5797. if (size.precision) {
  5798. width = Math.round(engine.getRenderWidth() * size.precision);
  5799. height = Math.round(width / engine.getAspectRatio(camera));
  5800. }
  5801. else if (size.width && size.height) {
  5802. width = size.width;
  5803. height = size.height;
  5804. }
  5805. else if (size.width && !size.height) {
  5806. width = size.width;
  5807. height = Math.round(width / engine.getAspectRatio(camera));
  5808. }
  5809. else if (size.height && !size.width) {
  5810. height = size.height;
  5811. width = Math.round(height * engine.getAspectRatio(camera));
  5812. }
  5813. else if (!isNaN(size)) {
  5814. height = size;
  5815. width = size;
  5816. }
  5817. else {
  5818. Tools.Error("Invalid 'size' parameter !");
  5819. return;
  5820. }
  5821. if (!screenshotCanvas) {
  5822. screenshotCanvas = document.createElement('canvas');
  5823. }
  5824. screenshotCanvas.width = width;
  5825. screenshotCanvas.height = height;
  5826. var renderContext = screenshotCanvas.getContext("2d");
  5827. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5828. var newWidth = width;
  5829. var newHeight = newWidth / ratio;
  5830. if (newHeight > height) {
  5831. newHeight = height;
  5832. newWidth = newHeight * ratio;
  5833. }
  5834. var offsetX = Math.max(0, width - newWidth) / 2;
  5835. var offsetY = Math.max(0, height - newHeight) / 2;
  5836. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5837. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5838. };
  5839. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5840. if (mimeType === void 0) { mimeType = "image/png"; }
  5841. if (samples === void 0) { samples = 1; }
  5842. var width;
  5843. var height;
  5844. //If a precision value is specified
  5845. if (size.precision) {
  5846. width = Math.round(engine.getRenderWidth() * size.precision);
  5847. height = Math.round(width / engine.getAspectRatio(camera));
  5848. size = { width: width, height: height };
  5849. }
  5850. else if (size.width && size.height) {
  5851. width = size.width;
  5852. height = size.height;
  5853. }
  5854. else if (size.width && !size.height) {
  5855. width = size.width;
  5856. height = Math.round(width / engine.getAspectRatio(camera));
  5857. size = { width: width, height: height };
  5858. }
  5859. else if (size.height && !size.width) {
  5860. height = size.height;
  5861. width = Math.round(height * engine.getAspectRatio(camera));
  5862. size = { width: width, height: height };
  5863. }
  5864. else if (!isNaN(size)) {
  5865. height = size;
  5866. width = size;
  5867. }
  5868. else {
  5869. Tools.Error("Invalid 'size' parameter !");
  5870. return;
  5871. }
  5872. var scene = camera.getScene();
  5873. var previousCamera = null;
  5874. if (scene.activeCamera !== camera) {
  5875. previousCamera = scene.activeCamera;
  5876. scene.activeCamera = camera;
  5877. }
  5878. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5879. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5880. texture.renderList = scene.meshes;
  5881. texture.samples = samples;
  5882. texture.onAfterRenderObservable.add(function () {
  5883. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5884. });
  5885. scene.incrementRenderId();
  5886. scene.resetCachedMaterial();
  5887. texture.render(true);
  5888. texture.dispose();
  5889. if (previousCamera) {
  5890. scene.activeCamera = previousCamera;
  5891. }
  5892. camera.getProjectionMatrix(true); // Force cache refresh;
  5893. };
  5894. // XHR response validator for local file scenario
  5895. Tools.ValidateXHRData = function (xhr, dataType) {
  5896. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5897. if (dataType === void 0) { dataType = 7; }
  5898. try {
  5899. if (dataType & 1) {
  5900. if (xhr.responseText && xhr.responseText.length > 0) {
  5901. return true;
  5902. }
  5903. else if (dataType === 1) {
  5904. return false;
  5905. }
  5906. }
  5907. if (dataType & 2) {
  5908. // Check header width and height since there is no "TGA" magic number
  5909. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5910. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5911. return true;
  5912. }
  5913. else if (dataType === 2) {
  5914. return false;
  5915. }
  5916. }
  5917. if (dataType & 4) {
  5918. // Check for the "DDS" magic number
  5919. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5920. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5921. return true;
  5922. }
  5923. else {
  5924. return false;
  5925. }
  5926. }
  5927. }
  5928. catch (e) {
  5929. // Global protection
  5930. }
  5931. return false;
  5932. };
  5933. /**
  5934. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5935. * Be aware Math.random() could cause collisions, but:
  5936. * "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"
  5937. */
  5938. Tools.RandomId = function () {
  5939. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5940. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5941. return v.toString(16);
  5942. });
  5943. };
  5944. Object.defineProperty(Tools, "NoneLogLevel", {
  5945. get: function () {
  5946. return Tools._NoneLogLevel;
  5947. },
  5948. enumerable: true,
  5949. configurable: true
  5950. });
  5951. Object.defineProperty(Tools, "MessageLogLevel", {
  5952. get: function () {
  5953. return Tools._MessageLogLevel;
  5954. },
  5955. enumerable: true,
  5956. configurable: true
  5957. });
  5958. Object.defineProperty(Tools, "WarningLogLevel", {
  5959. get: function () {
  5960. return Tools._WarningLogLevel;
  5961. },
  5962. enumerable: true,
  5963. configurable: true
  5964. });
  5965. Object.defineProperty(Tools, "ErrorLogLevel", {
  5966. get: function () {
  5967. return Tools._ErrorLogLevel;
  5968. },
  5969. enumerable: true,
  5970. configurable: true
  5971. });
  5972. Object.defineProperty(Tools, "AllLogLevel", {
  5973. get: function () {
  5974. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5975. },
  5976. enumerable: true,
  5977. configurable: true
  5978. });
  5979. Tools._AddLogEntry = function (entry) {
  5980. Tools._LogCache = entry + Tools._LogCache;
  5981. if (Tools.OnNewCacheEntry) {
  5982. Tools.OnNewCacheEntry(entry);
  5983. }
  5984. };
  5985. Tools._FormatMessage = function (message) {
  5986. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5987. var date = new Date();
  5988. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5989. };
  5990. Tools._LogDisabled = function (message) {
  5991. // nothing to do
  5992. };
  5993. Tools._LogEnabled = function (message) {
  5994. var formattedMessage = Tools._FormatMessage(message);
  5995. console.log("BJS - " + formattedMessage);
  5996. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5997. Tools._AddLogEntry(entry);
  5998. };
  5999. Tools._WarnDisabled = function (message) {
  6000. // nothing to do
  6001. };
  6002. Tools._WarnEnabled = function (message) {
  6003. var formattedMessage = Tools._FormatMessage(message);
  6004. console.warn("BJS - " + formattedMessage);
  6005. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6006. Tools._AddLogEntry(entry);
  6007. };
  6008. Tools._ErrorDisabled = function (message) {
  6009. // nothing to do
  6010. };
  6011. Tools._ErrorEnabled = function (message) {
  6012. Tools.errorsCount++;
  6013. var formattedMessage = Tools._FormatMessage(message);
  6014. console.error("BJS - " + formattedMessage);
  6015. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6016. Tools._AddLogEntry(entry);
  6017. };
  6018. Object.defineProperty(Tools, "LogCache", {
  6019. get: function () {
  6020. return Tools._LogCache;
  6021. },
  6022. enumerable: true,
  6023. configurable: true
  6024. });
  6025. Tools.ClearLogCache = function () {
  6026. Tools._LogCache = "";
  6027. Tools.errorsCount = 0;
  6028. };
  6029. Object.defineProperty(Tools, "LogLevels", {
  6030. set: function (level) {
  6031. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6032. Tools.Log = Tools._LogEnabled;
  6033. }
  6034. else {
  6035. Tools.Log = Tools._LogDisabled;
  6036. }
  6037. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6038. Tools.Warn = Tools._WarnEnabled;
  6039. }
  6040. else {
  6041. Tools.Warn = Tools._WarnDisabled;
  6042. }
  6043. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6044. Tools.Error = Tools._ErrorEnabled;
  6045. }
  6046. else {
  6047. Tools.Error = Tools._ErrorDisabled;
  6048. }
  6049. },
  6050. enumerable: true,
  6051. configurable: true
  6052. });
  6053. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6054. get: function () {
  6055. return Tools._PerformanceNoneLogLevel;
  6056. },
  6057. enumerable: true,
  6058. configurable: true
  6059. });
  6060. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6061. get: function () {
  6062. return Tools._PerformanceUserMarkLogLevel;
  6063. },
  6064. enumerable: true,
  6065. configurable: true
  6066. });
  6067. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6068. get: function () {
  6069. return Tools._PerformanceConsoleLogLevel;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6075. set: function (level) {
  6076. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6077. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6078. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6079. return;
  6080. }
  6081. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6082. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6083. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6084. return;
  6085. }
  6086. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6087. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6088. },
  6089. enumerable: true,
  6090. configurable: true
  6091. });
  6092. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6093. };
  6094. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6095. };
  6096. Tools._StartUserMark = function (counterName, condition) {
  6097. if (condition === void 0) { condition = true; }
  6098. if (!condition || !Tools._performance.mark) {
  6099. return;
  6100. }
  6101. Tools._performance.mark(counterName + "-Begin");
  6102. };
  6103. Tools._EndUserMark = function (counterName, condition) {
  6104. if (condition === void 0) { condition = true; }
  6105. if (!condition || !Tools._performance.mark) {
  6106. return;
  6107. }
  6108. Tools._performance.mark(counterName + "-End");
  6109. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6110. };
  6111. Tools._StartPerformanceConsole = function (counterName, condition) {
  6112. if (condition === void 0) { condition = true; }
  6113. if (!condition) {
  6114. return;
  6115. }
  6116. Tools._StartUserMark(counterName, condition);
  6117. if (console.time) {
  6118. console.time(counterName);
  6119. }
  6120. };
  6121. Tools._EndPerformanceConsole = function (counterName, condition) {
  6122. if (condition === void 0) { condition = true; }
  6123. if (!condition) {
  6124. return;
  6125. }
  6126. Tools._EndUserMark(counterName, condition);
  6127. if (console.time) {
  6128. console.timeEnd(counterName);
  6129. }
  6130. };
  6131. Object.defineProperty(Tools, "Now", {
  6132. get: function () {
  6133. if (window.performance && window.performance.now) {
  6134. return window.performance.now();
  6135. }
  6136. return new Date().getTime();
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. /**
  6142. * This method will return the name of the class used to create the instance of the given object.
  6143. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6144. * @param object the object to get the class name from
  6145. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6146. */
  6147. Tools.getClassName = function (object, isType) {
  6148. if (isType === void 0) { isType = false; }
  6149. var name = null;
  6150. if (!isType && object.getClassName) {
  6151. name = object.getClassName();
  6152. }
  6153. else {
  6154. if (object instanceof Object) {
  6155. var classObj = isType ? object : Object.getPrototypeOf(object);
  6156. name = classObj.constructor["__bjsclassName__"];
  6157. }
  6158. if (!name) {
  6159. name = typeof object;
  6160. }
  6161. }
  6162. return name;
  6163. };
  6164. Tools.first = function (array, predicate) {
  6165. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6166. var el = array_1[_i];
  6167. if (predicate(el)) {
  6168. return el;
  6169. }
  6170. }
  6171. };
  6172. /**
  6173. * This method will return the name of the full name of the class, including its owning module (if any).
  6174. * 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).
  6175. * @param object the object to get the class name from
  6176. * @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.
  6177. */
  6178. Tools.getFullClassName = function (object, isType) {
  6179. if (isType === void 0) { isType = false; }
  6180. var className = null;
  6181. var moduleName = null;
  6182. if (!isType && object.getClassName) {
  6183. className = object.getClassName();
  6184. }
  6185. else {
  6186. if (object instanceof Object) {
  6187. var classObj = isType ? object : Object.getPrototypeOf(object);
  6188. className = classObj.constructor["__bjsclassName__"];
  6189. moduleName = classObj.constructor["__bjsmoduleName__"];
  6190. }
  6191. if (!className) {
  6192. className = typeof object;
  6193. }
  6194. }
  6195. if (!className) {
  6196. return null;
  6197. }
  6198. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6199. };
  6200. /**
  6201. * 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.
  6202. * @param array
  6203. */
  6204. Tools.arrayOrStringFeeder = function (array) {
  6205. return function (index) {
  6206. if (index >= array.length) {
  6207. return null;
  6208. }
  6209. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6210. if (val && val.getHashCode) {
  6211. val = val.getHashCode();
  6212. }
  6213. if (typeof val === "string") {
  6214. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6215. }
  6216. return val;
  6217. };
  6218. };
  6219. /**
  6220. * Compute the hashCode of a stream of number
  6221. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6222. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6223. * @return the hash code computed
  6224. */
  6225. Tools.hashCodeFromStream = function (feeder) {
  6226. // Based from here: http://stackoverflow.com/a/7616484/802124
  6227. var hash = 0;
  6228. var index = 0;
  6229. var chr = feeder(index++);
  6230. while (chr != null) {
  6231. hash = ((hash << 5) - hash) + chr;
  6232. hash |= 0; // Convert to 32bit integer
  6233. chr = feeder(index++);
  6234. }
  6235. return hash;
  6236. };
  6237. return Tools;
  6238. }());
  6239. Tools.BaseUrl = "";
  6240. Tools.CorsBehavior = "anonymous";
  6241. Tools.UseFallbackTexture = true;
  6242. // Used in case of a texture loading problem
  6243. 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";
  6244. // Logs
  6245. Tools._NoneLogLevel = 0;
  6246. Tools._MessageLogLevel = 1;
  6247. Tools._WarningLogLevel = 2;
  6248. Tools._ErrorLogLevel = 4;
  6249. Tools._LogCache = "";
  6250. Tools.errorsCount = 0;
  6251. Tools.Log = Tools._LogEnabled;
  6252. Tools.Warn = Tools._WarnEnabled;
  6253. Tools.Error = Tools._ErrorEnabled;
  6254. // Performances
  6255. Tools._PerformanceNoneLogLevel = 0;
  6256. Tools._PerformanceUserMarkLogLevel = 1;
  6257. Tools._PerformanceConsoleLogLevel = 2;
  6258. Tools._performance = window.performance;
  6259. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6260. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6261. BABYLON.Tools = Tools;
  6262. /**
  6263. * This class is used to track a performance counter which is number based.
  6264. * The user has access to many properties which give statistics of different nature
  6265. *
  6266. * The implementer can track two kinds of Performance Counter: time and count
  6267. * 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.
  6268. * 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.
  6269. */
  6270. var PerfCounter = (function () {
  6271. function PerfCounter() {
  6272. this._startMonitoringTime = 0;
  6273. this._min = 0;
  6274. this._max = 0;
  6275. this._average = 0;
  6276. this._lastSecAverage = 0;
  6277. this._current = 0;
  6278. this._totalValueCount = 0;
  6279. this._totalAccumulated = 0;
  6280. this._lastSecAccumulated = 0;
  6281. this._lastSecTime = 0;
  6282. this._lastSecValueCount = 0;
  6283. }
  6284. Object.defineProperty(PerfCounter.prototype, "min", {
  6285. /**
  6286. * Returns the smallest value ever
  6287. */
  6288. get: function () {
  6289. return this._min;
  6290. },
  6291. enumerable: true,
  6292. configurable: true
  6293. });
  6294. Object.defineProperty(PerfCounter.prototype, "max", {
  6295. /**
  6296. * Returns the biggest value ever
  6297. */
  6298. get: function () {
  6299. return this._max;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(PerfCounter.prototype, "average", {
  6305. /**
  6306. * Returns the average value since the performance counter is running
  6307. */
  6308. get: function () {
  6309. return this._average;
  6310. },
  6311. enumerable: true,
  6312. configurable: true
  6313. });
  6314. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6315. /**
  6316. * Returns the average value of the last second the counter was monitored
  6317. */
  6318. get: function () {
  6319. return this._lastSecAverage;
  6320. },
  6321. enumerable: true,
  6322. configurable: true
  6323. });
  6324. Object.defineProperty(PerfCounter.prototype, "current", {
  6325. /**
  6326. * Returns the current value
  6327. */
  6328. get: function () {
  6329. return this._current;
  6330. },
  6331. enumerable: true,
  6332. configurable: true
  6333. });
  6334. Object.defineProperty(PerfCounter.prototype, "total", {
  6335. get: function () {
  6336. return this._totalAccumulated;
  6337. },
  6338. enumerable: true,
  6339. configurable: true
  6340. });
  6341. /**
  6342. * Call this method to start monitoring a new frame.
  6343. * 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.
  6344. */
  6345. PerfCounter.prototype.fetchNewFrame = function () {
  6346. this._totalValueCount++;
  6347. this._current = 0;
  6348. this._lastSecValueCount++;
  6349. };
  6350. /**
  6351. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6352. * @param newCount the count value to add to the monitored count
  6353. * @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.
  6354. */
  6355. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6356. if (!PerfCounter.Enabled) {
  6357. return;
  6358. }
  6359. this._current += newCount;
  6360. if (fetchResult) {
  6361. this._fetchResult();
  6362. }
  6363. };
  6364. /**
  6365. * Start monitoring this performance counter
  6366. */
  6367. PerfCounter.prototype.beginMonitoring = function () {
  6368. if (!PerfCounter.Enabled) {
  6369. return;
  6370. }
  6371. this._startMonitoringTime = Tools.Now;
  6372. };
  6373. /**
  6374. * Compute the time lapsed since the previous beginMonitoring() call.
  6375. * @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
  6376. */
  6377. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6378. if (newFrame === void 0) { newFrame = true; }
  6379. if (!PerfCounter.Enabled) {
  6380. return;
  6381. }
  6382. if (newFrame) {
  6383. this.fetchNewFrame();
  6384. }
  6385. var currentTime = Tools.Now;
  6386. this._current = currentTime - this._startMonitoringTime;
  6387. if (newFrame) {
  6388. this._fetchResult();
  6389. }
  6390. };
  6391. PerfCounter.prototype._fetchResult = function () {
  6392. this._totalAccumulated += this._current;
  6393. this._lastSecAccumulated += this._current;
  6394. // Min/Max update
  6395. this._min = Math.min(this._min, this._current);
  6396. this._max = Math.max(this._max, this._current);
  6397. this._average = this._totalAccumulated / this._totalValueCount;
  6398. // Reset last sec?
  6399. var now = Tools.Now;
  6400. if ((now - this._lastSecTime) > 1000) {
  6401. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6402. this._lastSecTime = now;
  6403. this._lastSecAccumulated = 0;
  6404. this._lastSecValueCount = 0;
  6405. }
  6406. };
  6407. return PerfCounter;
  6408. }());
  6409. PerfCounter.Enabled = true;
  6410. BABYLON.PerfCounter = PerfCounter;
  6411. /**
  6412. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6413. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6414. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6415. * @param name The name of the class, case should be preserved
  6416. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6417. */
  6418. function className(name, module) {
  6419. return function (target) {
  6420. target["__bjsclassName__"] = name;
  6421. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6422. };
  6423. }
  6424. BABYLON.className = className;
  6425. /**
  6426. * An implementation of a loop for asynchronous functions.
  6427. */
  6428. var AsyncLoop = (function () {
  6429. /**
  6430. * Constroctor.
  6431. * @param iterations the number of iterations.
  6432. * @param _fn the function to run each iteration
  6433. * @param _successCallback the callback that will be called upon succesful execution
  6434. * @param offset starting offset.
  6435. */
  6436. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6437. if (offset === void 0) { offset = 0; }
  6438. this.iterations = iterations;
  6439. this._fn = _fn;
  6440. this._successCallback = _successCallback;
  6441. this.index = offset - 1;
  6442. this._done = false;
  6443. }
  6444. /**
  6445. * Execute the next iteration. Must be called after the last iteration was finished.
  6446. */
  6447. AsyncLoop.prototype.executeNext = function () {
  6448. if (!this._done) {
  6449. if (this.index + 1 < this.iterations) {
  6450. ++this.index;
  6451. this._fn(this);
  6452. }
  6453. else {
  6454. this.breakLoop();
  6455. }
  6456. }
  6457. };
  6458. /**
  6459. * Break the loop and run the success callback.
  6460. */
  6461. AsyncLoop.prototype.breakLoop = function () {
  6462. this._done = true;
  6463. this._successCallback();
  6464. };
  6465. /**
  6466. * Helper function
  6467. */
  6468. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6469. if (offset === void 0) { offset = 0; }
  6470. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6471. loop.executeNext();
  6472. return loop;
  6473. };
  6474. /**
  6475. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6476. * @param iterations total number of iterations
  6477. * @param syncedIterations number of synchronous iterations in each async iteration.
  6478. * @param fn the function to call each iteration.
  6479. * @param callback a success call back that will be called when iterating stops.
  6480. * @param breakFunction a break condition (optional)
  6481. * @param timeout timeout settings for the setTimeout function. default - 0.
  6482. * @constructor
  6483. */
  6484. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6485. if (timeout === void 0) { timeout = 0; }
  6486. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6487. if (breakFunction && breakFunction())
  6488. loop.breakLoop();
  6489. else {
  6490. setTimeout(function () {
  6491. for (var i = 0; i < syncedIterations; ++i) {
  6492. var iteration = (loop.index * syncedIterations) + i;
  6493. if (iteration >= iterations)
  6494. break;
  6495. fn(iteration);
  6496. if (breakFunction && breakFunction()) {
  6497. loop.breakLoop();
  6498. break;
  6499. }
  6500. }
  6501. loop.executeNext();
  6502. }, timeout);
  6503. }
  6504. }, callback);
  6505. };
  6506. return AsyncLoop;
  6507. }());
  6508. BABYLON.AsyncLoop = AsyncLoop;
  6509. })(BABYLON || (BABYLON = {}));
  6510. //# sourceMappingURL=babylon.tools.js.map
  6511. var BABYLON;
  6512. (function (BABYLON) {
  6513. var Internals;
  6514. (function (Internals) {
  6515. var _AlphaState = (function () {
  6516. /**
  6517. * Initializes the state.
  6518. */
  6519. function _AlphaState() {
  6520. this._isAlphaBlendDirty = false;
  6521. this._isBlendFunctionParametersDirty = false;
  6522. this._isBlendEquationParametersDirty = false;
  6523. this._isBlendConstantsDirty = false;
  6524. this._alphaBlend = false;
  6525. this._blendFunctionParameters = new Array(4);
  6526. this._blendEquationParameters = new Array(2);
  6527. this._blendConstants = new Array(4);
  6528. this.reset();
  6529. }
  6530. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6531. get: function () {
  6532. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6538. get: function () {
  6539. return this._alphaBlend;
  6540. },
  6541. set: function (value) {
  6542. if (this._alphaBlend === value) {
  6543. return;
  6544. }
  6545. this._alphaBlend = value;
  6546. this._isAlphaBlendDirty = true;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6552. if (this._blendConstants[0] === r &&
  6553. this._blendConstants[1] === g &&
  6554. this._blendConstants[2] === b &&
  6555. this._blendConstants[3] === a) {
  6556. return;
  6557. }
  6558. this._blendConstants[0] = r;
  6559. this._blendConstants[1] = g;
  6560. this._blendConstants[2] = b;
  6561. this._blendConstants[3] = a;
  6562. this._isBlendConstantsDirty = true;
  6563. };
  6564. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6565. if (this._blendFunctionParameters[0] === value0 &&
  6566. this._blendFunctionParameters[1] === value1 &&
  6567. this._blendFunctionParameters[2] === value2 &&
  6568. this._blendFunctionParameters[3] === value3) {
  6569. return;
  6570. }
  6571. this._blendFunctionParameters[0] = value0;
  6572. this._blendFunctionParameters[1] = value1;
  6573. this._blendFunctionParameters[2] = value2;
  6574. this._blendFunctionParameters[3] = value3;
  6575. this._isBlendFunctionParametersDirty = true;
  6576. };
  6577. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6578. if (this._blendEquationParameters[0] === rgb &&
  6579. this._blendEquationParameters[1] === alpha) {
  6580. return;
  6581. }
  6582. this._blendEquationParameters[0] = rgb;
  6583. this._blendEquationParameters[1] = alpha;
  6584. this._isBlendEquationParametersDirty = true;
  6585. };
  6586. _AlphaState.prototype.reset = function () {
  6587. this._alphaBlend = false;
  6588. this._blendFunctionParameters[0] = null;
  6589. this._blendFunctionParameters[1] = null;
  6590. this._blendFunctionParameters[2] = null;
  6591. this._blendFunctionParameters[3] = null;
  6592. this._blendEquationParameters[0] = null;
  6593. this._blendEquationParameters[1] = null;
  6594. this._blendConstants[0] = null;
  6595. this._blendConstants[1] = null;
  6596. this._blendConstants[2] = null;
  6597. this._blendConstants[3] = null;
  6598. this._isAlphaBlendDirty = true;
  6599. this._isBlendFunctionParametersDirty = false;
  6600. this._isBlendEquationParametersDirty = false;
  6601. this._isBlendConstantsDirty = false;
  6602. };
  6603. _AlphaState.prototype.apply = function (gl) {
  6604. if (!this.isDirty) {
  6605. return;
  6606. }
  6607. // Alpha blend
  6608. if (this._isAlphaBlendDirty) {
  6609. if (this._alphaBlend) {
  6610. gl.enable(gl.BLEND);
  6611. }
  6612. else {
  6613. gl.disable(gl.BLEND);
  6614. }
  6615. this._isAlphaBlendDirty = false;
  6616. }
  6617. // Alpha function
  6618. if (this._isBlendFunctionParametersDirty) {
  6619. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6620. this._isBlendFunctionParametersDirty = false;
  6621. }
  6622. // Alpha equation
  6623. if (this._isBlendEquationParametersDirty) {
  6624. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6625. this._isBlendEquationParametersDirty = false;
  6626. }
  6627. // Constants
  6628. if (this._isBlendConstantsDirty) {
  6629. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6630. this._isBlendConstantsDirty = false;
  6631. }
  6632. };
  6633. return _AlphaState;
  6634. }());
  6635. Internals._AlphaState = _AlphaState;
  6636. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6637. })(BABYLON || (BABYLON = {}));
  6638. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6639. var BABYLON;
  6640. (function (BABYLON) {
  6641. var Internals;
  6642. (function (Internals) {
  6643. var _DepthCullingState = (function () {
  6644. /**
  6645. * Initializes the state.
  6646. */
  6647. function _DepthCullingState() {
  6648. this._isDepthTestDirty = false;
  6649. this._isDepthMaskDirty = false;
  6650. this._isDepthFuncDirty = false;
  6651. this._isCullFaceDirty = false;
  6652. this._isCullDirty = false;
  6653. this._isZOffsetDirty = false;
  6654. this.reset();
  6655. }
  6656. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6657. get: function () {
  6658. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6659. },
  6660. enumerable: true,
  6661. configurable: true
  6662. });
  6663. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6664. get: function () {
  6665. return this._zOffset;
  6666. },
  6667. set: function (value) {
  6668. if (this._zOffset === value) {
  6669. return;
  6670. }
  6671. this._zOffset = value;
  6672. this._isZOffsetDirty = true;
  6673. },
  6674. enumerable: true,
  6675. configurable: true
  6676. });
  6677. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6678. get: function () {
  6679. return this._cullFace;
  6680. },
  6681. set: function (value) {
  6682. if (this._cullFace === value) {
  6683. return;
  6684. }
  6685. this._cullFace = value;
  6686. this._isCullFaceDirty = true;
  6687. },
  6688. enumerable: true,
  6689. configurable: true
  6690. });
  6691. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6692. get: function () {
  6693. return this._cull;
  6694. },
  6695. set: function (value) {
  6696. if (this._cull === value) {
  6697. return;
  6698. }
  6699. this._cull = value;
  6700. this._isCullDirty = true;
  6701. },
  6702. enumerable: true,
  6703. configurable: true
  6704. });
  6705. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6706. get: function () {
  6707. return this._depthFunc;
  6708. },
  6709. set: function (value) {
  6710. if (this._depthFunc === value) {
  6711. return;
  6712. }
  6713. this._depthFunc = value;
  6714. this._isDepthFuncDirty = true;
  6715. },
  6716. enumerable: true,
  6717. configurable: true
  6718. });
  6719. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6720. get: function () {
  6721. return this._depthMask;
  6722. },
  6723. set: function (value) {
  6724. if (this._depthMask === value) {
  6725. return;
  6726. }
  6727. this._depthMask = value;
  6728. this._isDepthMaskDirty = true;
  6729. },
  6730. enumerable: true,
  6731. configurable: true
  6732. });
  6733. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6734. get: function () {
  6735. return this._depthTest;
  6736. },
  6737. set: function (value) {
  6738. if (this._depthTest === value) {
  6739. return;
  6740. }
  6741. this._depthTest = value;
  6742. this._isDepthTestDirty = true;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. _DepthCullingState.prototype.reset = function () {
  6748. this._depthMask = true;
  6749. this._depthTest = true;
  6750. this._depthFunc = null;
  6751. this._cullFace = null;
  6752. this._cull = null;
  6753. this._zOffset = 0;
  6754. this._isDepthTestDirty = true;
  6755. this._isDepthMaskDirty = true;
  6756. this._isDepthFuncDirty = false;
  6757. this._isCullFaceDirty = false;
  6758. this._isCullDirty = false;
  6759. this._isZOffsetDirty = false;
  6760. };
  6761. _DepthCullingState.prototype.apply = function (gl) {
  6762. if (!this.isDirty) {
  6763. return;
  6764. }
  6765. // Cull
  6766. if (this._isCullDirty) {
  6767. if (this.cull) {
  6768. gl.enable(gl.CULL_FACE);
  6769. }
  6770. else {
  6771. gl.disable(gl.CULL_FACE);
  6772. }
  6773. this._isCullDirty = false;
  6774. }
  6775. // Cull face
  6776. if (this._isCullFaceDirty) {
  6777. gl.cullFace(this.cullFace);
  6778. this._isCullFaceDirty = false;
  6779. }
  6780. // Depth mask
  6781. if (this._isDepthMaskDirty) {
  6782. gl.depthMask(this.depthMask);
  6783. this._isDepthMaskDirty = false;
  6784. }
  6785. // Depth test
  6786. if (this._isDepthTestDirty) {
  6787. if (this.depthTest) {
  6788. gl.enable(gl.DEPTH_TEST);
  6789. }
  6790. else {
  6791. gl.disable(gl.DEPTH_TEST);
  6792. }
  6793. this._isDepthTestDirty = false;
  6794. }
  6795. // Depth func
  6796. if (this._isDepthFuncDirty) {
  6797. gl.depthFunc(this.depthFunc);
  6798. this._isDepthFuncDirty = false;
  6799. }
  6800. // zOffset
  6801. if (this._isZOffsetDirty) {
  6802. if (this.zOffset) {
  6803. gl.enable(gl.POLYGON_OFFSET_FILL);
  6804. gl.polygonOffset(this.zOffset, 0);
  6805. }
  6806. else {
  6807. gl.disable(gl.POLYGON_OFFSET_FILL);
  6808. }
  6809. this._isZOffsetDirty = false;
  6810. }
  6811. };
  6812. return _DepthCullingState;
  6813. }());
  6814. Internals._DepthCullingState = _DepthCullingState;
  6815. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6816. })(BABYLON || (BABYLON = {}));
  6817. //# sourceMappingURL=babylon.depthCullingState.js.map
  6818. var BABYLON;
  6819. (function (BABYLON) {
  6820. var Internals;
  6821. (function (Internals) {
  6822. var _StencilState = (function () {
  6823. function _StencilState() {
  6824. this._isStencilTestDirty = false;
  6825. this._isStencilMaskDirty = false;
  6826. this._isStencilFuncDirty = false;
  6827. this._isStencilOpDirty = false;
  6828. this.reset();
  6829. }
  6830. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6831. get: function () {
  6832. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6833. },
  6834. enumerable: true,
  6835. configurable: true
  6836. });
  6837. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6838. get: function () {
  6839. return this._stencilFunc;
  6840. },
  6841. set: function (value) {
  6842. if (this._stencilFunc === value) {
  6843. return;
  6844. }
  6845. this._stencilFunc = value;
  6846. this._isStencilFuncDirty = true;
  6847. },
  6848. enumerable: true,
  6849. configurable: true
  6850. });
  6851. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6852. get: function () {
  6853. return this._stencilFuncRef;
  6854. },
  6855. set: function (value) {
  6856. if (this._stencilFuncRef === value) {
  6857. return;
  6858. }
  6859. this._stencilFuncRef = value;
  6860. this._isStencilFuncDirty = true;
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6866. get: function () {
  6867. return this._stencilFuncMask;
  6868. },
  6869. set: function (value) {
  6870. if (this._stencilFuncMask === value) {
  6871. return;
  6872. }
  6873. this._stencilFuncMask = value;
  6874. this._isStencilFuncDirty = true;
  6875. },
  6876. enumerable: true,
  6877. configurable: true
  6878. });
  6879. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6880. get: function () {
  6881. return this._stencilOpStencilFail;
  6882. },
  6883. set: function (value) {
  6884. if (this._stencilOpStencilFail === value) {
  6885. return;
  6886. }
  6887. this._stencilOpStencilFail = value;
  6888. this._isStencilOpDirty = true;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6894. get: function () {
  6895. return this._stencilOpDepthFail;
  6896. },
  6897. set: function (value) {
  6898. if (this._stencilOpDepthFail === value) {
  6899. return;
  6900. }
  6901. this._stencilOpDepthFail = value;
  6902. this._isStencilOpDirty = true;
  6903. },
  6904. enumerable: true,
  6905. configurable: true
  6906. });
  6907. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6908. get: function () {
  6909. return this._stencilOpStencilDepthPass;
  6910. },
  6911. set: function (value) {
  6912. if (this._stencilOpStencilDepthPass === value) {
  6913. return;
  6914. }
  6915. this._stencilOpStencilDepthPass = value;
  6916. this._isStencilOpDirty = true;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6922. get: function () {
  6923. return this._stencilMask;
  6924. },
  6925. set: function (value) {
  6926. if (this._stencilMask === value) {
  6927. return;
  6928. }
  6929. this._stencilMask = value;
  6930. this._isStencilMaskDirty = true;
  6931. },
  6932. enumerable: true,
  6933. configurable: true
  6934. });
  6935. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6936. get: function () {
  6937. return this._stencilTest;
  6938. },
  6939. set: function (value) {
  6940. if (this._stencilTest === value) {
  6941. return;
  6942. }
  6943. this._stencilTest = value;
  6944. this._isStencilTestDirty = true;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. _StencilState.prototype.reset = function () {
  6950. this._stencilTest = false;
  6951. this._stencilMask = 0xFF;
  6952. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6953. this._stencilFuncRef = 1;
  6954. this._stencilFuncMask = 0xFF;
  6955. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6956. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6957. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6958. this._isStencilTestDirty = true;
  6959. this._isStencilMaskDirty = true;
  6960. this._isStencilFuncDirty = true;
  6961. this._isStencilOpDirty = true;
  6962. };
  6963. _StencilState.prototype.apply = function (gl) {
  6964. if (!this.isDirty) {
  6965. return;
  6966. }
  6967. // Stencil test
  6968. if (this._isStencilTestDirty) {
  6969. if (this.stencilTest) {
  6970. gl.enable(gl.STENCIL_TEST);
  6971. }
  6972. else {
  6973. gl.disable(gl.STENCIL_TEST);
  6974. }
  6975. this._isStencilTestDirty = false;
  6976. }
  6977. // Stencil mask
  6978. if (this._isStencilMaskDirty) {
  6979. gl.stencilMask(this.stencilMask);
  6980. this._isStencilMaskDirty = false;
  6981. }
  6982. // Stencil func
  6983. if (this._isStencilFuncDirty) {
  6984. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6985. this._isStencilFuncDirty = false;
  6986. }
  6987. // Stencil op
  6988. if (this._isStencilOpDirty) {
  6989. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6990. this._isStencilOpDirty = false;
  6991. }
  6992. };
  6993. return _StencilState;
  6994. }());
  6995. Internals._StencilState = _StencilState;
  6996. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6997. })(BABYLON || (BABYLON = {}));
  6998. //# sourceMappingURL=babylon.stencilState.js.map
  6999. var BABYLON;
  7000. (function (BABYLON) {
  7001. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7002. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7003. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7004. gl.compileShader(shader);
  7005. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7006. throw new Error(gl.getShaderInfoLog(shader));
  7007. }
  7008. return shader;
  7009. };
  7010. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7011. var magFilter = gl.NEAREST;
  7012. var minFilter = gl.NEAREST;
  7013. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7014. magFilter = gl.LINEAR;
  7015. if (generateMipMaps) {
  7016. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7017. }
  7018. else {
  7019. minFilter = gl.LINEAR;
  7020. }
  7021. }
  7022. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7023. magFilter = gl.LINEAR;
  7024. if (generateMipMaps) {
  7025. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7026. }
  7027. else {
  7028. minFilter = gl.LINEAR;
  7029. }
  7030. }
  7031. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7032. magFilter = gl.NEAREST;
  7033. if (generateMipMaps) {
  7034. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7035. }
  7036. else {
  7037. minFilter = gl.NEAREST;
  7038. }
  7039. }
  7040. return {
  7041. min: minFilter,
  7042. mag: magFilter
  7043. };
  7044. };
  7045. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7047. var engine = scene.getEngine();
  7048. if (!engine) {
  7049. return;
  7050. }
  7051. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7052. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7053. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7054. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7055. texture._baseWidth = width;
  7056. texture._baseHeight = height;
  7057. texture._width = potWidth;
  7058. texture._height = potHeight;
  7059. texture.isReady = true;
  7060. processFunction(potWidth, potHeight);
  7061. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7064. if (!noMipmap && !isCompressed) {
  7065. gl.generateMipmap(gl.TEXTURE_2D);
  7066. }
  7067. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7068. engine.resetTextureCache();
  7069. scene._removePendingData(texture);
  7070. texture.onLoadedCallbacks.forEach(function (callback) {
  7071. callback();
  7072. });
  7073. texture.onLoadedCallbacks = [];
  7074. };
  7075. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7076. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7077. var img;
  7078. var onload = function () {
  7079. loadedImages[index] = img;
  7080. loadedImages._internalCount++;
  7081. scene._removePendingData(img);
  7082. if (loadedImages._internalCount === 6) {
  7083. onfinish(loadedImages);
  7084. }
  7085. };
  7086. var onerror = function () {
  7087. scene._removePendingData(img);
  7088. if (onErrorCallBack) {
  7089. onErrorCallBack();
  7090. }
  7091. };
  7092. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7093. scene._addPendingData(img);
  7094. };
  7095. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7096. if (onError === void 0) { onError = null; }
  7097. var loadedImages = [];
  7098. loadedImages._internalCount = 0;
  7099. for (var index = 0; index < 6; index++) {
  7100. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7101. }
  7102. };
  7103. var InstancingAttributeInfo = (function () {
  7104. function InstancingAttributeInfo() {
  7105. }
  7106. return InstancingAttributeInfo;
  7107. }());
  7108. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7109. var EngineCapabilities = (function () {
  7110. function EngineCapabilities() {
  7111. }
  7112. return EngineCapabilities;
  7113. }());
  7114. BABYLON.EngineCapabilities = EngineCapabilities;
  7115. /**
  7116. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7117. */
  7118. var Engine = (function () {
  7119. /**
  7120. * @constructor
  7121. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7122. * @param {boolean} [antialias] - enable antialias
  7123. * @param options - further options to be sent to the getContext function
  7124. */
  7125. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7126. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7127. var _this = this;
  7128. // Public members
  7129. this.isFullscreen = false;
  7130. this.isPointerLock = false;
  7131. this.cullBackFaces = true;
  7132. this.renderEvenInBackground = true;
  7133. this.preventCacheWipeBetweenFrames = false;
  7134. // To enable/disable IDB support and avoid XHR on .manifest
  7135. this.enableOfflineSupport = BABYLON.Database;
  7136. this.scenes = new Array();
  7137. // Observables
  7138. /**
  7139. * Observable event triggered each time the rendering canvas is resized
  7140. */
  7141. this.onResizeObservable = new BABYLON.Observable();
  7142. /**
  7143. * Observable event triggered each time the canvas lost focus
  7144. */
  7145. this.onCanvasBlurObservable = new BABYLON.Observable();
  7146. this._windowIsBackground = false;
  7147. this._webGLVersion = 1.0;
  7148. this._badOS = false;
  7149. this._badDesktopOS = false;
  7150. this._drawCalls = new BABYLON.PerfCounter();
  7151. this._renderingQueueLaunched = false;
  7152. this._activeRenderLoops = [];
  7153. // FPS
  7154. this.fpsRange = 60;
  7155. this.previousFramesDuration = [];
  7156. this.fps = 60;
  7157. this.deltaTime = 0;
  7158. // States
  7159. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7160. this._stencilState = new BABYLON.Internals._StencilState();
  7161. this._alphaState = new BABYLON.Internals._AlphaState();
  7162. this._alphaMode = Engine.ALPHA_DISABLE;
  7163. // Cache
  7164. this._loadedTexturesCache = new Array();
  7165. this._maxTextureChannels = 16;
  7166. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7167. this._compiledEffects = {};
  7168. this._vertexAttribArraysEnabled = [];
  7169. this._uintIndicesCurrentlySet = false;
  7170. this._currentBoundBuffer = new Array();
  7171. this._currentBufferPointers = [];
  7172. this._currentInstanceLocations = new Array();
  7173. this._currentInstanceBuffers = new Array();
  7174. this._vaoRecordInProgress = false;
  7175. this._mustWipeVertexAttributes = false;
  7176. // Hardware supported Compressed Textures
  7177. this._texturesSupported = new Array();
  7178. this._onVRFullScreenTriggered = function () {
  7179. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7180. //get the old size before we change
  7181. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7182. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7183. //get the width and height, change the render size
  7184. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7185. var width, height;
  7186. _this.setHardwareScalingLevel(1);
  7187. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7188. }
  7189. else {
  7190. //When the specs are implemented, need to uncomment this.
  7191. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7192. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7193. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7194. _this._vrDisplayEnabled = undefined;
  7195. }
  7196. };
  7197. this._renderingCanvas = canvas;
  7198. Engine.Instances.push(this);
  7199. options = options || {};
  7200. if (antialias != null) {
  7201. options.antialias = antialias;
  7202. }
  7203. if (options.preserveDrawingBuffer === undefined) {
  7204. options.preserveDrawingBuffer = false;
  7205. }
  7206. if (options.audioEngine === undefined) {
  7207. options.audioEngine = true;
  7208. }
  7209. if (options.stencil === undefined) {
  7210. options.stencil = true;
  7211. }
  7212. // GL
  7213. if (!options.disableWebGL2Support) {
  7214. try {
  7215. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7216. if (this._gl) {
  7217. this._webGLVersion = 2.0;
  7218. }
  7219. }
  7220. catch (e) {
  7221. // Do nothing
  7222. }
  7223. }
  7224. if (!this._gl) {
  7225. if (!canvas) {
  7226. throw new Error("The provided canvas is null or undefined.");
  7227. }
  7228. try {
  7229. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7230. }
  7231. catch (e) {
  7232. throw new Error("WebGL not supported");
  7233. }
  7234. }
  7235. if (!this._gl) {
  7236. throw new Error("WebGL not supported");
  7237. }
  7238. this._onBlur = function () {
  7239. _this._windowIsBackground = true;
  7240. };
  7241. this._onFocus = function () {
  7242. _this._windowIsBackground = false;
  7243. };
  7244. this._onCanvasBlur = function () {
  7245. _this.onCanvasBlurObservable.notifyObservers(_this);
  7246. };
  7247. window.addEventListener("blur", this._onBlur);
  7248. window.addEventListener("focus", this._onFocus);
  7249. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7250. // Viewport
  7251. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7252. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7253. this.resize();
  7254. // Caps
  7255. this._isStencilEnable = options.stencil;
  7256. this._caps = new EngineCapabilities();
  7257. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7258. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7259. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7260. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7261. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7262. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7263. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7264. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7265. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7266. // Infos
  7267. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7268. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7269. if (rendererInfo != null) {
  7270. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7271. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7272. }
  7273. if (!this._glVendor) {
  7274. this._glVendor = "Unknown vendor";
  7275. }
  7276. if (!this._glRenderer) {
  7277. this._glRenderer = "Unknown renderer";
  7278. }
  7279. // Constants
  7280. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  7281. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  7282. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  7283. this._gl.DEPTH24_STENCIL8 = 35056;
  7284. // Extensions
  7285. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7286. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7287. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7288. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7289. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7290. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7291. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7292. 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');
  7293. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7294. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7295. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7296. this._caps.highPrecisionShaderSupported = true;
  7297. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7298. // Checks if some of the format renders first to allow the use of webgl inspector.
  7299. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7300. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7301. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7302. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7303. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7304. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7305. if (this._webGLVersion > 1) {
  7306. this._gl.HALF_FLOAT_OES = 0x140B;
  7307. }
  7308. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7309. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7310. // Vertex array object
  7311. if (this._webGLVersion > 1) {
  7312. this._caps.vertexArrayObject = true;
  7313. }
  7314. else {
  7315. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7316. if (vertexArrayObjectExtension != null) {
  7317. this._caps.vertexArrayObject = true;
  7318. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7319. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7320. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7321. }
  7322. else {
  7323. this._caps.vertexArrayObject = false;
  7324. }
  7325. }
  7326. // Instances count
  7327. if (this._webGLVersion > 1) {
  7328. this._caps.instancedArrays = true;
  7329. }
  7330. else {
  7331. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7332. if (instanceExtension != null) {
  7333. this._caps.instancedArrays = true;
  7334. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7335. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7336. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7337. }
  7338. else {
  7339. this._caps.instancedArrays = false;
  7340. }
  7341. }
  7342. // Intelligently add supported compressed formats in order to check for.
  7343. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7344. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7345. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7346. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7347. if (this._caps.astc)
  7348. this.texturesSupported.push('-astc.ktx');
  7349. if (this._caps.s3tc)
  7350. this.texturesSupported.push('-dxt.ktx');
  7351. if (this._caps.pvrtc)
  7352. this.texturesSupported.push('-pvrtc.ktx');
  7353. if (this._caps.etc2)
  7354. this.texturesSupported.push('-etc2.ktx');
  7355. if (this._caps.etc1)
  7356. this.texturesSupported.push('-etc1.ktx');
  7357. if (this._gl.getShaderPrecisionFormat) {
  7358. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7359. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7360. }
  7361. // Depth buffer
  7362. this.setDepthBuffer(true);
  7363. this.setDepthFunctionToLessOrEqual();
  7364. this.setDepthWrite(true);
  7365. // Fullscreen
  7366. this._onFullscreenChange = function () {
  7367. if (document.fullscreen !== undefined) {
  7368. _this.isFullscreen = document.fullscreen;
  7369. }
  7370. else if (document.mozFullScreen !== undefined) {
  7371. _this.isFullscreen = document.mozFullScreen;
  7372. }
  7373. else if (document.webkitIsFullScreen !== undefined) {
  7374. _this.isFullscreen = document.webkitIsFullScreen;
  7375. }
  7376. else if (document.msIsFullScreen !== undefined) {
  7377. _this.isFullscreen = document.msIsFullScreen;
  7378. }
  7379. // Pointer lock
  7380. if (_this.isFullscreen && _this._pointerLockRequested) {
  7381. canvas.requestPointerLock = canvas.requestPointerLock ||
  7382. canvas.msRequestPointerLock ||
  7383. canvas.mozRequestPointerLock ||
  7384. canvas.webkitRequestPointerLock;
  7385. if (canvas.requestPointerLock) {
  7386. canvas.requestPointerLock();
  7387. }
  7388. }
  7389. };
  7390. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7391. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7392. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7393. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7394. // Pointer lock
  7395. this._onPointerLockChange = function () {
  7396. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7397. document.webkitPointerLockElement === canvas ||
  7398. document.msPointerLockElement === canvas ||
  7399. document.pointerLockElement === canvas);
  7400. };
  7401. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7402. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7403. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7404. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7405. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7406. Engine.audioEngine = new BABYLON.AudioEngine();
  7407. }
  7408. //Load WebVR Devices
  7409. if (options.autoEnableWebVR) {
  7410. this.initWebVR();
  7411. }
  7412. //Detect if we are running on a faulty buggy OS.
  7413. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7414. //Detect if we are running on a faulty buggy desktop OS.
  7415. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7416. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7417. }
  7418. Object.defineProperty(Engine, "LastCreatedEngine", {
  7419. get: function () {
  7420. if (Engine.Instances.length === 0) {
  7421. return null;
  7422. }
  7423. return Engine.Instances[Engine.Instances.length - 1];
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(Engine, "LastCreatedScene", {
  7429. get: function () {
  7430. var lastCreatedEngine = Engine.LastCreatedEngine;
  7431. if (!lastCreatedEngine) {
  7432. return null;
  7433. }
  7434. if (lastCreatedEngine.scenes.length === 0) {
  7435. return null;
  7436. }
  7437. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. /**
  7443. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7444. */
  7445. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7446. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7447. var engine = Engine.Instances[engineIndex];
  7448. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7449. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7450. }
  7451. }
  7452. };
  7453. Object.defineProperty(Engine, "NEVER", {
  7454. get: function () {
  7455. return Engine._NEVER;
  7456. },
  7457. enumerable: true,
  7458. configurable: true
  7459. });
  7460. Object.defineProperty(Engine, "ALWAYS", {
  7461. get: function () {
  7462. return Engine._ALWAYS;
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. Object.defineProperty(Engine, "LESS", {
  7468. get: function () {
  7469. return Engine._LESS;
  7470. },
  7471. enumerable: true,
  7472. configurable: true
  7473. });
  7474. Object.defineProperty(Engine, "EQUAL", {
  7475. get: function () {
  7476. return Engine._EQUAL;
  7477. },
  7478. enumerable: true,
  7479. configurable: true
  7480. });
  7481. Object.defineProperty(Engine, "LEQUAL", {
  7482. get: function () {
  7483. return Engine._LEQUAL;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(Engine, "GREATER", {
  7489. get: function () {
  7490. return Engine._GREATER;
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. Object.defineProperty(Engine, "GEQUAL", {
  7496. get: function () {
  7497. return Engine._GEQUAL;
  7498. },
  7499. enumerable: true,
  7500. configurable: true
  7501. });
  7502. Object.defineProperty(Engine, "NOTEQUAL", {
  7503. get: function () {
  7504. return Engine._NOTEQUAL;
  7505. },
  7506. enumerable: true,
  7507. configurable: true
  7508. });
  7509. Object.defineProperty(Engine, "KEEP", {
  7510. get: function () {
  7511. return Engine._KEEP;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(Engine, "REPLACE", {
  7517. get: function () {
  7518. return Engine._REPLACE;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. Object.defineProperty(Engine, "INCR", {
  7524. get: function () {
  7525. return Engine._INCR;
  7526. },
  7527. enumerable: true,
  7528. configurable: true
  7529. });
  7530. Object.defineProperty(Engine, "DECR", {
  7531. get: function () {
  7532. return Engine._DECR;
  7533. },
  7534. enumerable: true,
  7535. configurable: true
  7536. });
  7537. Object.defineProperty(Engine, "INVERT", {
  7538. get: function () {
  7539. return Engine._INVERT;
  7540. },
  7541. enumerable: true,
  7542. configurable: true
  7543. });
  7544. Object.defineProperty(Engine, "INCR_WRAP", {
  7545. get: function () {
  7546. return Engine._INCR_WRAP;
  7547. },
  7548. enumerable: true,
  7549. configurable: true
  7550. });
  7551. Object.defineProperty(Engine, "DECR_WRAP", {
  7552. get: function () {
  7553. return Engine._DECR_WRAP;
  7554. },
  7555. enumerable: true,
  7556. configurable: true
  7557. });
  7558. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7559. get: function () {
  7560. return Engine._ALPHA_DISABLE;
  7561. },
  7562. enumerable: true,
  7563. configurable: true
  7564. });
  7565. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7566. get: function () {
  7567. return Engine._ALPHA_ONEONE;
  7568. },
  7569. enumerable: true,
  7570. configurable: true
  7571. });
  7572. Object.defineProperty(Engine, "ALPHA_ADD", {
  7573. get: function () {
  7574. return Engine._ALPHA_ADD;
  7575. },
  7576. enumerable: true,
  7577. configurable: true
  7578. });
  7579. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7580. get: function () {
  7581. return Engine._ALPHA_COMBINE;
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7587. get: function () {
  7588. return Engine._ALPHA_SUBTRACT;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7594. get: function () {
  7595. return Engine._ALPHA_MULTIPLY;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7601. get: function () {
  7602. return Engine._ALPHA_MAXIMIZED;
  7603. },
  7604. enumerable: true,
  7605. configurable: true
  7606. });
  7607. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7608. get: function () {
  7609. return Engine._ALPHA_PREMULTIPLIED;
  7610. },
  7611. enumerable: true,
  7612. configurable: true
  7613. });
  7614. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7615. get: function () {
  7616. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7617. },
  7618. enumerable: true,
  7619. configurable: true
  7620. });
  7621. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7622. get: function () {
  7623. return Engine._ALPHA_INTERPOLATE;
  7624. },
  7625. enumerable: true,
  7626. configurable: true
  7627. });
  7628. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7629. get: function () {
  7630. return Engine._ALPHA_SCREENMODE;
  7631. },
  7632. enumerable: true,
  7633. configurable: true
  7634. });
  7635. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7636. get: function () {
  7637. return Engine._DELAYLOADSTATE_NONE;
  7638. },
  7639. enumerable: true,
  7640. configurable: true
  7641. });
  7642. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7643. get: function () {
  7644. return Engine._DELAYLOADSTATE_LOADED;
  7645. },
  7646. enumerable: true,
  7647. configurable: true
  7648. });
  7649. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7650. get: function () {
  7651. return Engine._DELAYLOADSTATE_LOADING;
  7652. },
  7653. enumerable: true,
  7654. configurable: true
  7655. });
  7656. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7657. get: function () {
  7658. return Engine._DELAYLOADSTATE_NOTLOADED;
  7659. },
  7660. enumerable: true,
  7661. configurable: true
  7662. });
  7663. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7664. get: function () {
  7665. return Engine._TEXTUREFORMAT_ALPHA;
  7666. },
  7667. enumerable: true,
  7668. configurable: true
  7669. });
  7670. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7671. get: function () {
  7672. return Engine._TEXTUREFORMAT_LUMINANCE;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7678. get: function () {
  7679. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7680. },
  7681. enumerable: true,
  7682. configurable: true
  7683. });
  7684. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7685. get: function () {
  7686. return Engine._TEXTUREFORMAT_RGB;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7692. get: function () {
  7693. return Engine._TEXTUREFORMAT_RGBA;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7699. get: function () {
  7700. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7701. },
  7702. enumerable: true,
  7703. configurable: true
  7704. });
  7705. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7706. get: function () {
  7707. return Engine._TEXTURETYPE_FLOAT;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7713. get: function () {
  7714. return Engine._TEXTURETYPE_HALF_FLOAT;
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7720. get: function () {
  7721. return Engine._SCALEMODE_FLOOR;
  7722. },
  7723. enumerable: true,
  7724. configurable: true
  7725. });
  7726. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7727. get: function () {
  7728. return Engine._SCALEMODE_NEAREST;
  7729. },
  7730. enumerable: true,
  7731. configurable: true
  7732. });
  7733. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7734. get: function () {
  7735. return Engine._SCALEMODE_CEILING;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. Object.defineProperty(Engine, "Version", {
  7741. get: function () {
  7742. return "3.0";
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. Object.defineProperty(Engine.prototype, "badOS", {
  7748. get: function () {
  7749. return this._badOS;
  7750. },
  7751. enumerable: true,
  7752. configurable: true
  7753. });
  7754. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  7755. get: function () {
  7756. return this._badDesktopOS;
  7757. },
  7758. enumerable: true,
  7759. configurable: true
  7760. });
  7761. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7762. get: function () {
  7763. return this._texturesSupported;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7769. get: function () {
  7770. return this._textureFormatInUse;
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7776. // Empty texture
  7777. get: function () {
  7778. if (!this._emptyTexture) {
  7779. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7780. }
  7781. return this._emptyTexture;
  7782. },
  7783. enumerable: true,
  7784. configurable: true
  7785. });
  7786. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7787. get: function () {
  7788. if (!this._emptyCubeTexture) {
  7789. var faceData = new Uint8Array(4);
  7790. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7791. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7792. }
  7793. return this._emptyCubeTexture;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7799. get: function () {
  7800. return this._webGLVersion;
  7801. },
  7802. enumerable: true,
  7803. configurable: true
  7804. });
  7805. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7806. /**
  7807. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7808. */
  7809. get: function () {
  7810. return this._isStencilEnable;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Engine.prototype._prepareWorkingCanvas = function () {
  7816. if (this._workingCanvas) {
  7817. return;
  7818. }
  7819. this._workingCanvas = document.createElement("canvas");
  7820. this._workingContext = this._workingCanvas.getContext("2d");
  7821. };
  7822. Engine.prototype.resetTextureCache = function () {
  7823. for (var index = 0; index < this._maxTextureChannels; index++) {
  7824. this._activeTexturesCache[index] = null;
  7825. }
  7826. };
  7827. Engine.prototype.getGlInfo = function () {
  7828. return {
  7829. vendor: this._glVendor,
  7830. renderer: this._glRenderer,
  7831. version: this._glVersion
  7832. };
  7833. };
  7834. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7835. if (useScreen === void 0) { useScreen = false; }
  7836. var viewport = camera.viewport;
  7837. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7838. };
  7839. Engine.prototype.getRenderWidth = function (useScreen) {
  7840. if (useScreen === void 0) { useScreen = false; }
  7841. if (!useScreen && this._currentRenderTarget) {
  7842. return this._currentRenderTarget._width;
  7843. }
  7844. return this._renderingCanvas.width;
  7845. };
  7846. Engine.prototype.getRenderHeight = function (useScreen) {
  7847. if (useScreen === void 0) { useScreen = false; }
  7848. if (!useScreen && this._currentRenderTarget) {
  7849. return this._currentRenderTarget._height;
  7850. }
  7851. return this._renderingCanvas.height;
  7852. };
  7853. Engine.prototype.getRenderingCanvas = function () {
  7854. return this._renderingCanvas;
  7855. };
  7856. Engine.prototype.getRenderingCanvasClientRect = function () {
  7857. return this._renderingCanvas.getBoundingClientRect();
  7858. };
  7859. Engine.prototype.setHardwareScalingLevel = function (level) {
  7860. this._hardwareScalingLevel = level;
  7861. this.resize();
  7862. };
  7863. Engine.prototype.getHardwareScalingLevel = function () {
  7864. return this._hardwareScalingLevel;
  7865. };
  7866. Engine.prototype.getLoadedTexturesCache = function () {
  7867. return this._loadedTexturesCache;
  7868. };
  7869. Engine.prototype.getCaps = function () {
  7870. return this._caps;
  7871. };
  7872. Object.defineProperty(Engine.prototype, "drawCalls", {
  7873. get: function () {
  7874. return this._drawCalls.current;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7880. get: function () {
  7881. return this._drawCalls;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Engine.prototype.getDepthFunction = function () {
  7887. return this._depthCullingState.depthFunc;
  7888. };
  7889. Engine.prototype.setDepthFunction = function (depthFunc) {
  7890. this._depthCullingState.depthFunc = depthFunc;
  7891. };
  7892. Engine.prototype.setDepthFunctionToGreater = function () {
  7893. this._depthCullingState.depthFunc = this._gl.GREATER;
  7894. };
  7895. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7896. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7897. };
  7898. Engine.prototype.setDepthFunctionToLess = function () {
  7899. this._depthCullingState.depthFunc = this._gl.LESS;
  7900. };
  7901. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7902. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7903. };
  7904. Engine.prototype.getStencilBuffer = function () {
  7905. return this._stencilState.stencilTest;
  7906. };
  7907. Engine.prototype.setStencilBuffer = function (enable) {
  7908. this._stencilState.stencilTest = enable;
  7909. };
  7910. Engine.prototype.getStencilMask = function () {
  7911. return this._stencilState.stencilMask;
  7912. };
  7913. Engine.prototype.setStencilMask = function (mask) {
  7914. this._stencilState.stencilMask = mask;
  7915. };
  7916. Engine.prototype.getStencilFunction = function () {
  7917. return this._stencilState.stencilFunc;
  7918. };
  7919. Engine.prototype.getStencilFunctionReference = function () {
  7920. return this._stencilState.stencilFuncRef;
  7921. };
  7922. Engine.prototype.getStencilFunctionMask = function () {
  7923. return this._stencilState.stencilFuncMask;
  7924. };
  7925. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7926. this._stencilState.stencilFunc = stencilFunc;
  7927. };
  7928. Engine.prototype.setStencilFunctionReference = function (reference) {
  7929. this._stencilState.stencilFuncRef = reference;
  7930. };
  7931. Engine.prototype.setStencilFunctionMask = function (mask) {
  7932. this._stencilState.stencilFuncMask = mask;
  7933. };
  7934. Engine.prototype.getStencilOperationFail = function () {
  7935. return this._stencilState.stencilOpStencilFail;
  7936. };
  7937. Engine.prototype.getStencilOperationDepthFail = function () {
  7938. return this._stencilState.stencilOpDepthFail;
  7939. };
  7940. Engine.prototype.getStencilOperationPass = function () {
  7941. return this._stencilState.stencilOpStencilDepthPass;
  7942. };
  7943. Engine.prototype.setStencilOperationFail = function (operation) {
  7944. this._stencilState.stencilOpStencilFail = operation;
  7945. };
  7946. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7947. this._stencilState.stencilOpDepthFail = operation;
  7948. };
  7949. Engine.prototype.setStencilOperationPass = function (operation) {
  7950. this._stencilState.stencilOpStencilDepthPass = operation;
  7951. };
  7952. Engine.prototype.setDitheringState = function (value) {
  7953. if (value) {
  7954. this._gl.enable(this._gl.DITHER);
  7955. }
  7956. else {
  7957. this._gl.disable(this._gl.DITHER);
  7958. }
  7959. };
  7960. /**
  7961. * stop executing a render loop function and remove it from the execution array
  7962. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7963. */
  7964. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7965. if (!renderFunction) {
  7966. this._activeRenderLoops = [];
  7967. return;
  7968. }
  7969. var index = this._activeRenderLoops.indexOf(renderFunction);
  7970. if (index >= 0) {
  7971. this._activeRenderLoops.splice(index, 1);
  7972. }
  7973. };
  7974. Engine.prototype._renderLoop = function () {
  7975. var shouldRender = true;
  7976. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7977. shouldRender = false;
  7978. }
  7979. if (shouldRender) {
  7980. // Start new frame
  7981. this.beginFrame();
  7982. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7983. var renderFunction = this._activeRenderLoops[index];
  7984. renderFunction();
  7985. }
  7986. // Present
  7987. this.endFrame();
  7988. }
  7989. if (this._activeRenderLoops.length > 0) {
  7990. // Register new frame
  7991. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7992. }
  7993. else {
  7994. this._renderingQueueLaunched = false;
  7995. }
  7996. };
  7997. /**
  7998. * Register and execute a render loop. The engine can have more than one render function.
  7999. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8000. * @example
  8001. * engine.runRenderLoop(function () {
  8002. * scene.render()
  8003. * })
  8004. */
  8005. Engine.prototype.runRenderLoop = function (renderFunction) {
  8006. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8007. return;
  8008. }
  8009. this._activeRenderLoops.push(renderFunction);
  8010. if (!this._renderingQueueLaunched) {
  8011. this._renderingQueueLaunched = true;
  8012. this._bindedRenderFunction = this._renderLoop.bind(this);
  8013. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8014. }
  8015. };
  8016. /**
  8017. * Toggle full screen mode.
  8018. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8019. * @param {any} options - an options object to be sent to the requestFullscreen function
  8020. */
  8021. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8022. if (this.isFullscreen) {
  8023. BABYLON.Tools.ExitFullscreen();
  8024. }
  8025. else {
  8026. this._pointerLockRequested = requestPointerLock;
  8027. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8028. }
  8029. };
  8030. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8031. if (stencil === void 0) { stencil = false; }
  8032. this.applyStates();
  8033. var mode = 0;
  8034. if (backBuffer && color) {
  8035. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8036. mode |= this._gl.COLOR_BUFFER_BIT;
  8037. }
  8038. if (depth) {
  8039. this._gl.clearDepth(1.0);
  8040. mode |= this._gl.DEPTH_BUFFER_BIT;
  8041. }
  8042. if (stencil) {
  8043. this._gl.clearStencil(0);
  8044. mode |= this._gl.STENCIL_BUFFER_BIT;
  8045. }
  8046. this._gl.clear(mode);
  8047. };
  8048. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8049. var gl = this._gl;
  8050. // Save state
  8051. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8052. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8053. // Change state
  8054. gl.enable(gl.SCISSOR_TEST);
  8055. gl.scissor(x, y, width, height);
  8056. // Clear
  8057. this.clear(clearColor, true, true, true);
  8058. // Restore state
  8059. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8060. if (curScissor === true) {
  8061. gl.enable(gl.SCISSOR_TEST);
  8062. }
  8063. else {
  8064. gl.disable(gl.SCISSOR_TEST);
  8065. }
  8066. };
  8067. /**
  8068. * Set the WebGL's viewport
  8069. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8070. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8071. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8072. */
  8073. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8074. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8075. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8076. var x = viewport.x || 0;
  8077. var y = viewport.y || 0;
  8078. this._cachedViewport = viewport;
  8079. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8080. };
  8081. /**
  8082. * Directly set the WebGL Viewport
  8083. * The x, y, width & height are directly passed to the WebGL call
  8084. * @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.
  8085. */
  8086. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8087. var currentViewport = this._cachedViewport;
  8088. this._cachedViewport = null;
  8089. this._gl.viewport(x, y, width, height);
  8090. return currentViewport;
  8091. };
  8092. Engine.prototype.beginFrame = function () {
  8093. this._measureFps();
  8094. };
  8095. Engine.prototype.endFrame = function () {
  8096. //force a flush in case we are using a bad OS.
  8097. if (this._badOS) {
  8098. this.flushFramebuffer();
  8099. }
  8100. //submit frame to the vr device, if enabled
  8101. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8102. this._vrDisplayEnabled.submitFrame();
  8103. }
  8104. };
  8105. /**
  8106. * resize the view according to the canvas' size.
  8107. * @example
  8108. * window.addEventListener("resize", function () {
  8109. * engine.resize();
  8110. * });
  8111. */
  8112. Engine.prototype.resize = function () {
  8113. // We're not resizing the size of the canvas while in VR mode & presenting
  8114. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8115. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8116. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8117. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8118. }
  8119. };
  8120. /**
  8121. * force a specific size of the canvas
  8122. * @param {number} width - the new canvas' width
  8123. * @param {number} height - the new canvas' height
  8124. */
  8125. Engine.prototype.setSize = function (width, height) {
  8126. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8127. return;
  8128. }
  8129. this._renderingCanvas.width = width;
  8130. this._renderingCanvas.height = height;
  8131. for (var index = 0; index < this.scenes.length; index++) {
  8132. var scene = this.scenes[index];
  8133. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8134. var cam = scene.cameras[camIndex];
  8135. cam._currentRenderId = 0;
  8136. }
  8137. }
  8138. if (this.onResizeObservable.hasObservers) {
  8139. this.onResizeObservable.notifyObservers(this);
  8140. }
  8141. };
  8142. //WebVR functions
  8143. Engine.prototype.isVRDevicePresent = function (callback) {
  8144. this.getVRDevice(null, function (device) {
  8145. callback(device !== null);
  8146. });
  8147. };
  8148. Engine.prototype.getVRDevice = function (name, callback) {
  8149. if (!this.vrDisplaysPromise) {
  8150. callback(null);
  8151. return;
  8152. }
  8153. this.vrDisplaysPromise.then(function (devices) {
  8154. if (devices.length > 0) {
  8155. if (name) {
  8156. var found = devices.some(function (device) {
  8157. if (device.displayName === name) {
  8158. callback(device);
  8159. return true;
  8160. }
  8161. else {
  8162. return false;
  8163. }
  8164. });
  8165. if (!found) {
  8166. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8167. callback(devices[0]);
  8168. }
  8169. }
  8170. else {
  8171. //choose the first one
  8172. callback(devices[0]);
  8173. }
  8174. }
  8175. else {
  8176. BABYLON.Tools.Error("No WebVR devices found!");
  8177. callback(null);
  8178. }
  8179. });
  8180. };
  8181. Engine.prototype.initWebVR = function () {
  8182. if (!this.vrDisplaysPromise) {
  8183. this._getVRDisplays();
  8184. }
  8185. };
  8186. Engine.prototype.enableVR = function (vrDevice) {
  8187. this._vrDisplayEnabled = vrDevice;
  8188. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8189. };
  8190. Engine.prototype.disableVR = function () {
  8191. if (this._vrDisplayEnabled) {
  8192. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8193. }
  8194. };
  8195. Engine.prototype._getVRDisplays = function () {
  8196. var _this = this;
  8197. var getWebVRDevices = function (devices) {
  8198. var size = devices.length;
  8199. var i = 0;
  8200. _this._vrDisplays = devices.filter(function (device) {
  8201. return devices[i] instanceof VRDisplay;
  8202. });
  8203. return _this._vrDisplays;
  8204. };
  8205. //using a key due to typescript
  8206. if (navigator.getVRDisplays) {
  8207. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8208. }
  8209. };
  8210. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8211. if (this._currentRenderTarget) {
  8212. this.unBindFramebuffer(this._currentRenderTarget);
  8213. }
  8214. this._currentRenderTarget = texture;
  8215. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8216. var gl = this._gl;
  8217. if (texture.isCube) {
  8218. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8219. }
  8220. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8221. this.wipeCaches();
  8222. };
  8223. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8224. if (this._currentFramebuffer !== framebuffer) {
  8225. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8226. this._currentFramebuffer = framebuffer;
  8227. }
  8228. };
  8229. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8230. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8231. this._currentRenderTarget = null;
  8232. // If MSAA, we need to bitblt back to main texture
  8233. var gl = this._gl;
  8234. if (texture._MSAAFramebuffer) {
  8235. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8236. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8237. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8238. }
  8239. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8240. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8241. gl.generateMipmap(gl.TEXTURE_2D);
  8242. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8243. }
  8244. if (onBeforeUnbind) {
  8245. if (texture._MSAAFramebuffer) {
  8246. // Bind the correct framebuffer
  8247. this.bindUnboundFramebuffer(texture._framebuffer);
  8248. }
  8249. onBeforeUnbind();
  8250. }
  8251. this.bindUnboundFramebuffer(null);
  8252. };
  8253. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8254. if (texture.generateMipMaps) {
  8255. var gl = this._gl;
  8256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8257. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8258. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8259. }
  8260. };
  8261. Engine.prototype.flushFramebuffer = function () {
  8262. this._gl.flush();
  8263. };
  8264. Engine.prototype.restoreDefaultFramebuffer = function () {
  8265. if (this._currentRenderTarget) {
  8266. this.unBindFramebuffer(this._currentRenderTarget);
  8267. }
  8268. else {
  8269. this.bindUnboundFramebuffer(null);
  8270. }
  8271. if (this._cachedViewport) {
  8272. this.setViewport(this._cachedViewport);
  8273. }
  8274. this.wipeCaches();
  8275. };
  8276. // UBOs
  8277. Engine.prototype.createUniformBuffer = function (elements) {
  8278. var ubo = this._gl.createBuffer();
  8279. this.bindUniformBuffer(ubo);
  8280. if (elements instanceof Float32Array) {
  8281. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8282. }
  8283. else {
  8284. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8285. }
  8286. this.bindUniformBuffer(null);
  8287. ubo.references = 1;
  8288. return ubo;
  8289. };
  8290. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8291. var ubo = this._gl.createBuffer();
  8292. this.bindUniformBuffer(ubo);
  8293. if (elements instanceof Float32Array) {
  8294. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8295. }
  8296. else {
  8297. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8298. }
  8299. this.bindUniformBuffer(null);
  8300. ubo.references = 1;
  8301. return ubo;
  8302. };
  8303. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8304. this.bindUniformBuffer(uniformBuffer);
  8305. if (offset === undefined) {
  8306. offset = 0;
  8307. }
  8308. if (count === undefined) {
  8309. if (elements instanceof Float32Array) {
  8310. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8311. }
  8312. else {
  8313. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8314. }
  8315. }
  8316. else {
  8317. if (elements instanceof Float32Array) {
  8318. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8319. }
  8320. else {
  8321. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8322. }
  8323. }
  8324. this.bindUniformBuffer(null);
  8325. };
  8326. // VBOs
  8327. Engine.prototype._resetVertexBufferBinding = function () {
  8328. this.bindArrayBuffer(null);
  8329. this._cachedVertexBuffers = null;
  8330. };
  8331. Engine.prototype.createVertexBuffer = function (vertices) {
  8332. var vbo = this._gl.createBuffer();
  8333. this.bindArrayBuffer(vbo);
  8334. if (vertices instanceof Float32Array) {
  8335. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8336. }
  8337. else {
  8338. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8339. }
  8340. this._resetVertexBufferBinding();
  8341. vbo.references = 1;
  8342. return vbo;
  8343. };
  8344. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8345. var vbo = this._gl.createBuffer();
  8346. this.bindArrayBuffer(vbo);
  8347. if (vertices instanceof Float32Array) {
  8348. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8349. }
  8350. else {
  8351. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8352. }
  8353. this._resetVertexBufferBinding();
  8354. vbo.references = 1;
  8355. return vbo;
  8356. };
  8357. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8358. this.bindArrayBuffer(vertexBuffer);
  8359. if (offset === undefined) {
  8360. offset = 0;
  8361. }
  8362. if (count === undefined) {
  8363. if (vertices instanceof Float32Array) {
  8364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8365. }
  8366. else {
  8367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8368. }
  8369. }
  8370. else {
  8371. if (vertices instanceof Float32Array) {
  8372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8373. }
  8374. else {
  8375. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8376. }
  8377. }
  8378. this._resetVertexBufferBinding();
  8379. };
  8380. Engine.prototype._resetIndexBufferBinding = function () {
  8381. this.bindIndexBuffer(null);
  8382. this._cachedIndexBuffer = null;
  8383. };
  8384. Engine.prototype.createIndexBuffer = function (indices) {
  8385. var vbo = this._gl.createBuffer();
  8386. this.bindIndexBuffer(vbo);
  8387. // Check for 32 bits indices
  8388. var arrayBuffer;
  8389. var need32Bits = false;
  8390. if (indices instanceof Uint16Array) {
  8391. arrayBuffer = indices;
  8392. }
  8393. else {
  8394. //check 32 bit support
  8395. if (this._caps.uintIndices) {
  8396. if (indices instanceof Uint32Array) {
  8397. arrayBuffer = indices;
  8398. need32Bits = true;
  8399. }
  8400. else {
  8401. //number[] or Int32Array, check if 32 bit is necessary
  8402. for (var index = 0; index < indices.length; index++) {
  8403. if (indices[index] > 65535) {
  8404. need32Bits = true;
  8405. break;
  8406. }
  8407. }
  8408. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8409. }
  8410. }
  8411. else {
  8412. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8413. arrayBuffer = new Uint16Array(indices);
  8414. }
  8415. }
  8416. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8417. this._resetIndexBufferBinding();
  8418. vbo.references = 1;
  8419. vbo.is32Bits = need32Bits;
  8420. return vbo;
  8421. };
  8422. Engine.prototype.bindArrayBuffer = function (buffer) {
  8423. if (!this._vaoRecordInProgress) {
  8424. this._unBindVertexArrayObject();
  8425. }
  8426. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8427. };
  8428. Engine.prototype.bindUniformBuffer = function (buffer) {
  8429. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8430. };
  8431. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8432. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8433. };
  8434. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8435. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8436. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8437. };
  8438. ;
  8439. Engine.prototype.bindIndexBuffer = function (buffer) {
  8440. if (!this._vaoRecordInProgress) {
  8441. this._unBindVertexArrayObject();
  8442. }
  8443. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8444. };
  8445. Engine.prototype.bindBuffer = function (buffer, target) {
  8446. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8447. this._gl.bindBuffer(target, buffer);
  8448. this._currentBoundBuffer[target] = buffer;
  8449. }
  8450. };
  8451. Engine.prototype.updateArrayBuffer = function (data) {
  8452. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8453. };
  8454. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8455. var pointer = this._currentBufferPointers[indx];
  8456. var changed = false;
  8457. if (!pointer) {
  8458. changed = true;
  8459. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8460. }
  8461. else {
  8462. if (pointer.buffer !== buffer) {
  8463. pointer.buffer = buffer;
  8464. changed = true;
  8465. }
  8466. if (pointer.size !== size) {
  8467. pointer.size = size;
  8468. changed = true;
  8469. }
  8470. if (pointer.type !== type) {
  8471. pointer.type = type;
  8472. changed = true;
  8473. }
  8474. if (pointer.normalized !== normalized) {
  8475. pointer.normalized = normalized;
  8476. changed = true;
  8477. }
  8478. if (pointer.stride !== stride) {
  8479. pointer.stride = stride;
  8480. changed = true;
  8481. }
  8482. if (pointer.offset !== offset) {
  8483. pointer.offset = offset;
  8484. changed = true;
  8485. }
  8486. }
  8487. if (changed || this._vaoRecordInProgress) {
  8488. this.bindArrayBuffer(buffer);
  8489. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8490. }
  8491. };
  8492. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8493. if (indexBuffer == null) {
  8494. return;
  8495. }
  8496. if (this._cachedIndexBuffer !== indexBuffer) {
  8497. this._cachedIndexBuffer = indexBuffer;
  8498. this.bindIndexBuffer(indexBuffer);
  8499. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8500. }
  8501. };
  8502. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8503. var attributes = effect.getAttributesNames();
  8504. if (!this._vaoRecordInProgress) {
  8505. this._unBindVertexArrayObject();
  8506. }
  8507. this.unbindAllAttributes();
  8508. for (var index = 0; index < attributes.length; index++) {
  8509. var order = effect.getAttributeLocation(index);
  8510. if (order >= 0) {
  8511. var vertexBuffer = vertexBuffers[attributes[index]];
  8512. if (!vertexBuffer) {
  8513. continue;
  8514. }
  8515. this._gl.enableVertexAttribArray(order);
  8516. if (!this._vaoRecordInProgress) {
  8517. this._vertexAttribArraysEnabled[order] = true;
  8518. }
  8519. var buffer = vertexBuffer.getBuffer();
  8520. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8521. if (vertexBuffer.getIsInstanced()) {
  8522. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8523. if (!this._vaoRecordInProgress) {
  8524. this._currentInstanceLocations.push(order);
  8525. this._currentInstanceBuffers.push(buffer);
  8526. }
  8527. }
  8528. }
  8529. }
  8530. };
  8531. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8532. var vao = this._gl.createVertexArray();
  8533. this._vaoRecordInProgress = true;
  8534. this._gl.bindVertexArray(vao);
  8535. this._mustWipeVertexAttributes = true;
  8536. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8537. this.bindIndexBuffer(indexBuffer);
  8538. this._vaoRecordInProgress = false;
  8539. this._gl.bindVertexArray(null);
  8540. return vao;
  8541. };
  8542. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8543. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8544. this._cachedVertexArrayObject = vertexArrayObject;
  8545. this._gl.bindVertexArray(vertexArrayObject);
  8546. this._cachedVertexBuffers = null;
  8547. this._cachedIndexBuffer = null;
  8548. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8549. this._mustWipeVertexAttributes = true;
  8550. }
  8551. };
  8552. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8553. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8554. this._cachedVertexBuffers = vertexBuffer;
  8555. this._cachedEffectForVertexBuffers = effect;
  8556. var attributesCount = effect.getAttributesCount();
  8557. this._unBindVertexArrayObject();
  8558. this.unbindAllAttributes();
  8559. var offset = 0;
  8560. for (var index = 0; index < attributesCount; index++) {
  8561. if (index < vertexDeclaration.length) {
  8562. var order = effect.getAttributeLocation(index);
  8563. if (order >= 0) {
  8564. this._gl.enableVertexAttribArray(order);
  8565. this._vertexAttribArraysEnabled[order] = true;
  8566. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8567. }
  8568. offset += vertexDeclaration[index] * 4;
  8569. }
  8570. }
  8571. }
  8572. this._bindIndexBufferWithCache(indexBuffer);
  8573. };
  8574. Engine.prototype._unBindVertexArrayObject = function () {
  8575. if (!this._cachedVertexArrayObject) {
  8576. return;
  8577. }
  8578. this._cachedVertexArrayObject = null;
  8579. this._gl.bindVertexArray(null);
  8580. };
  8581. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8582. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8583. this._cachedVertexBuffers = vertexBuffers;
  8584. this._cachedEffectForVertexBuffers = effect;
  8585. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8586. }
  8587. this._bindIndexBufferWithCache(indexBuffer);
  8588. };
  8589. Engine.prototype.unbindInstanceAttributes = function () {
  8590. var boundBuffer;
  8591. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8592. var instancesBuffer = this._currentInstanceBuffers[i];
  8593. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8594. boundBuffer = instancesBuffer;
  8595. this.bindArrayBuffer(instancesBuffer);
  8596. }
  8597. var offsetLocation = this._currentInstanceLocations[i];
  8598. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8599. }
  8600. this._currentInstanceBuffers.length = 0;
  8601. this._currentInstanceLocations.length = 0;
  8602. };
  8603. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8604. this._gl.deleteVertexArray(vao);
  8605. };
  8606. Engine.prototype._releaseBuffer = function (buffer) {
  8607. buffer.references--;
  8608. if (buffer.references === 0) {
  8609. this._gl.deleteBuffer(buffer);
  8610. return true;
  8611. }
  8612. return false;
  8613. };
  8614. Engine.prototype.createInstancesBuffer = function (capacity) {
  8615. var buffer = this._gl.createBuffer();
  8616. buffer.capacity = capacity;
  8617. this.bindArrayBuffer(buffer);
  8618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8619. return buffer;
  8620. };
  8621. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8622. this._gl.deleteBuffer(buffer);
  8623. };
  8624. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8625. this.bindArrayBuffer(instancesBuffer);
  8626. if (data) {
  8627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8628. }
  8629. if (offsetLocations[0].index !== undefined) {
  8630. var stride = 0;
  8631. for (var i = 0; i < offsetLocations.length; i++) {
  8632. var ai = offsetLocations[i];
  8633. stride += ai.attributeSize * 4;
  8634. }
  8635. for (var i = 0; i < offsetLocations.length; i++) {
  8636. var ai = offsetLocations[i];
  8637. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8638. this._gl.enableVertexAttribArray(ai.index);
  8639. this._vertexAttribArraysEnabled[ai.index] = true;
  8640. }
  8641. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8642. this._gl.vertexAttribDivisor(ai.index, 1);
  8643. this._currentInstanceLocations.push(ai.index);
  8644. this._currentInstanceBuffers.push(instancesBuffer);
  8645. }
  8646. }
  8647. else {
  8648. for (var index = 0; index < 4; index++) {
  8649. var offsetLocation = offsetLocations[index];
  8650. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8651. this._gl.enableVertexAttribArray(offsetLocation);
  8652. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8653. }
  8654. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8655. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8656. this._currentInstanceLocations.push(offsetLocation);
  8657. this._currentInstanceBuffers.push(instancesBuffer);
  8658. }
  8659. }
  8660. };
  8661. Engine.prototype.applyStates = function () {
  8662. this._depthCullingState.apply(this._gl);
  8663. this._stencilState.apply(this._gl);
  8664. this._alphaState.apply(this._gl);
  8665. };
  8666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8667. // Apply states
  8668. this.applyStates();
  8669. this._drawCalls.addCount(1, false);
  8670. // Render
  8671. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8672. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8673. if (instancesCount) {
  8674. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8675. return;
  8676. }
  8677. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8678. };
  8679. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8680. // Apply states
  8681. this.applyStates();
  8682. this._drawCalls.addCount(1, false);
  8683. if (instancesCount) {
  8684. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8685. return;
  8686. }
  8687. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8688. };
  8689. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8690. // Apply states
  8691. this.applyStates();
  8692. this._drawCalls.addCount(1, false);
  8693. if (instancesCount) {
  8694. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8695. return;
  8696. }
  8697. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8698. };
  8699. // Shaders
  8700. Engine.prototype._releaseEffect = function (effect) {
  8701. if (this._compiledEffects[effect._key]) {
  8702. delete this._compiledEffects[effect._key];
  8703. if (effect.getProgram()) {
  8704. this._gl.deleteProgram(effect.getProgram());
  8705. }
  8706. }
  8707. };
  8708. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8709. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8710. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8711. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8712. if (this._compiledEffects[name]) {
  8713. var compiledEffect = this._compiledEffects[name];
  8714. if (onCompiled && compiledEffect.isReady()) {
  8715. onCompiled(compiledEffect);
  8716. }
  8717. return compiledEffect;
  8718. }
  8719. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8720. effect._key = name;
  8721. this._compiledEffects[name] = effect;
  8722. return effect;
  8723. };
  8724. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8725. if (uniformsNames === void 0) { uniformsNames = []; }
  8726. if (samplers === void 0) { samplers = []; }
  8727. if (defines === void 0) { defines = ""; }
  8728. return this.createEffect({
  8729. vertex: "particles",
  8730. fragmentElement: fragmentName
  8731. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8732. };
  8733. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8734. context = context || this._gl;
  8735. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8736. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8737. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8738. var shaderProgram = context.createProgram();
  8739. context.attachShader(shaderProgram, vertexShader);
  8740. context.attachShader(shaderProgram, fragmentShader);
  8741. context.linkProgram(shaderProgram);
  8742. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8743. if (!linked) {
  8744. context.validateProgram(shaderProgram);
  8745. var error = context.getProgramInfoLog(shaderProgram);
  8746. if (error) {
  8747. throw new Error(error);
  8748. }
  8749. }
  8750. context.deleteShader(vertexShader);
  8751. context.deleteShader(fragmentShader);
  8752. return shaderProgram;
  8753. };
  8754. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8755. var results = [];
  8756. for (var index = 0; index < uniformsNames.length; index++) {
  8757. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8758. }
  8759. return results;
  8760. };
  8761. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8762. var results = [];
  8763. for (var index = 0; index < attributesNames.length; index++) {
  8764. try {
  8765. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8766. }
  8767. catch (e) {
  8768. results.push(-1);
  8769. }
  8770. }
  8771. return results;
  8772. };
  8773. Engine.prototype.enableEffect = function (effect) {
  8774. // Use program
  8775. this.setProgram(effect.getProgram());
  8776. this._currentEffect = effect;
  8777. if (effect.onBind) {
  8778. effect.onBind(effect);
  8779. }
  8780. effect.onBindObservable.notifyObservers(effect);
  8781. };
  8782. Engine.prototype.setIntArray = function (uniform, array) {
  8783. if (!uniform)
  8784. return;
  8785. this._gl.uniform1iv(uniform, array);
  8786. };
  8787. Engine.prototype.setIntArray2 = function (uniform, array) {
  8788. if (!uniform || array.length % 2 !== 0)
  8789. return;
  8790. this._gl.uniform2iv(uniform, array);
  8791. };
  8792. Engine.prototype.setIntArray3 = function (uniform, array) {
  8793. if (!uniform || array.length % 3 !== 0)
  8794. return;
  8795. this._gl.uniform3iv(uniform, array);
  8796. };
  8797. Engine.prototype.setIntArray4 = function (uniform, array) {
  8798. if (!uniform || array.length % 4 !== 0)
  8799. return;
  8800. this._gl.uniform4iv(uniform, array);
  8801. };
  8802. Engine.prototype.setFloatArray = function (uniform, array) {
  8803. if (!uniform)
  8804. return;
  8805. this._gl.uniform1fv(uniform, array);
  8806. };
  8807. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8808. if (!uniform || array.length % 2 !== 0)
  8809. return;
  8810. this._gl.uniform2fv(uniform, array);
  8811. };
  8812. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8813. if (!uniform || array.length % 3 !== 0)
  8814. return;
  8815. this._gl.uniform3fv(uniform, array);
  8816. };
  8817. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8818. if (!uniform || array.length % 4 !== 0)
  8819. return;
  8820. this._gl.uniform4fv(uniform, array);
  8821. };
  8822. Engine.prototype.setArray = function (uniform, array) {
  8823. if (!uniform)
  8824. return;
  8825. this._gl.uniform1fv(uniform, array);
  8826. };
  8827. Engine.prototype.setArray2 = function (uniform, array) {
  8828. if (!uniform || array.length % 2 !== 0)
  8829. return;
  8830. this._gl.uniform2fv(uniform, array);
  8831. };
  8832. Engine.prototype.setArray3 = function (uniform, array) {
  8833. if (!uniform || array.length % 3 !== 0)
  8834. return;
  8835. this._gl.uniform3fv(uniform, array);
  8836. };
  8837. Engine.prototype.setArray4 = function (uniform, array) {
  8838. if (!uniform || array.length % 4 !== 0)
  8839. return;
  8840. this._gl.uniform4fv(uniform, array);
  8841. };
  8842. Engine.prototype.setMatrices = function (uniform, matrices) {
  8843. if (!uniform)
  8844. return;
  8845. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8846. };
  8847. Engine.prototype.setMatrix = function (uniform, matrix) {
  8848. if (!uniform)
  8849. return;
  8850. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8851. };
  8852. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8853. if (!uniform)
  8854. return;
  8855. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8856. };
  8857. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8858. if (!uniform)
  8859. return;
  8860. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8861. };
  8862. Engine.prototype.setFloat = function (uniform, value) {
  8863. if (!uniform)
  8864. return;
  8865. this._gl.uniform1f(uniform, value);
  8866. };
  8867. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8868. if (!uniform)
  8869. return;
  8870. this._gl.uniform2f(uniform, x, y);
  8871. };
  8872. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8873. if (!uniform)
  8874. return;
  8875. this._gl.uniform3f(uniform, x, y, z);
  8876. };
  8877. Engine.prototype.setBool = function (uniform, bool) {
  8878. if (!uniform)
  8879. return;
  8880. this._gl.uniform1i(uniform, bool);
  8881. };
  8882. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8883. if (!uniform)
  8884. return;
  8885. this._gl.uniform4f(uniform, x, y, z, w);
  8886. };
  8887. Engine.prototype.setColor3 = function (uniform, color3) {
  8888. if (!uniform)
  8889. return;
  8890. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8891. };
  8892. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8893. if (!uniform)
  8894. return;
  8895. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8896. };
  8897. // States
  8898. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8899. if (zOffset === void 0) { zOffset = 0; }
  8900. if (reverseSide === void 0) { reverseSide = false; }
  8901. // Culling
  8902. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8903. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8904. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8905. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8906. if (culling) {
  8907. this._depthCullingState.cullFace = cullFace;
  8908. this._depthCullingState.cull = true;
  8909. }
  8910. else {
  8911. this._depthCullingState.cull = false;
  8912. }
  8913. }
  8914. // Z offset
  8915. this.setZOffset(zOffset);
  8916. };
  8917. Engine.prototype.setZOffset = function (value) {
  8918. this._depthCullingState.zOffset = value;
  8919. };
  8920. Engine.prototype.getZOffset = function () {
  8921. return this._depthCullingState.zOffset;
  8922. };
  8923. Engine.prototype.setDepthBuffer = function (enable) {
  8924. this._depthCullingState.depthTest = enable;
  8925. };
  8926. Engine.prototype.getDepthWrite = function () {
  8927. return this._depthCullingState.depthMask;
  8928. };
  8929. Engine.prototype.setDepthWrite = function (enable) {
  8930. this._depthCullingState.depthMask = enable;
  8931. };
  8932. Engine.prototype.setColorWrite = function (enable) {
  8933. this._gl.colorMask(enable, enable, enable, enable);
  8934. };
  8935. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8936. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8937. };
  8938. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8939. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8940. if (this._alphaMode === mode) {
  8941. return;
  8942. }
  8943. switch (mode) {
  8944. case Engine.ALPHA_DISABLE:
  8945. this._alphaState.alphaBlend = false;
  8946. break;
  8947. case Engine.ALPHA_PREMULTIPLIED:
  8948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8949. this._alphaState.alphaBlend = true;
  8950. break;
  8951. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8953. this._alphaState.alphaBlend = true;
  8954. break;
  8955. case Engine.ALPHA_COMBINE:
  8956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8957. this._alphaState.alphaBlend = true;
  8958. break;
  8959. case Engine.ALPHA_ONEONE:
  8960. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8961. this._alphaState.alphaBlend = true;
  8962. break;
  8963. case Engine.ALPHA_ADD:
  8964. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8965. this._alphaState.alphaBlend = true;
  8966. break;
  8967. case Engine.ALPHA_SUBTRACT:
  8968. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8969. this._alphaState.alphaBlend = true;
  8970. break;
  8971. case Engine.ALPHA_MULTIPLY:
  8972. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8973. this._alphaState.alphaBlend = true;
  8974. break;
  8975. case Engine.ALPHA_MAXIMIZED:
  8976. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8977. this._alphaState.alphaBlend = true;
  8978. break;
  8979. case Engine.ALPHA_INTERPOLATE:
  8980. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8981. this._alphaState.alphaBlend = true;
  8982. break;
  8983. case Engine.ALPHA_SCREENMODE:
  8984. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8985. this._alphaState.alphaBlend = true;
  8986. break;
  8987. }
  8988. if (!noDepthWriteChange) {
  8989. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8990. }
  8991. this._alphaMode = mode;
  8992. };
  8993. Engine.prototype.getAlphaMode = function () {
  8994. return this._alphaMode;
  8995. };
  8996. Engine.prototype.setAlphaTesting = function (enable) {
  8997. this._alphaTest = enable;
  8998. };
  8999. Engine.prototype.getAlphaTesting = function () {
  9000. return !!this._alphaTest;
  9001. };
  9002. // Textures
  9003. Engine.prototype.wipeCaches = function (bruteForce) {
  9004. if (this.preventCacheWipeBetweenFrames) {
  9005. return;
  9006. }
  9007. this.resetTextureCache();
  9008. this._currentEffect = null;
  9009. // 6/8/2017: deltakosh: Should not be required anymore.
  9010. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9011. if (bruteForce) {
  9012. this._stencilState.reset();
  9013. this._depthCullingState.reset();
  9014. this.setDepthFunctionToLessOrEqual();
  9015. this._alphaState.reset();
  9016. }
  9017. this._cachedVertexBuffers = null;
  9018. this._cachedIndexBuffer = null;
  9019. this._cachedEffectForVertexBuffers = null;
  9020. this._unBindVertexArrayObject();
  9021. this.bindIndexBuffer(null);
  9022. this.bindArrayBuffer(null);
  9023. };
  9024. /**
  9025. * Set the compressed texture format to use, based on the formats you have, and the formats
  9026. * supported by the hardware / browser.
  9027. *
  9028. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9029. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9030. * to API arguments needed to compressed textures. This puts the burden on the container
  9031. * generator to house the arcane code for determining these for current & future formats.
  9032. *
  9033. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9034. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9035. *
  9036. * Note: The result of this call is not taken into account when a texture is base64.
  9037. *
  9038. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9039. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9040. *
  9041. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9042. * @returns The extension selected.
  9043. */
  9044. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9045. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9046. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9047. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9048. return this._textureFormatInUse = this._texturesSupported[i];
  9049. }
  9050. }
  9051. }
  9052. // actively set format to nothing, to allow this to be called more than once
  9053. // and possibly fail the 2nd time
  9054. return this._textureFormatInUse = null;
  9055. };
  9056. /**
  9057. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9058. * @param {string} urlArg- This contains one of the following:
  9059. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9060. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9061. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9062. *
  9063. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9064. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9065. * @param {Scene} scene- Needed for loading to the correct scene.
  9066. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9067. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9068. * @param {callback} onError- Optional callback to be called upon failure.
  9069. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9070. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9071. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9072. *
  9073. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9074. */
  9075. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9076. var _this = this;
  9077. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9078. if (onLoad === void 0) { onLoad = null; }
  9079. if (onError === void 0) { onError = null; }
  9080. if (buffer === void 0) { buffer = null; }
  9081. var texture = fallBack ? fallBack : this._gl.createTexture();
  9082. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9083. var fromData = url.substr(0, 5) === "data:";
  9084. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9085. // establish the file extension, if possible
  9086. var lastDot = url.lastIndexOf('.');
  9087. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9088. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9089. var isTGA = (extension === ".tga");
  9090. // determine if a ktx file should be substituted
  9091. var isKTX = false;
  9092. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9093. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9094. isKTX = true;
  9095. }
  9096. scene._addPendingData(texture);
  9097. texture.url = url;
  9098. texture.generateMipMaps = !noMipmap;
  9099. texture.references = 1;
  9100. texture.samplingMode = samplingMode;
  9101. texture.onLoadedCallbacks = [];
  9102. if (onLoad) {
  9103. texture.onLoadedCallbacks.push(onLoad);
  9104. }
  9105. if (!fallBack)
  9106. this._loadedTexturesCache.push(texture);
  9107. var onerror = function () {
  9108. scene._removePendingData(texture);
  9109. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9110. if (isKTX) {
  9111. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9112. }
  9113. else if (onError) {
  9114. onError();
  9115. }
  9116. };
  9117. var callback;
  9118. // processing for non-image formats
  9119. if (isKTX || isTGA || isDDS) {
  9120. if (isKTX) {
  9121. callback = function (data) {
  9122. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9123. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9124. ktx.uploadLevels(_this._gl, !noMipmap);
  9125. }, samplingMode);
  9126. };
  9127. }
  9128. else if (isTGA) {
  9129. callback = function (arrayBuffer) {
  9130. var data = new Uint8Array(arrayBuffer);
  9131. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9132. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9133. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9134. }, samplingMode);
  9135. };
  9136. }
  9137. else if (isDDS) {
  9138. callback = function (data) {
  9139. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9140. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9141. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9142. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 1);
  9143. }, samplingMode);
  9144. };
  9145. }
  9146. if (!buffer) {
  9147. BABYLON.Tools.LoadFile(url, function (data) {
  9148. callback(data);
  9149. }, null, scene.database, true, onerror);
  9150. }
  9151. else {
  9152. callback(buffer);
  9153. }
  9154. // image format processing
  9155. }
  9156. else {
  9157. var onload = function (img) {
  9158. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9159. var isPot = (img.width === potWidth && img.height === potHeight);
  9160. if (!isPot) {
  9161. _this._prepareWorkingCanvas();
  9162. _this._workingCanvas.width = potWidth;
  9163. _this._workingCanvas.height = potHeight;
  9164. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9165. _this._workingContext.imageSmoothingEnabled = false;
  9166. _this._workingContext.mozImageSmoothingEnabled = false;
  9167. _this._workingContext.oImageSmoothingEnabled = false;
  9168. _this._workingContext.webkitImageSmoothingEnabled = false;
  9169. _this._workingContext.msImageSmoothingEnabled = false;
  9170. }
  9171. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9172. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9173. _this._workingContext.imageSmoothingEnabled = true;
  9174. _this._workingContext.mozImageSmoothingEnabled = true;
  9175. _this._workingContext.oImageSmoothingEnabled = true;
  9176. _this._workingContext.webkitImageSmoothingEnabled = true;
  9177. _this._workingContext.msImageSmoothingEnabled = true;
  9178. }
  9179. }
  9180. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9181. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9182. }, samplingMode);
  9183. };
  9184. if (!fromData || isBase64)
  9185. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9186. else if (buffer instanceof Array || typeof buffer === "string")
  9187. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9188. else
  9189. onload(buffer);
  9190. }
  9191. return texture;
  9192. };
  9193. Engine.prototype._getInternalFormat = function (format) {
  9194. var internalFormat = this._gl.RGBA;
  9195. switch (format) {
  9196. case Engine.TEXTUREFORMAT_ALPHA:
  9197. internalFormat = this._gl.ALPHA;
  9198. break;
  9199. case Engine.TEXTUREFORMAT_LUMINANCE:
  9200. internalFormat = this._gl.LUMINANCE;
  9201. break;
  9202. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9203. internalFormat = this._gl.LUMINANCE_ALPHA;
  9204. break;
  9205. case Engine.TEXTUREFORMAT_RGB:
  9206. internalFormat = this._gl.RGB;
  9207. break;
  9208. case Engine.TEXTUREFORMAT_RGBA:
  9209. internalFormat = this._gl.RGBA;
  9210. break;
  9211. }
  9212. return internalFormat;
  9213. };
  9214. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9215. if (compression === void 0) { compression = null; }
  9216. var internalFormat = this._getInternalFormat(format);
  9217. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9218. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9219. if (texture._width % 4 !== 0) {
  9220. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9221. }
  9222. if (compression) {
  9223. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9224. }
  9225. else {
  9226. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9227. }
  9228. if (texture.generateMipMaps) {
  9229. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9230. }
  9231. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9232. this.resetTextureCache();
  9233. texture.isReady = true;
  9234. };
  9235. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9236. if (compression === void 0) { compression = null; }
  9237. var texture = this._gl.createTexture();
  9238. texture._baseWidth = width;
  9239. texture._baseHeight = height;
  9240. texture._width = width;
  9241. texture._height = height;
  9242. texture.references = 1;
  9243. this.updateRawTexture(texture, data, format, invertY, compression);
  9244. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9245. // Filters
  9246. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9247. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9248. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9249. if (generateMipMaps) {
  9250. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9251. }
  9252. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9253. texture.samplingMode = samplingMode;
  9254. this._loadedTexturesCache.push(texture);
  9255. return texture;
  9256. };
  9257. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9258. var texture = this._gl.createTexture();
  9259. texture._baseWidth = width;
  9260. texture._baseHeight = height;
  9261. if (generateMipMaps) {
  9262. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9263. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9264. }
  9265. this.resetTextureCache();
  9266. texture._width = width;
  9267. texture._height = height;
  9268. texture.isReady = false;
  9269. texture.generateMipMaps = generateMipMaps;
  9270. texture.references = 1;
  9271. texture.samplingMode = samplingMode;
  9272. this.updateTextureSamplingMode(samplingMode, texture);
  9273. this._loadedTexturesCache.push(texture);
  9274. return texture;
  9275. };
  9276. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9277. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9278. if (texture.isCube) {
  9279. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9280. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9281. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9282. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9283. }
  9284. else {
  9285. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9288. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9289. }
  9290. texture.samplingMode = samplingMode;
  9291. };
  9292. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9293. if (premulAlpha === void 0) { premulAlpha = false; }
  9294. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9295. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9296. if (premulAlpha) {
  9297. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9298. }
  9299. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9300. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9301. if (texture.generateMipMaps) {
  9302. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9303. }
  9304. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9305. if (premulAlpha) {
  9306. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9307. }
  9308. this.resetTextureCache();
  9309. texture.isReady = true;
  9310. };
  9311. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9312. if (texture._isDisabled) {
  9313. return;
  9314. }
  9315. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9316. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9317. try {
  9318. // Testing video texture support
  9319. if (this._videoTextureSupported === undefined) {
  9320. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9321. if (this._gl.getError() !== 0) {
  9322. this._videoTextureSupported = false;
  9323. }
  9324. else {
  9325. this._videoTextureSupported = true;
  9326. }
  9327. }
  9328. // Copy video through the current working canvas if video texture is not supported
  9329. if (!this._videoTextureSupported) {
  9330. if (!texture._workingCanvas) {
  9331. texture._workingCanvas = document.createElement("canvas");
  9332. texture._workingContext = texture._workingCanvas.getContext("2d");
  9333. texture._workingCanvas.width = texture._width;
  9334. texture._workingCanvas.height = texture._height;
  9335. }
  9336. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9337. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9338. }
  9339. else {
  9340. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9341. }
  9342. if (texture.generateMipMaps) {
  9343. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9344. }
  9345. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9346. this.resetTextureCache();
  9347. texture.isReady = true;
  9348. }
  9349. catch (ex) {
  9350. // Something unexpected
  9351. // Let's disable the texture
  9352. texture._isDisabled = true;
  9353. }
  9354. };
  9355. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9356. // old version had a "generateMipMaps" arg instead of options.
  9357. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9358. // in the same way, generateDepthBuffer is defaulted to true
  9359. var generateMipMaps = false;
  9360. var generateDepthBuffer = true;
  9361. var generateStencilBuffer = false;
  9362. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9363. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9364. if (options !== undefined) {
  9365. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9366. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9367. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9368. type = options.type === undefined ? type : options.type;
  9369. if (options.samplingMode !== undefined) {
  9370. samplingMode = options.samplingMode;
  9371. }
  9372. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9373. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9374. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9375. }
  9376. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9377. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9378. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9379. }
  9380. }
  9381. var gl = this._gl;
  9382. var texture = gl.createTexture();
  9383. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9384. var width = size.width || size;
  9385. var height = size.height || size;
  9386. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9387. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9388. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9389. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9390. }
  9391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9394. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9395. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9396. // Create the framebuffer
  9397. var framebuffer = gl.createFramebuffer();
  9398. this.bindUnboundFramebuffer(framebuffer);
  9399. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9400. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9401. if (generateMipMaps) {
  9402. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9403. }
  9404. // Unbind
  9405. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9406. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9407. this.bindUnboundFramebuffer(null);
  9408. texture._framebuffer = framebuffer;
  9409. texture._baseWidth = width;
  9410. texture._baseHeight = height;
  9411. texture._width = width;
  9412. texture._height = height;
  9413. texture.isReady = true;
  9414. texture.samples = 1;
  9415. texture.generateMipMaps = generateMipMaps;
  9416. texture.references = 1;
  9417. texture.samplingMode = samplingMode;
  9418. texture.type = type;
  9419. texture._generateDepthBuffer = generateDepthBuffer;
  9420. texture._generateStencilBuffer = generateStencilBuffer;
  9421. this.resetTextureCache();
  9422. this._loadedTexturesCache.push(texture);
  9423. return texture;
  9424. };
  9425. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9426. var generateMipMaps = false;
  9427. var generateDepthBuffer = true;
  9428. var generateStencilBuffer = false;
  9429. var generateDepthTexture = false;
  9430. var textureCount = 1;
  9431. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9432. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9433. var types = [], samplingModes = [];
  9434. if (options !== undefined) {
  9435. generateMipMaps = options.generateMipMaps;
  9436. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9437. generateStencilBuffer = options.generateStencilBuffer;
  9438. generateDepthTexture = options.generateDepthTexture;
  9439. textureCount = options.textureCount || 1;
  9440. if (options.types) {
  9441. types = options.types;
  9442. }
  9443. if (options.samplingModes) {
  9444. samplingModes = options.samplingModes;
  9445. }
  9446. }
  9447. var gl = this._gl;
  9448. // Create the framebuffer
  9449. var framebuffer = gl.createFramebuffer();
  9450. this.bindUnboundFramebuffer(framebuffer);
  9451. var width = size.width || size;
  9452. var height = size.height || size;
  9453. var textures = [];
  9454. var attachments = [];
  9455. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9456. for (var i = 0; i < textureCount; i++) {
  9457. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9458. var type = types[i] || defaultType;
  9459. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9460. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9461. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9462. }
  9463. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9464. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9465. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9466. }
  9467. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9468. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9469. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9470. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9471. }
  9472. var texture = gl.createTexture();
  9473. var attachment = gl["COLOR_ATTACHMENT" + i];
  9474. textures.push(texture);
  9475. attachments.push(attachment);
  9476. gl.activeTexture(gl["TEXTURE" + i]);
  9477. gl.bindTexture(gl.TEXTURE_2D, texture);
  9478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9481. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9482. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9483. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9484. if (generateMipMaps) {
  9485. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9486. }
  9487. // Unbind
  9488. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9489. texture._framebuffer = framebuffer;
  9490. texture._depthStencilBuffer = depthStencilBuffer;
  9491. texture._baseWidth = width;
  9492. texture._baseHeight = height;
  9493. texture._width = width;
  9494. texture._height = height;
  9495. texture.isReady = true;
  9496. texture.samples = 1;
  9497. texture.generateMipMaps = generateMipMaps;
  9498. texture.references = 1;
  9499. texture.samplingMode = samplingMode;
  9500. texture.type = type;
  9501. texture._generateDepthBuffer = generateDepthBuffer;
  9502. texture._generateStencilBuffer = generateStencilBuffer;
  9503. this._loadedTexturesCache.push(texture);
  9504. }
  9505. if (generateDepthTexture) {
  9506. // Depth texture
  9507. var depthTexture = gl.createTexture();
  9508. gl.activeTexture(gl.TEXTURE0);
  9509. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9510. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9511. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9512. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9513. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9514. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9515. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9516. depthTexture._framebuffer = framebuffer;
  9517. depthTexture._baseWidth = width;
  9518. depthTexture._baseHeight = height;
  9519. depthTexture._width = width;
  9520. depthTexture._height = height;
  9521. depthTexture.isReady = true;
  9522. depthTexture.samples = 1;
  9523. depthTexture.generateMipMaps = generateMipMaps;
  9524. depthTexture.references = 1;
  9525. depthTexture.samplingMode = gl.NEAREST;
  9526. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9527. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9528. textures.push(depthTexture);
  9529. this._loadedTexturesCache.push(depthTexture);
  9530. }
  9531. gl.drawBuffers(attachments);
  9532. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9533. this.bindUnboundFramebuffer(null);
  9534. this.resetTextureCache();
  9535. return textures;
  9536. };
  9537. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9538. if (samples === void 0) { samples = 1; }
  9539. var depthStencilBuffer = null;
  9540. var gl = this._gl;
  9541. // Create the depth/stencil buffer
  9542. if (generateStencilBuffer) {
  9543. depthStencilBuffer = gl.createRenderbuffer();
  9544. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9545. if (samples > 1) {
  9546. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  9547. }
  9548. else {
  9549. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9550. }
  9551. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9552. }
  9553. else if (generateDepthBuffer) {
  9554. depthStencilBuffer = gl.createRenderbuffer();
  9555. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9556. if (samples > 1) {
  9557. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9558. }
  9559. else {
  9560. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9561. }
  9562. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9563. }
  9564. return depthStencilBuffer;
  9565. };
  9566. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9567. if (this.webGLVersion < 2) {
  9568. return 1;
  9569. }
  9570. if (texture.samples === samples) {
  9571. return samples;
  9572. }
  9573. var gl = this._gl;
  9574. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9575. // Dispose previous render buffers
  9576. if (texture._depthStencilBuffer) {
  9577. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9578. }
  9579. if (texture._MSAAFramebuffer) {
  9580. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9581. }
  9582. if (texture._MSAARenderBuffer) {
  9583. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9584. }
  9585. if (samples > 1) {
  9586. texture._MSAAFramebuffer = gl.createFramebuffer();
  9587. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9588. var colorRenderbuffer = gl.createRenderbuffer();
  9589. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9590. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9591. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9592. texture._MSAARenderBuffer = colorRenderbuffer;
  9593. }
  9594. else {
  9595. this.bindUnboundFramebuffer(texture._framebuffer);
  9596. }
  9597. texture.samples = samples;
  9598. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9599. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9600. this.bindUnboundFramebuffer(null);
  9601. return samples;
  9602. };
  9603. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  9604. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  9605. };
  9606. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  9607. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  9608. };
  9609. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9610. var gl = this._gl;
  9611. var texture = gl.createTexture();
  9612. var generateMipMaps = true;
  9613. var generateDepthBuffer = true;
  9614. var generateStencilBuffer = false;
  9615. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9616. if (options !== undefined) {
  9617. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9618. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9619. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9620. if (options.samplingMode !== undefined) {
  9621. samplingMode = options.samplingMode;
  9622. }
  9623. }
  9624. texture.isCube = true;
  9625. texture.references = 1;
  9626. texture.generateMipMaps = generateMipMaps;
  9627. texture.references = 1;
  9628. texture.samples = 1;
  9629. texture.samplingMode = samplingMode;
  9630. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9631. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9632. for (var face = 0; face < 6; face++) {
  9633. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9634. }
  9635. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9639. // Create the framebuffer
  9640. var framebuffer = gl.createFramebuffer();
  9641. this.bindUnboundFramebuffer(framebuffer);
  9642. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9643. // Mipmaps
  9644. if (texture.generateMipMaps) {
  9645. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9646. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9647. }
  9648. // Unbind
  9649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9650. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9651. this.bindUnboundFramebuffer(null);
  9652. texture._framebuffer = framebuffer;
  9653. texture._width = size;
  9654. texture._height = size;
  9655. texture.isReady = true;
  9656. this.resetTextureCache();
  9657. this._loadedTexturesCache.push(texture);
  9658. return texture;
  9659. };
  9660. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format) {
  9661. var _this = this;
  9662. if (onError === void 0) { onError = null; }
  9663. var callback = function (loadData) {
  9664. if (_this._caps.textureLOD || !loadData) {
  9665. // Do not add extra process if texture lod is supported.
  9666. if (onLoad) {
  9667. onLoad();
  9668. }
  9669. return;
  9670. }
  9671. var mipSlices = 3;
  9672. var gl = _this._gl;
  9673. var width = loadData.width;
  9674. if (!width) {
  9675. return;
  9676. }
  9677. var textures = [];
  9678. for (var i = 0; i < mipSlices; i++) {
  9679. //compute LOD from even spacing in smoothness (matching shader calculation)
  9680. var smoothness = i / (mipSlices - 1);
  9681. var roughness = 1 - smoothness;
  9682. var minLODIndex = offset; // roughness = 0
  9683. var maxLODIndex = BABYLON.MathTools.Log2(width) * scale + offset; // roughness = 1
  9684. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  9685. var mipmapIndex = Math.min(Math.max(Math.round(lodIndex), 0), maxLODIndex);
  9686. var glTextureFromLod = gl.createTexture();
  9687. glTextureFromLod.isCube = true;
  9688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  9689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9693. if (loadData.isDDS) {
  9694. var info = loadData.info;
  9695. var data = loadData.data;
  9696. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  9697. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, true, 6, mipmapIndex);
  9698. }
  9699. else {
  9700. BABYLON.Tools.Warn("DDS is the only prefiltered cube map support so far.");
  9701. }
  9702. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9703. // Wrap in a base texture for easy binding.
  9704. var lodTexture = new BABYLON.BaseTexture(scene);
  9705. lodTexture.isCube = true;
  9706. lodTexture._texture = glTextureFromLod;
  9707. glTextureFromLod.isReady = true;
  9708. textures.push(lodTexture);
  9709. }
  9710. loadData.texture._lodTextureHigh = textures[2];
  9711. loadData.texture._lodTextureMid = textures[1];
  9712. loadData.texture._lodTextureLow = textures[0];
  9713. if (onLoad) {
  9714. onLoad();
  9715. }
  9716. };
  9717. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format);
  9718. };
  9719. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9720. var _this = this;
  9721. if (onLoad === void 0) { onLoad = null; }
  9722. if (onError === void 0) { onError = null; }
  9723. var gl = this._gl;
  9724. var texture = gl.createTexture();
  9725. texture.isCube = true;
  9726. texture.url = rootUrl;
  9727. texture.references = 1;
  9728. texture.onLoadedCallbacks = [];
  9729. texture.generateMipMaps = !noMipmap;
  9730. var isKTX = false;
  9731. var isDDS = false;
  9732. var lastDot = rootUrl.lastIndexOf('.');
  9733. var extension = rootUrl.substring(lastDot).toLowerCase();
  9734. if (this._textureFormatInUse) {
  9735. extension = this._textureFormatInUse;
  9736. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9737. isKTX = true;
  9738. }
  9739. else {
  9740. isDDS = (extension === ".dds");
  9741. }
  9742. if (isKTX) {
  9743. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9744. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9745. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9746. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9747. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9748. ktx.uploadLevels(_this._gl, !noMipmap);
  9749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9751. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9752. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9753. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9754. _this.resetTextureCache();
  9755. texture._width = ktx.pixelWidth;
  9756. texture._height = ktx.pixelHeight;
  9757. texture.isReady = true;
  9758. }, null, null, true, onError);
  9759. }
  9760. else if (isDDS) {
  9761. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9762. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9763. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9765. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  9766. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, data, info, loadMipmap, 6);
  9767. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9768. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9769. }
  9770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9774. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9775. _this.resetTextureCache();
  9776. texture._width = info.width;
  9777. texture._height = info.height;
  9778. texture.isReady = true;
  9779. texture.type = info.textureType;
  9780. if (onLoad) {
  9781. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  9782. }
  9783. }, null, null, true, onError);
  9784. }
  9785. else {
  9786. cascadeLoad(rootUrl, scene, function (imgs) {
  9787. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9788. var height = width;
  9789. _this._prepareWorkingCanvas();
  9790. _this._workingCanvas.width = width;
  9791. _this._workingCanvas.height = height;
  9792. var faces = [
  9793. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9794. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9795. ];
  9796. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9797. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9798. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9799. for (var index = 0; index < faces.length; index++) {
  9800. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9801. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9802. }
  9803. if (!noMipmap) {
  9804. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9805. }
  9806. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9809. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9810. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9811. _this.resetTextureCache();
  9812. texture._width = width;
  9813. texture._height = height;
  9814. texture.isReady = true;
  9815. texture.onLoadedCallbacks.forEach(function (callback) {
  9816. callback();
  9817. });
  9818. if (onLoad) {
  9819. onLoad();
  9820. }
  9821. }, files, onError);
  9822. }
  9823. this._loadedTexturesCache.push(texture);
  9824. return texture;
  9825. };
  9826. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9827. texture._width = width;
  9828. texture._height = height;
  9829. texture._size = width * height;
  9830. texture._baseWidth = width;
  9831. texture._baseHeight = height;
  9832. };
  9833. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9834. if (compression === void 0) { compression = null; }
  9835. if (level === void 0) { level = 0; }
  9836. var gl = this._gl;
  9837. var textureType = this._getWebGLTextureType(type);
  9838. var internalFormat = this._getInternalFormat(format);
  9839. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9840. var needConversion = false;
  9841. if (internalFormat === gl.RGB) {
  9842. internalFormat = gl.RGBA;
  9843. needConversion = true;
  9844. }
  9845. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9846. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9847. if (texture._width % 4 !== 0) {
  9848. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9849. }
  9850. // Data are known to be in +X +Y +Z -X -Y -Z
  9851. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  9852. var faceData = data[faceIndex];
  9853. if (compression) {
  9854. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9855. }
  9856. else {
  9857. if (needConversion) {
  9858. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9859. }
  9860. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9861. }
  9862. }
  9863. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9864. if (isPot && texture.generateMipMaps && level === 0) {
  9865. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9866. }
  9867. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9868. this.resetTextureCache();
  9869. texture.isReady = true;
  9870. };
  9871. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9872. if (compression === void 0) { compression = null; }
  9873. var gl = this._gl;
  9874. var texture = gl.createTexture();
  9875. texture.isCube = true;
  9876. texture.references = 1;
  9877. texture.generateMipMaps = generateMipMaps;
  9878. texture.format = format;
  9879. texture.type = type;
  9880. var textureType = this._getWebGLTextureType(type);
  9881. var internalFormat = this._getInternalFormat(format);
  9882. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9883. var needConversion = false;
  9884. if (internalFormat === gl.RGB) {
  9885. internalFormat = gl.RGBA;
  9886. needConversion = true;
  9887. }
  9888. var width = size;
  9889. var height = width;
  9890. texture._width = width;
  9891. texture._height = height;
  9892. // Double check on POT to generate Mips.
  9893. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9894. if (!isPot) {
  9895. generateMipMaps = false;
  9896. }
  9897. // Upload data if needed. The texture won t be ready until then.
  9898. if (data) {
  9899. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9900. }
  9901. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9902. // Filters
  9903. if (data && generateMipMaps) {
  9904. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9905. }
  9906. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9909. }
  9910. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9913. }
  9914. else {
  9915. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9918. }
  9919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9922. return texture;
  9923. };
  9924. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9925. var _this = this;
  9926. if (onLoad === void 0) { onLoad = null; }
  9927. if (onError === void 0) { onError = null; }
  9928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9929. if (invertY === void 0) { invertY = false; }
  9930. var gl = this._gl;
  9931. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9932. scene._addPendingData(texture);
  9933. texture.url = url;
  9934. this._loadedTexturesCache.push(texture);
  9935. var onerror = function () {
  9936. scene._removePendingData(texture);
  9937. if (onError) {
  9938. onError();
  9939. }
  9940. };
  9941. var internalCallback = function (data) {
  9942. var width = texture._width;
  9943. var height = texture._height;
  9944. var faceDataArrays = callback(data);
  9945. if (mipmmapGenerator) {
  9946. var textureType = _this._getWebGLTextureType(type);
  9947. var internalFormat = _this._getInternalFormat(format);
  9948. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9949. var needConversion = false;
  9950. if (internalFormat === gl.RGB) {
  9951. internalFormat = gl.RGBA;
  9952. needConversion = true;
  9953. }
  9954. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9955. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9956. var mipData = mipmmapGenerator(faceDataArrays);
  9957. for (var level = 0; level < mipData.length; level++) {
  9958. var mipSize = width >> level;
  9959. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  9960. var mipFaceData = mipData[level][faceIndex];
  9961. if (needConversion) {
  9962. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9963. }
  9964. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9965. }
  9966. }
  9967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9968. }
  9969. else {
  9970. texture.generateMipMaps = !noMipmap;
  9971. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  9972. }
  9973. texture.isReady = true;
  9974. _this.resetTextureCache();
  9975. scene._removePendingData(texture);
  9976. if (onLoad) {
  9977. onLoad();
  9978. }
  9979. };
  9980. BABYLON.Tools.LoadFile(url, function (data) {
  9981. internalCallback(data);
  9982. }, onerror, scene.database, true);
  9983. return texture;
  9984. };
  9985. ;
  9986. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9987. // Create new RGBA data container.
  9988. var rgbaData;
  9989. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9990. rgbaData = new Float32Array(width * height * 4);
  9991. }
  9992. else {
  9993. rgbaData = new Uint32Array(width * height * 4);
  9994. }
  9995. // Convert each pixel.
  9996. for (var x = 0; x < width; x++) {
  9997. for (var y = 0; y < height; y++) {
  9998. var index = (y * width + x) * 3;
  9999. var newIndex = (y * width + x) * 4;
  10000. // Map Old Value to new value.
  10001. rgbaData[newIndex + 0] = rgbData[index + 0];
  10002. rgbaData[newIndex + 1] = rgbData[index + 1];
  10003. rgbaData[newIndex + 2] = rgbData[index + 2];
  10004. // Add fully opaque alpha channel.
  10005. rgbaData[newIndex + 3] = 1;
  10006. }
  10007. }
  10008. return rgbaData;
  10009. };
  10010. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10011. var gl = this._gl;
  10012. if (texture._framebuffer) {
  10013. gl.deleteFramebuffer(texture._framebuffer);
  10014. texture._framebuffer = null;
  10015. }
  10016. if (texture._depthStencilBuffer) {
  10017. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10018. texture._depthStencilBuffer = null;
  10019. }
  10020. if (texture._MSAAFramebuffer) {
  10021. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10022. texture._MSAAFramebuffer = null;
  10023. }
  10024. if (texture._MSAARenderBuffer) {
  10025. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10026. texture._MSAARenderBuffer = null;
  10027. }
  10028. };
  10029. Engine.prototype._releaseTexture = function (texture) {
  10030. var gl = this._gl;
  10031. this._releaseFramebufferObjects(texture);
  10032. gl.deleteTexture(texture);
  10033. // Unbind channels
  10034. this.unbindAllTextures();
  10035. var index = this._loadedTexturesCache.indexOf(texture);
  10036. if (index !== -1) {
  10037. this._loadedTexturesCache.splice(index, 1);
  10038. }
  10039. // Integrated fixed lod samplers.
  10040. if (texture._lodTextureHigh) {
  10041. texture._lodTextureHigh.dispose();
  10042. }
  10043. if (texture._lodTextureMid) {
  10044. texture._lodTextureMid.dispose();
  10045. }
  10046. if (texture._lodTextureLow) {
  10047. texture._lodTextureLow.dispose();
  10048. }
  10049. };
  10050. Engine.prototype.setProgram = function (program) {
  10051. if (this._currentProgram !== program) {
  10052. this._gl.useProgram(program);
  10053. this._currentProgram = program;
  10054. }
  10055. };
  10056. Engine.prototype.bindSamplers = function (effect) {
  10057. this.setProgram(effect.getProgram());
  10058. var samplers = effect.getSamplers();
  10059. for (var index = 0; index < samplers.length; index++) {
  10060. var uniform = effect.getUniform(samplers[index]);
  10061. this._gl.uniform1i(uniform, index);
  10062. }
  10063. this._currentEffect = null;
  10064. };
  10065. Engine.prototype.activateTexture = function (texture) {
  10066. if (this._activeTexture !== texture) {
  10067. this._gl.activeTexture(texture);
  10068. this._activeTexture = texture;
  10069. }
  10070. };
  10071. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10072. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10073. this._gl.bindTexture(target, texture);
  10074. this._activeTexturesCache[this._activeTexture] = texture;
  10075. }
  10076. };
  10077. Engine.prototype._bindTexture = function (channel, texture) {
  10078. if (channel < 0) {
  10079. return;
  10080. }
  10081. this.activateTexture(this._gl.TEXTURE0 + channel);
  10082. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10083. };
  10084. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10085. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10086. };
  10087. Engine.prototype.unbindAllTextures = function () {
  10088. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10089. this.activateTexture(this._gl["TEXTURE" + channel]);
  10090. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10091. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10092. }
  10093. };
  10094. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10095. if (channel < 0) {
  10096. return;
  10097. }
  10098. this._gl.uniform1i(uniform, channel);
  10099. this._setTexture(channel, texture);
  10100. };
  10101. Engine.prototype._setTexture = function (channel, texture) {
  10102. // Not ready?
  10103. if (!texture) {
  10104. if (this._activeTexturesCache[channel] != null) {
  10105. this.activateTexture(this._gl["TEXTURE" + channel]);
  10106. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10107. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10108. }
  10109. return;
  10110. }
  10111. // Video
  10112. var alreadyActivated = false;
  10113. if (texture.video) {
  10114. this.activateTexture(this._gl["TEXTURE" + channel]);
  10115. alreadyActivated = true;
  10116. texture.update();
  10117. }
  10118. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10119. texture.delayLoad();
  10120. return;
  10121. }
  10122. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10123. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10124. if (this._activeTexturesCache[channel] === internalTexture) {
  10125. return;
  10126. }
  10127. if (!alreadyActivated) {
  10128. this.activateTexture(this._gl["TEXTURE" + channel]);
  10129. }
  10130. if (internalTexture.isCube) {
  10131. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10132. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10133. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10134. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10135. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10136. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10137. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10138. }
  10139. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10140. }
  10141. else {
  10142. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10143. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10144. internalTexture._cachedWrapU = texture.wrapU;
  10145. switch (texture.wrapU) {
  10146. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10147. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10148. break;
  10149. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10150. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10151. break;
  10152. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10153. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10154. break;
  10155. }
  10156. }
  10157. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10158. internalTexture._cachedWrapV = texture.wrapV;
  10159. switch (texture.wrapV) {
  10160. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10161. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10162. break;
  10163. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10164. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10165. break;
  10166. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10167. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10168. break;
  10169. }
  10170. }
  10171. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10172. }
  10173. };
  10174. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10175. if (channel < 0) {
  10176. return;
  10177. }
  10178. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10179. this._textureUnits = new Int32Array(textures.length);
  10180. }
  10181. for (var i = 0; i < textures.length; i++) {
  10182. this._textureUnits[i] = channel + i;
  10183. }
  10184. this._gl.uniform1iv(uniform, this._textureUnits);
  10185. for (var index = 0; index < textures.length; index++) {
  10186. this._setTexture(channel + index, textures[index]);
  10187. }
  10188. };
  10189. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10190. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10191. var value = texture.anisotropicFilteringLevel;
  10192. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10193. value = 1;
  10194. }
  10195. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10196. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10197. texture._cachedAnisotropicFilteringLevel = value;
  10198. }
  10199. };
  10200. Engine.prototype.readPixels = function (x, y, width, height) {
  10201. var data = new Uint8Array(height * width * 4);
  10202. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10203. return data;
  10204. };
  10205. /**
  10206. * Add an externaly attached data from its key.
  10207. * This method call will fail and return false, if such key already exists.
  10208. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10209. * @param key the unique key that identifies the data
  10210. * @param data the data object to associate to the key for this Engine instance
  10211. * @return true if no such key were already present and the data was added successfully, false otherwise
  10212. */
  10213. Engine.prototype.addExternalData = function (key, data) {
  10214. if (!this._externalData) {
  10215. this._externalData = new BABYLON.StringDictionary();
  10216. }
  10217. return this._externalData.add(key, data);
  10218. };
  10219. /**
  10220. * Get an externaly attached data from its key
  10221. * @param key the unique key that identifies the data
  10222. * @return the associated data, if present (can be null), or undefined if not present
  10223. */
  10224. Engine.prototype.getExternalData = function (key) {
  10225. if (!this._externalData) {
  10226. this._externalData = new BABYLON.StringDictionary();
  10227. }
  10228. return this._externalData.get(key);
  10229. };
  10230. /**
  10231. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10232. * @param key the unique key that identifies the data
  10233. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10234. * @return the associated data, can be null if the factory returned null.
  10235. */
  10236. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10237. if (!this._externalData) {
  10238. this._externalData = new BABYLON.StringDictionary();
  10239. }
  10240. return this._externalData.getOrAddWithFactory(key, factory);
  10241. };
  10242. /**
  10243. * Remove an externaly attached data from the Engine instance
  10244. * @param key the unique key that identifies the data
  10245. * @return true if the data was successfully removed, false if it doesn't exist
  10246. */
  10247. Engine.prototype.removeExternalData = function (key) {
  10248. if (!this._externalData) {
  10249. this._externalData = new BABYLON.StringDictionary();
  10250. }
  10251. return this._externalData.remove(key);
  10252. };
  10253. Engine.prototype.releaseInternalTexture = function (texture) {
  10254. if (!texture) {
  10255. return;
  10256. }
  10257. texture.references--;
  10258. // Final reference ?
  10259. if (texture.references === 0) {
  10260. var texturesCache = this.getLoadedTexturesCache();
  10261. var index = texturesCache.indexOf(texture);
  10262. if (index > -1) {
  10263. texturesCache.splice(index, 1);
  10264. }
  10265. this._releaseTexture(texture);
  10266. }
  10267. };
  10268. Engine.prototype.unbindAllAttributes = function () {
  10269. if (this._mustWipeVertexAttributes) {
  10270. this._mustWipeVertexAttributes = false;
  10271. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10272. this._gl.disableVertexAttribArray(i);
  10273. this._vertexAttribArraysEnabled[i] = false;
  10274. this._currentBufferPointers[i] = null;
  10275. }
  10276. return;
  10277. }
  10278. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10279. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10280. continue;
  10281. }
  10282. this._gl.disableVertexAttribArray(i);
  10283. this._vertexAttribArraysEnabled[i] = false;
  10284. this._currentBufferPointers[i] = null;
  10285. }
  10286. };
  10287. Engine.prototype.releaseEffects = function () {
  10288. for (var name in this._compiledEffects) {
  10289. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10290. }
  10291. this._compiledEffects = {};
  10292. };
  10293. // Dispose
  10294. Engine.prototype.dispose = function () {
  10295. this.hideLoadingUI();
  10296. this.stopRenderLoop();
  10297. // Empty texture
  10298. if (this._emptyTexture) {
  10299. this._releaseTexture(this._emptyTexture);
  10300. this._emptyTexture = null;
  10301. }
  10302. if (this._emptyCubeTexture) {
  10303. this._releaseTexture(this._emptyCubeTexture);
  10304. this._emptyCubeTexture = null;
  10305. }
  10306. // Release scenes
  10307. while (this.scenes.length) {
  10308. this.scenes[0].dispose();
  10309. }
  10310. // Release audio engine
  10311. if (Engine.audioEngine) {
  10312. Engine.audioEngine.dispose();
  10313. }
  10314. // Release effects
  10315. this.releaseEffects();
  10316. // Unbind
  10317. this.unbindAllAttributes();
  10318. if (this._dummyFramebuffer) {
  10319. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10320. }
  10321. this._gl = null;
  10322. //WebVR
  10323. this.disableVR();
  10324. // Events
  10325. window.removeEventListener("blur", this._onBlur);
  10326. window.removeEventListener("focus", this._onFocus);
  10327. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10328. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10329. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10330. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10331. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10332. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10333. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10334. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10335. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10336. // Remove from Instances
  10337. var index = Engine.Instances.indexOf(this);
  10338. if (index >= 0) {
  10339. Engine.Instances.splice(index, 1);
  10340. }
  10341. };
  10342. // Loading screen
  10343. Engine.prototype.displayLoadingUI = function () {
  10344. var loadingScreen = this.loadingScreen;
  10345. if (loadingScreen) {
  10346. loadingScreen.displayLoadingUI();
  10347. }
  10348. };
  10349. Engine.prototype.hideLoadingUI = function () {
  10350. var loadingScreen = this.loadingScreen;
  10351. if (loadingScreen) {
  10352. loadingScreen.hideLoadingUI();
  10353. }
  10354. };
  10355. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10356. get: function () {
  10357. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10358. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10359. return this._loadingScreen;
  10360. },
  10361. set: function (loadingScreen) {
  10362. this._loadingScreen = loadingScreen;
  10363. },
  10364. enumerable: true,
  10365. configurable: true
  10366. });
  10367. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10368. set: function (text) {
  10369. this.loadingScreen.loadingUIText = text;
  10370. },
  10371. enumerable: true,
  10372. configurable: true
  10373. });
  10374. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10375. set: function (color) {
  10376. this.loadingScreen.loadingUIBackgroundColor = color;
  10377. },
  10378. enumerable: true,
  10379. configurable: true
  10380. });
  10381. Engine.prototype.attachContextLostEvent = function (callback) {
  10382. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10383. };
  10384. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10385. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10386. };
  10387. Engine.prototype.getVertexShaderSource = function (program) {
  10388. var shaders = this._gl.getAttachedShaders(program);
  10389. return this._gl.getShaderSource(shaders[0]);
  10390. };
  10391. Engine.prototype.getFragmentShaderSource = function (program) {
  10392. var shaders = this._gl.getAttachedShaders(program);
  10393. return this._gl.getShaderSource(shaders[1]);
  10394. };
  10395. Engine.prototype.getError = function () {
  10396. return this._gl.getError();
  10397. };
  10398. // FPS
  10399. Engine.prototype.getFps = function () {
  10400. return this.fps;
  10401. };
  10402. Engine.prototype.getDeltaTime = function () {
  10403. return this.deltaTime;
  10404. };
  10405. Engine.prototype._measureFps = function () {
  10406. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10407. var length = this.previousFramesDuration.length;
  10408. if (length >= 2) {
  10409. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10410. }
  10411. if (length >= this.fpsRange) {
  10412. if (length > this.fpsRange) {
  10413. this.previousFramesDuration.splice(0, 1);
  10414. length = this.previousFramesDuration.length;
  10415. }
  10416. var sum = 0;
  10417. for (var id = 0; id < length - 1; id++) {
  10418. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10419. }
  10420. this.fps = 1000.0 / (sum / (length - 1));
  10421. }
  10422. };
  10423. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10424. if (faceIndex === void 0) { faceIndex = -1; }
  10425. var gl = this._gl;
  10426. if (!this._dummyFramebuffer) {
  10427. this._dummyFramebuffer = gl.createFramebuffer();
  10428. }
  10429. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10430. if (faceIndex > -1) {
  10431. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10432. }
  10433. else {
  10434. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10435. }
  10436. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10437. var buffer;
  10438. switch (readType) {
  10439. case gl.UNSIGNED_BYTE:
  10440. buffer = new Uint8Array(4 * width * height);
  10441. readType = gl.UNSIGNED_BYTE;
  10442. break;
  10443. default:
  10444. buffer = new Float32Array(4 * width * height);
  10445. readType = gl.FLOAT;
  10446. break;
  10447. }
  10448. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10449. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10450. return buffer;
  10451. };
  10452. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10453. if (this._webGLVersion > 1) {
  10454. return this._caps.colorBufferFloat;
  10455. }
  10456. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10457. };
  10458. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10459. if (this._webGLVersion > 1) {
  10460. return this._caps.colorBufferFloat;
  10461. }
  10462. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10463. };
  10464. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10465. Engine.prototype._canRenderToFramebuffer = function (type) {
  10466. var gl = this._gl;
  10467. //clear existing errors
  10468. while (gl.getError() !== gl.NO_ERROR) { }
  10469. var successful = true;
  10470. var texture = gl.createTexture();
  10471. gl.bindTexture(gl.TEXTURE_2D, texture);
  10472. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10473. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10475. var fb = gl.createFramebuffer();
  10476. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10477. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10478. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10479. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10480. successful = successful && (gl.getError() === gl.NO_ERROR);
  10481. //try render by clearing frame buffer's color buffer
  10482. if (successful) {
  10483. gl.clear(gl.COLOR_BUFFER_BIT);
  10484. successful = successful && (gl.getError() === gl.NO_ERROR);
  10485. }
  10486. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10487. if (successful) {
  10488. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10489. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10490. var readFormat = gl.RGBA;
  10491. var readType = gl.UNSIGNED_BYTE;
  10492. var buffer = new Uint8Array(4);
  10493. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10494. successful = successful && (gl.getError() === gl.NO_ERROR);
  10495. }
  10496. //clean up
  10497. gl.deleteTexture(texture);
  10498. gl.deleteFramebuffer(fb);
  10499. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10500. //clear accumulated errors
  10501. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10502. return successful;
  10503. };
  10504. Engine.prototype._getWebGLTextureType = function (type) {
  10505. if (type === Engine.TEXTURETYPE_FLOAT) {
  10506. return this._gl.FLOAT;
  10507. }
  10508. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10509. // Add Half Float Constant.
  10510. return this._gl.HALF_FLOAT_OES;
  10511. }
  10512. return this._gl.UNSIGNED_BYTE;
  10513. };
  10514. ;
  10515. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10516. if (this._webGLVersion === 1) {
  10517. return this._gl.RGBA;
  10518. }
  10519. if (type === Engine.TEXTURETYPE_FLOAT) {
  10520. return this._gl.RGBA32F;
  10521. }
  10522. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10523. return this._gl.RGBA16F;
  10524. }
  10525. return this._gl.RGBA;
  10526. };
  10527. ;
  10528. // Statics
  10529. Engine.isSupported = function () {
  10530. try {
  10531. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10532. if (navigator.isCocoonJS) {
  10533. return true;
  10534. }
  10535. var tempcanvas = document.createElement("canvas");
  10536. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10537. return gl != null && !!window.WebGLRenderingContext;
  10538. }
  10539. catch (e) {
  10540. return false;
  10541. }
  10542. };
  10543. return Engine;
  10544. }());
  10545. Engine.Instances = new Array();
  10546. // Const statics
  10547. Engine._ALPHA_DISABLE = 0;
  10548. Engine._ALPHA_ADD = 1;
  10549. Engine._ALPHA_COMBINE = 2;
  10550. Engine._ALPHA_SUBTRACT = 3;
  10551. Engine._ALPHA_MULTIPLY = 4;
  10552. Engine._ALPHA_MAXIMIZED = 5;
  10553. Engine._ALPHA_ONEONE = 6;
  10554. Engine._ALPHA_PREMULTIPLIED = 7;
  10555. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10556. Engine._ALPHA_INTERPOLATE = 9;
  10557. Engine._ALPHA_SCREENMODE = 10;
  10558. Engine._DELAYLOADSTATE_NONE = 0;
  10559. Engine._DELAYLOADSTATE_LOADED = 1;
  10560. Engine._DELAYLOADSTATE_LOADING = 2;
  10561. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10562. Engine._TEXTUREFORMAT_ALPHA = 0;
  10563. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10564. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10565. Engine._TEXTUREFORMAT_RGB = 4;
  10566. Engine._TEXTUREFORMAT_RGBA = 5;
  10567. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10568. Engine._TEXTURETYPE_FLOAT = 1;
  10569. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10570. // Depht or Stencil test Constants.
  10571. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10572. 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.
  10573. 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.
  10574. 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.
  10575. 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.
  10576. 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.
  10577. 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.
  10578. 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.
  10579. // Stencil Actions Constants.
  10580. Engine._KEEP = 0x1E00;
  10581. Engine._REPLACE = 0x1E01;
  10582. Engine._INCR = 0x1E02;
  10583. Engine._DECR = 0x1E03;
  10584. Engine._INVERT = 0x150A;
  10585. Engine._INCR_WRAP = 0x8507;
  10586. Engine._DECR_WRAP = 0x8508;
  10587. // Texture rescaling mode
  10588. Engine._SCALEMODE_FLOOR = 1;
  10589. Engine._SCALEMODE_NEAREST = 2;
  10590. Engine._SCALEMODE_CEILING = 3;
  10591. // Updatable statics so stick with vars here
  10592. Engine.CollisionsEpsilon = 0.001;
  10593. Engine.CodeRepository = "src/";
  10594. Engine.ShadersRepository = "src/Shaders/";
  10595. BABYLON.Engine = Engine;
  10596. })(BABYLON || (BABYLON = {}));
  10597. //# sourceMappingURL=babylon.engine.js.map
  10598. /// <reference path="Tools\babylon.decorators.ts" />
  10599. var BABYLON;
  10600. (function (BABYLON) {
  10601. /**
  10602. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10603. */
  10604. var Node = (function () {
  10605. /**
  10606. * @constructor
  10607. * @param {string} name - the name and id to be given to this node
  10608. * @param {BABYLON.Scene} the scene this node will be added to
  10609. */
  10610. function Node(name, scene) {
  10611. this.state = "";
  10612. this.metadata = null;
  10613. this.doNotSerialize = false;
  10614. this.animations = new Array();
  10615. this._ranges = {};
  10616. this._childrenFlag = -1;
  10617. this._isEnabled = true;
  10618. this._isReady = true;
  10619. this._currentRenderId = -1;
  10620. this._parentRenderId = -1;
  10621. /**
  10622. * An event triggered when the mesh is disposed.
  10623. * @type {BABYLON.Observable}
  10624. */
  10625. this.onDisposeObservable = new BABYLON.Observable();
  10626. this.name = name;
  10627. this.id = name;
  10628. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10629. this._initCache();
  10630. }
  10631. Object.defineProperty(Node.prototype, "parent", {
  10632. get: function () {
  10633. return this._parentNode;
  10634. },
  10635. set: function (parent) {
  10636. if (this._parentNode === parent) {
  10637. return;
  10638. }
  10639. if (this._parentNode) {
  10640. var index = this._parentNode._children.indexOf(this);
  10641. if (index !== -1) {
  10642. this._parentNode._children.splice(index, 1);
  10643. }
  10644. }
  10645. this._parentNode = parent;
  10646. if (this._parentNode) {
  10647. if (!this._parentNode._children) {
  10648. this._parentNode._children = new Array();
  10649. }
  10650. this._parentNode._children.push(this);
  10651. }
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Node.prototype.getClassName = function () {
  10657. return "Node";
  10658. };
  10659. Object.defineProperty(Node.prototype, "onDispose", {
  10660. set: function (callback) {
  10661. if (this._onDisposeObserver) {
  10662. this.onDisposeObservable.remove(this._onDisposeObserver);
  10663. }
  10664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Node.prototype.getScene = function () {
  10670. return this._scene;
  10671. };
  10672. Node.prototype.getEngine = function () {
  10673. return this._scene.getEngine();
  10674. };
  10675. // override it in derived class
  10676. Node.prototype.getWorldMatrix = function () {
  10677. return BABYLON.Matrix.Identity();
  10678. };
  10679. // override it in derived class if you add new variables to the cache
  10680. // and call the parent class method
  10681. Node.prototype._initCache = function () {
  10682. this._cache = {};
  10683. this._cache.parent = undefined;
  10684. };
  10685. Node.prototype.updateCache = function (force) {
  10686. if (!force && this.isSynchronized())
  10687. return;
  10688. this._cache.parent = this.parent;
  10689. this._updateCache();
  10690. };
  10691. // override it in derived class if you add new variables to the cache
  10692. // and call the parent class method if !ignoreParentClass
  10693. Node.prototype._updateCache = function (ignoreParentClass) {
  10694. };
  10695. // override it in derived class if you add new variables to the cache
  10696. Node.prototype._isSynchronized = function () {
  10697. return true;
  10698. };
  10699. Node.prototype._markSyncedWithParent = function () {
  10700. this._parentRenderId = this.parent._currentRenderId;
  10701. };
  10702. Node.prototype.isSynchronizedWithParent = function () {
  10703. if (!this.parent) {
  10704. return true;
  10705. }
  10706. if (this._parentRenderId !== this.parent._currentRenderId) {
  10707. return false;
  10708. }
  10709. return this.parent.isSynchronized();
  10710. };
  10711. Node.prototype.isSynchronized = function (updateCache) {
  10712. var check = this.hasNewParent();
  10713. check = check || !this.isSynchronizedWithParent();
  10714. check = check || !this._isSynchronized();
  10715. if (updateCache)
  10716. this.updateCache(true);
  10717. return !check;
  10718. };
  10719. Node.prototype.hasNewParent = function (update) {
  10720. if (this._cache.parent === this.parent)
  10721. return false;
  10722. if (update)
  10723. this._cache.parent = this.parent;
  10724. return true;
  10725. };
  10726. /**
  10727. * Is this node ready to be used/rendered
  10728. * @return {boolean} is it ready
  10729. */
  10730. Node.prototype.isReady = function () {
  10731. return this._isReady;
  10732. };
  10733. /**
  10734. * Is this node enabled.
  10735. * If the node has a parent and is enabled, the parent will be inspected as well.
  10736. * @return {boolean} whether this node (and its parent) is enabled.
  10737. * @see setEnabled
  10738. */
  10739. Node.prototype.isEnabled = function () {
  10740. if (!this._isEnabled) {
  10741. return false;
  10742. }
  10743. if (this.parent) {
  10744. return this.parent.isEnabled();
  10745. }
  10746. return true;
  10747. };
  10748. /**
  10749. * Set the enabled state of this node.
  10750. * @param {boolean} value - the new enabled state
  10751. * @see isEnabled
  10752. */
  10753. Node.prototype.setEnabled = function (value) {
  10754. this._isEnabled = value;
  10755. };
  10756. /**
  10757. * Is this node a descendant of the given node.
  10758. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10759. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10760. * @see parent
  10761. */
  10762. Node.prototype.isDescendantOf = function (ancestor) {
  10763. if (this.parent) {
  10764. if (this.parent === ancestor) {
  10765. return true;
  10766. }
  10767. return this.parent.isDescendantOf(ancestor);
  10768. }
  10769. return false;
  10770. };
  10771. /**
  10772. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10773. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10774. * @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.
  10775. * @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.
  10776. */
  10777. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10778. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10779. if (!this._children) {
  10780. return;
  10781. }
  10782. for (var index = 0; index < this._children.length; index++) {
  10783. var item = this._children[index];
  10784. if (!predicate || predicate(item)) {
  10785. results.push(item);
  10786. }
  10787. if (!directDescendantsOnly) {
  10788. item._getDescendants(results, false, predicate);
  10789. }
  10790. }
  10791. };
  10792. /**
  10793. * Will return all nodes that have this node as ascendant.
  10794. * @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.
  10795. * @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.
  10796. * @return {BABYLON.Node[]} all children nodes of all types.
  10797. */
  10798. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10799. var results = [];
  10800. this._getDescendants(results, directDescendantsOnly, predicate);
  10801. return results;
  10802. };
  10803. /**
  10804. * Get all child-meshes of this node.
  10805. */
  10806. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10807. var results = [];
  10808. this._getDescendants(results, directDecendantsOnly, function (node) {
  10809. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10810. });
  10811. return results;
  10812. };
  10813. /**
  10814. * Get all direct children of this node.
  10815. */
  10816. Node.prototype.getChildren = function (predicate) {
  10817. return this.getDescendants(true, predicate);
  10818. };
  10819. Node.prototype._setReady = function (state) {
  10820. if (state === this._isReady) {
  10821. return;
  10822. }
  10823. if (!state) {
  10824. this._isReady = false;
  10825. return;
  10826. }
  10827. this._isReady = true;
  10828. if (this.onReady) {
  10829. this.onReady(this);
  10830. }
  10831. };
  10832. Node.prototype.getAnimationByName = function (name) {
  10833. for (var i = 0; i < this.animations.length; i++) {
  10834. var animation = this.animations[i];
  10835. if (animation.name === name) {
  10836. return animation;
  10837. }
  10838. }
  10839. return null;
  10840. };
  10841. Node.prototype.createAnimationRange = function (name, from, to) {
  10842. // check name not already in use
  10843. if (!this._ranges[name]) {
  10844. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10845. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10846. if (this.animations[i]) {
  10847. this.animations[i].createRange(name, from, to);
  10848. }
  10849. }
  10850. }
  10851. };
  10852. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10853. if (deleteFrames === void 0) { deleteFrames = true; }
  10854. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10855. if (this.animations[i]) {
  10856. this.animations[i].deleteRange(name, deleteFrames);
  10857. }
  10858. }
  10859. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10860. };
  10861. Node.prototype.getAnimationRange = function (name) {
  10862. return this._ranges[name];
  10863. };
  10864. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10865. var range = this.getAnimationRange(name);
  10866. if (!range) {
  10867. return null;
  10868. }
  10869. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10870. };
  10871. Node.prototype.serializeAnimationRanges = function () {
  10872. var serializationRanges = [];
  10873. for (var name in this._ranges) {
  10874. var range = {};
  10875. range.name = name;
  10876. range.from = this._ranges[name].from;
  10877. range.to = this._ranges[name].to;
  10878. serializationRanges.push(range);
  10879. }
  10880. return serializationRanges;
  10881. };
  10882. Node.prototype.dispose = function () {
  10883. this.parent = null;
  10884. // Callback
  10885. this.onDisposeObservable.notifyObservers(this);
  10886. this.onDisposeObservable.clear();
  10887. };
  10888. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10889. if (parsedNode.ranges) {
  10890. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10891. var data = parsedNode.ranges[index];
  10892. node.createAnimationRange(data.name, data.from, data.to);
  10893. }
  10894. }
  10895. };
  10896. return Node;
  10897. }());
  10898. __decorate([
  10899. BABYLON.serialize()
  10900. ], Node.prototype, "name", void 0);
  10901. __decorate([
  10902. BABYLON.serialize()
  10903. ], Node.prototype, "id", void 0);
  10904. __decorate([
  10905. BABYLON.serialize()
  10906. ], Node.prototype, "uniqueId", void 0);
  10907. __decorate([
  10908. BABYLON.serialize()
  10909. ], Node.prototype, "state", void 0);
  10910. __decorate([
  10911. BABYLON.serialize()
  10912. ], Node.prototype, "metadata", void 0);
  10913. BABYLON.Node = Node;
  10914. })(BABYLON || (BABYLON = {}));
  10915. //# sourceMappingURL=babylon.node.js.map
  10916. var BABYLON;
  10917. (function (BABYLON) {
  10918. var BoundingSphere = (function () {
  10919. function BoundingSphere(minimum, maximum) {
  10920. this.minimum = minimum;
  10921. this.maximum = maximum;
  10922. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10923. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10924. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10925. this.radius = distance * 0.5;
  10926. this.centerWorld = BABYLON.Vector3.Zero();
  10927. this._update(BABYLON.Matrix.Identity());
  10928. }
  10929. // Methods
  10930. BoundingSphere.prototype._update = function (world) {
  10931. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10932. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10933. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10934. };
  10935. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10936. for (var i = 0; i < 6; i++) {
  10937. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10938. return false;
  10939. }
  10940. return true;
  10941. };
  10942. BoundingSphere.prototype.intersectsPoint = function (point) {
  10943. var x = this.centerWorld.x - point.x;
  10944. var y = this.centerWorld.y - point.y;
  10945. var z = this.centerWorld.z - point.z;
  10946. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10947. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10948. return false;
  10949. return true;
  10950. };
  10951. // Statics
  10952. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10953. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10954. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10955. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10956. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10957. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10958. return false;
  10959. return true;
  10960. };
  10961. return BoundingSphere;
  10962. }());
  10963. BABYLON.BoundingSphere = BoundingSphere;
  10964. })(BABYLON || (BABYLON = {}));
  10965. //# sourceMappingURL=babylon.boundingSphere.js.map
  10966. var BABYLON;
  10967. (function (BABYLON) {
  10968. var BoundingBox = (function () {
  10969. function BoundingBox(minimum, maximum) {
  10970. this.minimum = minimum;
  10971. this.maximum = maximum;
  10972. this.vectors = new Array();
  10973. this.vectorsWorld = new Array();
  10974. // Bounding vectors
  10975. this.vectors.push(this.minimum.clone());
  10976. this.vectors.push(this.maximum.clone());
  10977. this.vectors.push(this.minimum.clone());
  10978. this.vectors[2].x = this.maximum.x;
  10979. this.vectors.push(this.minimum.clone());
  10980. this.vectors[3].y = this.maximum.y;
  10981. this.vectors.push(this.minimum.clone());
  10982. this.vectors[4].z = this.maximum.z;
  10983. this.vectors.push(this.maximum.clone());
  10984. this.vectors[5].z = this.minimum.z;
  10985. this.vectors.push(this.maximum.clone());
  10986. this.vectors[6].x = this.minimum.x;
  10987. this.vectors.push(this.maximum.clone());
  10988. this.vectors[7].y = this.minimum.y;
  10989. // OBB
  10990. this.center = this.maximum.add(this.minimum).scale(0.5);
  10991. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10992. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10993. // World
  10994. for (var index = 0; index < this.vectors.length; index++) {
  10995. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10996. }
  10997. this.minimumWorld = BABYLON.Vector3.Zero();
  10998. this.maximumWorld = BABYLON.Vector3.Zero();
  10999. this.centerWorld = BABYLON.Vector3.Zero();
  11000. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11001. this._update(BABYLON.Matrix.Identity());
  11002. }
  11003. // Methods
  11004. BoundingBox.prototype.getWorldMatrix = function () {
  11005. return this._worldMatrix;
  11006. };
  11007. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11008. this._worldMatrix.copyFrom(matrix);
  11009. return this;
  11010. };
  11011. BoundingBox.prototype._update = function (world) {
  11012. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11013. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11014. for (var index = 0; index < this.vectors.length; index++) {
  11015. var v = this.vectorsWorld[index];
  11016. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11017. if (v.x < this.minimumWorld.x)
  11018. this.minimumWorld.x = v.x;
  11019. if (v.y < this.minimumWorld.y)
  11020. this.minimumWorld.y = v.y;
  11021. if (v.z < this.minimumWorld.z)
  11022. this.minimumWorld.z = v.z;
  11023. if (v.x > this.maximumWorld.x)
  11024. this.maximumWorld.x = v.x;
  11025. if (v.y > this.maximumWorld.y)
  11026. this.maximumWorld.y = v.y;
  11027. if (v.z > this.maximumWorld.z)
  11028. this.maximumWorld.z = v.z;
  11029. }
  11030. // Extend
  11031. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11032. this.extendSizeWorld.scaleInPlace(0.5);
  11033. // OBB
  11034. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11035. this.centerWorld.scaleInPlace(0.5);
  11036. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11037. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11038. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11039. this._worldMatrix = world;
  11040. };
  11041. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11042. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11043. };
  11044. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11045. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11046. };
  11047. BoundingBox.prototype.intersectsPoint = function (point) {
  11048. var delta = -BABYLON.Epsilon;
  11049. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11050. return false;
  11051. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11052. return false;
  11053. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11054. return false;
  11055. return true;
  11056. };
  11057. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11058. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11059. };
  11060. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11061. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11062. return false;
  11063. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11064. return false;
  11065. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11066. return false;
  11067. return true;
  11068. };
  11069. // Statics
  11070. BoundingBox.Intersects = function (box0, box1) {
  11071. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11072. return false;
  11073. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11074. return false;
  11075. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11076. return false;
  11077. return true;
  11078. };
  11079. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11080. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11081. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11082. return (num <= (sphereRadius * sphereRadius));
  11083. };
  11084. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11085. for (var p = 0; p < 6; p++) {
  11086. for (var i = 0; i < 8; i++) {
  11087. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11088. return false;
  11089. }
  11090. }
  11091. }
  11092. return true;
  11093. };
  11094. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11095. for (var p = 0; p < 6; p++) {
  11096. var inCount = 8;
  11097. for (var i = 0; i < 8; i++) {
  11098. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11099. --inCount;
  11100. }
  11101. else {
  11102. break;
  11103. }
  11104. }
  11105. if (inCount === 0)
  11106. return false;
  11107. }
  11108. return true;
  11109. };
  11110. return BoundingBox;
  11111. }());
  11112. BABYLON.BoundingBox = BoundingBox;
  11113. })(BABYLON || (BABYLON = {}));
  11114. //# sourceMappingURL=babylon.boundingBox.js.map
  11115. var BABYLON;
  11116. (function (BABYLON) {
  11117. var computeBoxExtents = function (axis, box) {
  11118. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11119. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11120. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11121. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11122. var r = r0 + r1 + r2;
  11123. return {
  11124. min: p - r,
  11125. max: p + r
  11126. };
  11127. };
  11128. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11129. var axisOverlap = function (axis, box0, box1) {
  11130. var result0 = computeBoxExtents(axis, box0);
  11131. var result1 = computeBoxExtents(axis, box1);
  11132. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11133. };
  11134. var BoundingInfo = (function () {
  11135. function BoundingInfo(minimum, maximum) {
  11136. this.minimum = minimum;
  11137. this.maximum = maximum;
  11138. this._isLocked = false;
  11139. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11140. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11141. }
  11142. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11143. get: function () {
  11144. return this._isLocked;
  11145. },
  11146. set: function (value) {
  11147. this._isLocked = value;
  11148. },
  11149. enumerable: true,
  11150. configurable: true
  11151. });
  11152. // Methods
  11153. BoundingInfo.prototype.update = function (world) {
  11154. if (this._isLocked) {
  11155. return;
  11156. }
  11157. this.boundingBox._update(world);
  11158. this.boundingSphere._update(world);
  11159. };
  11160. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11161. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11162. return false;
  11163. return this.boundingBox.isInFrustum(frustumPlanes);
  11164. };
  11165. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11166. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11167. };
  11168. BoundingInfo.prototype._checkCollision = function (collider) {
  11169. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11170. };
  11171. BoundingInfo.prototype.intersectsPoint = function (point) {
  11172. if (!this.boundingSphere.centerWorld) {
  11173. return false;
  11174. }
  11175. if (!this.boundingSphere.intersectsPoint(point)) {
  11176. return false;
  11177. }
  11178. if (!this.boundingBox.intersectsPoint(point)) {
  11179. return false;
  11180. }
  11181. return true;
  11182. };
  11183. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11184. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11185. return false;
  11186. }
  11187. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11188. return false;
  11189. }
  11190. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11191. return false;
  11192. }
  11193. if (!precise) {
  11194. return true;
  11195. }
  11196. var box0 = this.boundingBox;
  11197. var box1 = boundingInfo.boundingBox;
  11198. if (!axisOverlap(box0.directions[0], box0, box1))
  11199. return false;
  11200. if (!axisOverlap(box0.directions[1], box0, box1))
  11201. return false;
  11202. if (!axisOverlap(box0.directions[2], box0, box1))
  11203. return false;
  11204. if (!axisOverlap(box1.directions[0], box0, box1))
  11205. return false;
  11206. if (!axisOverlap(box1.directions[1], box0, box1))
  11207. return false;
  11208. if (!axisOverlap(box1.directions[2], box0, box1))
  11209. return false;
  11210. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11211. return false;
  11212. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11213. return false;
  11214. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11215. return false;
  11216. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11217. return false;
  11218. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11219. return false;
  11220. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11221. return false;
  11222. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11223. return false;
  11224. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11225. return false;
  11226. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11227. return false;
  11228. return true;
  11229. };
  11230. return BoundingInfo;
  11231. }());
  11232. BABYLON.BoundingInfo = BoundingInfo;
  11233. })(BABYLON || (BABYLON = {}));
  11234. //# sourceMappingURL=babylon.boundingInfo.js.map
  11235. var BABYLON;
  11236. (function (BABYLON) {
  11237. var AbstractMesh = (function (_super) {
  11238. __extends(AbstractMesh, _super);
  11239. // Constructor
  11240. function AbstractMesh(name, scene) {
  11241. var _this = _super.call(this, name, scene) || this;
  11242. _this._facetNb = 0; // facet number
  11243. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11244. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11245. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11246. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11247. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11248. _this._subDiv = {
  11249. max: 1,
  11250. X: 1,
  11251. Y: 1,
  11252. Z: 1
  11253. };
  11254. // Events
  11255. /**
  11256. * An event triggered when this mesh collides with another one
  11257. * @type {BABYLON.Observable}
  11258. */
  11259. _this.onCollideObservable = new BABYLON.Observable();
  11260. /**
  11261. * An event triggered when the collision's position changes
  11262. * @type {BABYLON.Observable}
  11263. */
  11264. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11265. /**
  11266. * An event triggered after the world matrix is updated
  11267. * @type {BABYLON.Observable}
  11268. */
  11269. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11270. // Properties
  11271. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11272. _this.position = BABYLON.Vector3.Zero();
  11273. _this._rotation = BABYLON.Vector3.Zero();
  11274. _this._scaling = BABYLON.Vector3.One();
  11275. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11276. _this.visibility = 1.0;
  11277. _this.alphaIndex = Number.MAX_VALUE;
  11278. _this.infiniteDistance = false;
  11279. _this.isVisible = true;
  11280. _this.isPickable = true;
  11281. _this.showBoundingBox = false;
  11282. _this.showSubMeshesBoundingBox = false;
  11283. _this.isBlocker = false;
  11284. _this.renderingGroupId = 0;
  11285. _this._receiveShadows = false;
  11286. _this.renderOutline = false;
  11287. _this.outlineColor = BABYLON.Color3.Red();
  11288. _this.outlineWidth = 0.02;
  11289. _this.renderOverlay = false;
  11290. _this.overlayColor = BABYLON.Color3.Red();
  11291. _this.overlayAlpha = 0.5;
  11292. _this._hasVertexAlpha = false;
  11293. _this._useVertexColors = true;
  11294. _this._computeBonesUsingShaders = true;
  11295. _this._numBoneInfluencers = 4;
  11296. _this._applyFog = true;
  11297. _this.scalingDeterminant = 1;
  11298. _this.useOctreeForRenderingSelection = true;
  11299. _this.useOctreeForPicking = true;
  11300. _this.useOctreeForCollisions = true;
  11301. _this.layerMask = 0x0FFFFFFF;
  11302. /**
  11303. * True if the mesh must be rendered in any case.
  11304. */
  11305. _this.alwaysSelectAsActiveMesh = false;
  11306. // Collisions
  11307. _this._checkCollisions = false;
  11308. _this._collisionMask = -1;
  11309. _this._collisionGroup = -1;
  11310. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11311. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11312. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11313. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11314. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11315. // Edges
  11316. _this.edgesWidth = 1;
  11317. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11318. // Cache
  11319. _this._localWorld = BABYLON.Matrix.Zero();
  11320. _this._worldMatrix = BABYLON.Matrix.Zero();
  11321. _this._absolutePosition = BABYLON.Vector3.Zero();
  11322. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11323. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11324. _this._isDirty = false;
  11325. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11326. _this._isDisposed = false;
  11327. _this._renderId = 0;
  11328. _this._intersectionsInProgress = new Array();
  11329. _this._isWorldMatrixFrozen = false;
  11330. _this._unIndexed = false;
  11331. _this._lightSources = new Array();
  11332. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11333. if (collidedMesh === void 0) { collidedMesh = null; }
  11334. //TODO move this to the collision coordinator!
  11335. if (_this.getScene().workerCollisions)
  11336. newPosition.multiplyInPlace(_this._collider.radius);
  11337. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11338. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11339. _this.position.addInPlace(_this._diffPositionForCollisions);
  11340. }
  11341. if (collidedMesh) {
  11342. _this.onCollideObservable.notifyObservers(collidedMesh);
  11343. }
  11344. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11345. };
  11346. _this.getScene().addMesh(_this);
  11347. _this._resyncLightSources();
  11348. return _this;
  11349. }
  11350. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11351. get: function () {
  11352. return AbstractMesh._BILLBOARDMODE_NONE;
  11353. },
  11354. enumerable: true,
  11355. configurable: true
  11356. });
  11357. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11358. get: function () {
  11359. return AbstractMesh._BILLBOARDMODE_X;
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11365. get: function () {
  11366. return AbstractMesh._BILLBOARDMODE_Y;
  11367. },
  11368. enumerable: true,
  11369. configurable: true
  11370. });
  11371. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11372. get: function () {
  11373. return AbstractMesh._BILLBOARDMODE_Z;
  11374. },
  11375. enumerable: true,
  11376. configurable: true
  11377. });
  11378. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11379. get: function () {
  11380. return AbstractMesh._BILLBOARDMODE_ALL;
  11381. },
  11382. enumerable: true,
  11383. configurable: true
  11384. });
  11385. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11386. /**
  11387. * Read-only : the number of facets in the mesh
  11388. */
  11389. get: function () {
  11390. return this._facetNb;
  11391. },
  11392. enumerable: true,
  11393. configurable: true
  11394. });
  11395. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11396. /**
  11397. * The number (integer) of subdivisions per axis in the partioning space
  11398. */
  11399. get: function () {
  11400. return this._partitioningSubdivisions;
  11401. },
  11402. set: function (nb) {
  11403. this._partitioningSubdivisions = nb;
  11404. },
  11405. enumerable: true,
  11406. configurable: true
  11407. });
  11408. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11409. /**
  11410. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11411. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11412. */
  11413. get: function () {
  11414. return this._partitioningBBoxRatio;
  11415. },
  11416. set: function (ratio) {
  11417. this._partitioningBBoxRatio = ratio;
  11418. },
  11419. enumerable: true,
  11420. configurable: true
  11421. });
  11422. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11423. /**
  11424. * Read-only boolean : is the feature facetData enabled ?
  11425. */
  11426. get: function () {
  11427. return this._facetDataEnabled;
  11428. },
  11429. enumerable: true,
  11430. configurable: true
  11431. });
  11432. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11433. set: function (callback) {
  11434. if (this._onCollideObserver) {
  11435. this.onCollideObservable.remove(this._onCollideObserver);
  11436. }
  11437. this._onCollideObserver = this.onCollideObservable.add(callback);
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11443. set: function (callback) {
  11444. if (this._onCollisionPositionChangeObserver) {
  11445. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11446. }
  11447. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11448. },
  11449. enumerable: true,
  11450. configurable: true
  11451. });
  11452. Object.defineProperty(AbstractMesh.prototype, "material", {
  11453. get: function () {
  11454. return this._material;
  11455. },
  11456. set: function (value) {
  11457. if (this._material === value) {
  11458. return;
  11459. }
  11460. this._material = value;
  11461. if (!this.subMeshes) {
  11462. return;
  11463. }
  11464. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11465. var subMesh = _a[_i];
  11466. subMesh.setEffect(null);
  11467. }
  11468. },
  11469. enumerable: true,
  11470. configurable: true
  11471. });
  11472. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11473. get: function () {
  11474. return this._receiveShadows;
  11475. },
  11476. set: function (value) {
  11477. if (this._receiveShadows === value) {
  11478. return;
  11479. }
  11480. this._receiveShadows = value;
  11481. this._markSubMeshesAsLightDirty();
  11482. },
  11483. enumerable: true,
  11484. configurable: true
  11485. });
  11486. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11487. get: function () {
  11488. return this._hasVertexAlpha;
  11489. },
  11490. set: function (value) {
  11491. if (this._hasVertexAlpha === value) {
  11492. return;
  11493. }
  11494. this._hasVertexAlpha = value;
  11495. this._markSubMeshesAsAttributesDirty();
  11496. },
  11497. enumerable: true,
  11498. configurable: true
  11499. });
  11500. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11501. get: function () {
  11502. return this._useVertexColors;
  11503. },
  11504. set: function (value) {
  11505. if (this._useVertexColors === value) {
  11506. return;
  11507. }
  11508. this._useVertexColors = value;
  11509. this._markSubMeshesAsAttributesDirty();
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11515. get: function () {
  11516. return this._computeBonesUsingShaders;
  11517. },
  11518. set: function (value) {
  11519. if (this._computeBonesUsingShaders === value) {
  11520. return;
  11521. }
  11522. this._computeBonesUsingShaders = value;
  11523. this._markSubMeshesAsAttributesDirty();
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11529. get: function () {
  11530. return this._numBoneInfluencers;
  11531. },
  11532. set: function (value) {
  11533. if (this._numBoneInfluencers === value) {
  11534. return;
  11535. }
  11536. this._numBoneInfluencers = value;
  11537. this._markSubMeshesAsAttributesDirty();
  11538. },
  11539. enumerable: true,
  11540. configurable: true
  11541. });
  11542. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11543. get: function () {
  11544. return this._applyFog;
  11545. },
  11546. set: function (value) {
  11547. if (this._applyFog === value) {
  11548. return;
  11549. }
  11550. this._applyFog = value;
  11551. this._markSubMeshesAsMiscDirty();
  11552. },
  11553. enumerable: true,
  11554. configurable: true
  11555. });
  11556. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11557. get: function () {
  11558. return this._collisionMask;
  11559. },
  11560. set: function (mask) {
  11561. this._collisionMask = !isNaN(mask) ? mask : -1;
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11567. get: function () {
  11568. return this._collisionGroup;
  11569. },
  11570. set: function (mask) {
  11571. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11572. },
  11573. enumerable: true,
  11574. configurable: true
  11575. });
  11576. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11577. get: function () {
  11578. return null;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11584. get: function () {
  11585. return this._skeleton;
  11586. },
  11587. set: function (value) {
  11588. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11589. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11590. }
  11591. if (value && value.needInitialSkinMatrix) {
  11592. value._registerMeshWithPoseMatrix(this);
  11593. }
  11594. this._skeleton = value;
  11595. if (!this._skeleton) {
  11596. this._bonesTransformMatrices = null;
  11597. }
  11598. this._markSubMeshesAsAttributesDirty();
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. /**
  11604. * Returns the string "AbstractMesh"
  11605. */
  11606. AbstractMesh.prototype.getClassName = function () {
  11607. return "AbstractMesh";
  11608. };
  11609. /**
  11610. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11611. */
  11612. AbstractMesh.prototype.toString = function (fullDetails) {
  11613. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11614. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11615. if (this._skeleton) {
  11616. ret += ", skeleton: " + this._skeleton.name;
  11617. }
  11618. if (fullDetails) {
  11619. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11620. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11621. }
  11622. return ret;
  11623. };
  11624. AbstractMesh.prototype._resyncLightSources = function () {
  11625. this._lightSources.length = 0;
  11626. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11627. var light = _a[_i];
  11628. if (!light.isEnabled()) {
  11629. continue;
  11630. }
  11631. if (light.canAffectMesh(this)) {
  11632. this._lightSources.push(light);
  11633. }
  11634. }
  11635. this._markSubMeshesAsLightDirty();
  11636. };
  11637. AbstractMesh.prototype._resyncLighSource = function (light) {
  11638. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11639. var index = this._lightSources.indexOf(light);
  11640. if (index === -1) {
  11641. if (!isIn) {
  11642. return;
  11643. }
  11644. this._lightSources.push(light);
  11645. }
  11646. else {
  11647. if (isIn) {
  11648. return;
  11649. }
  11650. this._lightSources.splice(index, 1);
  11651. }
  11652. this._markSubMeshesAsLightDirty();
  11653. };
  11654. AbstractMesh.prototype._removeLightSource = function (light) {
  11655. var index = this._lightSources.indexOf(light);
  11656. if (index === -1) {
  11657. return;
  11658. }
  11659. this._lightSources.splice(index, 1);
  11660. };
  11661. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11662. if (!this.subMeshes) {
  11663. return;
  11664. }
  11665. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11666. var subMesh = _a[_i];
  11667. if (subMesh._materialDefines) {
  11668. func(subMesh._materialDefines);
  11669. }
  11670. }
  11671. };
  11672. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11673. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11674. };
  11675. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11676. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11677. };
  11678. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11679. if (!this.subMeshes) {
  11680. return;
  11681. }
  11682. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11683. var subMesh = _a[_i];
  11684. var material = subMesh.getMaterial();
  11685. if (material) {
  11686. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11687. }
  11688. }
  11689. };
  11690. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11691. /**
  11692. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11693. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11694. * Default : (0.0, 0.0, 0.0)
  11695. */
  11696. get: function () {
  11697. return this._rotation;
  11698. },
  11699. set: function (newRotation) {
  11700. this._rotation = newRotation;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11706. /**
  11707. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11708. * Default : (1.0, 1.0, 1.0)
  11709. */
  11710. get: function () {
  11711. return this._scaling;
  11712. },
  11713. set: function (newScaling) {
  11714. this._scaling = newScaling;
  11715. if (this.physicsImpostor) {
  11716. this.physicsImpostor.forceUpdate();
  11717. }
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11723. /**
  11724. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11725. * It's null by default.
  11726. * 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)
  11727. */
  11728. get: function () {
  11729. return this._rotationQuaternion;
  11730. },
  11731. set: function (quaternion) {
  11732. this._rotationQuaternion = quaternion;
  11733. //reset the rotation vector.
  11734. if (quaternion && this.rotation.length()) {
  11735. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11736. }
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. // Methods
  11742. /**
  11743. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11744. * Returns the AbstractMesh.
  11745. */
  11746. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11747. this._poseMatrix.copyFrom(matrix);
  11748. return this;
  11749. };
  11750. /**
  11751. * Returns the mesh Pose matrix.
  11752. * Returned object : Matrix
  11753. */
  11754. AbstractMesh.prototype.getPoseMatrix = function () {
  11755. return this._poseMatrix;
  11756. };
  11757. /**
  11758. * Disables the mesh edger rendering mode.
  11759. * Returns the AbstractMesh.
  11760. */
  11761. AbstractMesh.prototype.disableEdgesRendering = function () {
  11762. if (this._edgesRenderer !== undefined) {
  11763. this._edgesRenderer.dispose();
  11764. this._edgesRenderer = undefined;
  11765. }
  11766. return this;
  11767. };
  11768. /**
  11769. * Enables the edge rendering mode on the mesh.
  11770. * This mode makes the mesh edges visible.
  11771. * Returns the AbstractMesh.
  11772. */
  11773. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11774. if (epsilon === void 0) { epsilon = 0.95; }
  11775. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11776. this.disableEdgesRendering();
  11777. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11778. return this;
  11779. };
  11780. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11781. /**
  11782. * Returns true if the mesh is blocked. Used by the class Mesh.
  11783. * Returns the boolean `false` by default.
  11784. */
  11785. get: function () {
  11786. return false;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. /**
  11792. * Returns the mesh itself by default, used by the class Mesh.
  11793. * Returned type : AbstractMesh
  11794. */
  11795. AbstractMesh.prototype.getLOD = function (camera) {
  11796. return this;
  11797. };
  11798. /**
  11799. * Returns 0 by default, used by the class Mesh.
  11800. * Returns an integer.
  11801. */
  11802. AbstractMesh.prototype.getTotalVertices = function () {
  11803. return 0;
  11804. };
  11805. /**
  11806. * Returns null by default, used by the class Mesh.
  11807. * Returned type : integer array
  11808. */
  11809. AbstractMesh.prototype.getIndices = function () {
  11810. return null;
  11811. };
  11812. /**
  11813. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11814. * Returned type : float array or Float32Array
  11815. */
  11816. AbstractMesh.prototype.getVerticesData = function (kind) {
  11817. return null;
  11818. };
  11819. /**
  11820. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11821. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11822. * The `data` are either a numeric array either a Float32Array.
  11823. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11824. * 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).
  11825. * Note that a new underlying VertexBuffer object is created each call.
  11826. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11827. *
  11828. * Possible `kind` values :
  11829. * - BABYLON.VertexBuffer.PositionKind
  11830. * - BABYLON.VertexBuffer.UVKind
  11831. * - BABYLON.VertexBuffer.UV2Kind
  11832. * - BABYLON.VertexBuffer.UV3Kind
  11833. * - BABYLON.VertexBuffer.UV4Kind
  11834. * - BABYLON.VertexBuffer.UV5Kind
  11835. * - BABYLON.VertexBuffer.UV6Kind
  11836. * - BABYLON.VertexBuffer.ColorKind
  11837. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11838. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11839. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11840. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11841. *
  11842. * Returns the Mesh.
  11843. */
  11844. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11845. return null;
  11846. };
  11847. /**
  11848. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11849. * If the mesh has no geometry, it is simply returned as it is.
  11850. * The `data` are either a numeric array either a Float32Array.
  11851. * No new underlying VertexBuffer object is created.
  11852. * 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.
  11853. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11854. *
  11855. * Possible `kind` values :
  11856. * - BABYLON.VertexBuffer.PositionKind
  11857. * - BABYLON.VertexBuffer.UVKind
  11858. * - BABYLON.VertexBuffer.UV2Kind
  11859. * - BABYLON.VertexBuffer.UV3Kind
  11860. * - BABYLON.VertexBuffer.UV4Kind
  11861. * - BABYLON.VertexBuffer.UV5Kind
  11862. * - BABYLON.VertexBuffer.UV6Kind
  11863. * - BABYLON.VertexBuffer.ColorKind
  11864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11868. *
  11869. * Returns the Mesh.
  11870. */
  11871. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11872. return null;
  11873. };
  11874. /**
  11875. * Sets the mesh indices.
  11876. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11877. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11878. * This method creates a new index buffer each call.
  11879. * Returns the Mesh.
  11880. */
  11881. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11882. return null;
  11883. };
  11884. /** Returns false by default, used by the class Mesh.
  11885. * Returns a boolean
  11886. */
  11887. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11888. return false;
  11889. };
  11890. /**
  11891. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11892. * Returns a BoundingInfo
  11893. */
  11894. AbstractMesh.prototype.getBoundingInfo = function () {
  11895. if (this._masterMesh) {
  11896. return this._masterMesh.getBoundingInfo();
  11897. }
  11898. if (!this._boundingInfo) {
  11899. this._updateBoundingInfo();
  11900. }
  11901. return this._boundingInfo;
  11902. };
  11903. /**
  11904. * Sets a mesh new object BoundingInfo.
  11905. * Returns the AbstractMesh.
  11906. */
  11907. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11908. this._boundingInfo = boundingInfo;
  11909. return this;
  11910. };
  11911. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11912. get: function () {
  11913. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. AbstractMesh.prototype._preActivate = function () {
  11919. };
  11920. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11921. };
  11922. AbstractMesh.prototype._activate = function (renderId) {
  11923. this._renderId = renderId;
  11924. };
  11925. /**
  11926. * Returns the last update of the World matrix
  11927. * Returns a Matrix.
  11928. */
  11929. AbstractMesh.prototype.getWorldMatrix = function () {
  11930. if (this._masterMesh) {
  11931. return this._masterMesh.getWorldMatrix();
  11932. }
  11933. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11934. this.computeWorldMatrix();
  11935. }
  11936. return this._worldMatrix;
  11937. };
  11938. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11939. /**
  11940. * Returns directly the last state of the mesh World matrix.
  11941. * A Matrix is returned.
  11942. */
  11943. get: function () {
  11944. return this._worldMatrix;
  11945. },
  11946. enumerable: true,
  11947. configurable: true
  11948. });
  11949. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11950. /**
  11951. * Returns the current mesh absolute position.
  11952. * Retuns a Vector3.
  11953. */
  11954. get: function () {
  11955. return this._absolutePosition;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. /**
  11961. * Prevents the World matrix to be computed any longer.
  11962. * Returns the AbstractMesh.
  11963. */
  11964. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11965. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11966. this.computeWorldMatrix(true);
  11967. this._isWorldMatrixFrozen = true;
  11968. return this;
  11969. };
  11970. /**
  11971. * Allows back the World matrix computation.
  11972. * Returns the AbstractMesh.
  11973. */
  11974. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11975. this._isWorldMatrixFrozen = false;
  11976. this.computeWorldMatrix(true);
  11977. return this;
  11978. };
  11979. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11980. /**
  11981. * True if the World matrix has been frozen.
  11982. * Returns a boolean.
  11983. */
  11984. get: function () {
  11985. return this._isWorldMatrixFrozen;
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. /**
  11991. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11992. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11993. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11994. * The passed axis is also normalized.
  11995. * Returns the AbstractMesh.
  11996. */
  11997. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11998. axis.normalize();
  11999. if (!this.rotationQuaternion) {
  12000. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12001. this.rotation = BABYLON.Vector3.Zero();
  12002. }
  12003. var rotationQuaternion;
  12004. if (!space || space === BABYLON.Space.LOCAL) {
  12005. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12006. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12007. }
  12008. else {
  12009. if (this.parent) {
  12010. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12011. invertParentWorldMatrix.invert();
  12012. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12013. }
  12014. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12015. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12016. }
  12017. return this;
  12018. };
  12019. /**
  12020. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12021. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12022. * The passed axis is also normalized.
  12023. * Returns the AbstractMesh.
  12024. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12025. */
  12026. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12027. axis.normalize();
  12028. if (!this.rotationQuaternion) {
  12029. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12030. this.rotation.copyFromFloats(0, 0, 0);
  12031. }
  12032. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12033. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12034. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12035. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12036. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12037. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12038. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12039. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12040. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  12041. return this;
  12042. };
  12043. /**
  12044. * Translates the mesh along the axis vector for the passed distance in the given space.
  12045. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12046. * Returns the AbstractMesh.
  12047. */
  12048. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12049. var displacementVector = axis.scale(distance);
  12050. if (!space || space === BABYLON.Space.LOCAL) {
  12051. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12052. this.setPositionWithLocalVector(tempV3);
  12053. }
  12054. else {
  12055. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12056. }
  12057. return this;
  12058. };
  12059. /**
  12060. * Adds a rotation step to the mesh current rotation.
  12061. * x, y, z are Euler angles expressed in radians.
  12062. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12063. * This means this rotation is made in the mesh local space only.
  12064. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12065. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12066. * ```javascript
  12067. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12068. * ```
  12069. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12070. * 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.
  12071. * Returns the AbstractMesh.
  12072. */
  12073. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12074. var rotationQuaternion;
  12075. if (this.rotationQuaternion) {
  12076. rotationQuaternion = this.rotationQuaternion;
  12077. }
  12078. else {
  12079. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12080. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12081. }
  12082. var accumulation = BABYLON.Tmp.Quaternion[0];
  12083. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12084. rotationQuaternion.multiplyInPlace(accumulation);
  12085. if (!this.rotationQuaternion) {
  12086. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12087. }
  12088. return this;
  12089. };
  12090. /**
  12091. * Retuns the mesh absolute position in the World.
  12092. * Returns a Vector3.
  12093. */
  12094. AbstractMesh.prototype.getAbsolutePosition = function () {
  12095. this.computeWorldMatrix();
  12096. return this._absolutePosition;
  12097. };
  12098. /**
  12099. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12100. * Returns the AbstractMesh.
  12101. */
  12102. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12103. if (!absolutePosition) {
  12104. return;
  12105. }
  12106. var absolutePositionX;
  12107. var absolutePositionY;
  12108. var absolutePositionZ;
  12109. if (absolutePosition.x === undefined) {
  12110. if (arguments.length < 3) {
  12111. return;
  12112. }
  12113. absolutePositionX = arguments[0];
  12114. absolutePositionY = arguments[1];
  12115. absolutePositionZ = arguments[2];
  12116. }
  12117. else {
  12118. absolutePositionX = absolutePosition.x;
  12119. absolutePositionY = absolutePosition.y;
  12120. absolutePositionZ = absolutePosition.z;
  12121. }
  12122. if (this.parent) {
  12123. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12124. invertParentWorldMatrix.invert();
  12125. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12126. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12127. }
  12128. else {
  12129. this.position.x = absolutePositionX;
  12130. this.position.y = absolutePositionY;
  12131. this.position.z = absolutePositionZ;
  12132. }
  12133. return this;
  12134. };
  12135. // ================================== Point of View Movement =================================
  12136. /**
  12137. * Perform relative position change from the point of view of behind the front of the mesh.
  12138. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12139. * Supports definition of mesh facing forward or backward.
  12140. * @param {number} amountRight
  12141. * @param {number} amountUp
  12142. * @param {number} amountForward
  12143. *
  12144. * Returns the AbstractMesh.
  12145. */
  12146. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12147. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12148. return this;
  12149. };
  12150. /**
  12151. * Calculate relative position change from the point of view of behind the front of the mesh.
  12152. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12153. * Supports definition of mesh facing forward or backward.
  12154. * @param {number} amountRight
  12155. * @param {number} amountUp
  12156. * @param {number} amountForward
  12157. *
  12158. * Returns a new Vector3.
  12159. */
  12160. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12161. var rotMatrix = new BABYLON.Matrix();
  12162. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12163. rotQuaternion.toRotationMatrix(rotMatrix);
  12164. var translationDelta = BABYLON.Vector3.Zero();
  12165. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12167. return translationDelta;
  12168. };
  12169. // ================================== Point of View Rotation =================================
  12170. /**
  12171. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12172. * Supports definition of mesh facing forward or backward.
  12173. * @param {number} flipBack
  12174. * @param {number} twirlClockwise
  12175. * @param {number} tiltRight
  12176. *
  12177. * Returns the AbstractMesh.
  12178. */
  12179. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12180. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12181. return this;
  12182. };
  12183. /**
  12184. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12185. * Supports definition of mesh facing forward or backward.
  12186. * @param {number} flipBack
  12187. * @param {number} twirlClockwise
  12188. * @param {number} tiltRight
  12189. *
  12190. * Returns a new Vector3.
  12191. */
  12192. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12193. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12194. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12195. };
  12196. /**
  12197. * Sets a new pivot matrix to the mesh.
  12198. * Returns the AbstractMesh.
  12199. */
  12200. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12201. this._pivotMatrix = matrix;
  12202. this._cache.pivotMatrixUpdated = true;
  12203. return this;
  12204. };
  12205. /**
  12206. * Returns the mesh pivot matrix.
  12207. * Default : Identity.
  12208. * A Matrix is returned.
  12209. */
  12210. AbstractMesh.prototype.getPivotMatrix = function () {
  12211. return this._pivotMatrix;
  12212. };
  12213. AbstractMesh.prototype._isSynchronized = function () {
  12214. if (this._isDirty) {
  12215. return false;
  12216. }
  12217. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12218. return false;
  12219. if (this._cache.pivotMatrixUpdated) {
  12220. return false;
  12221. }
  12222. if (this.infiniteDistance) {
  12223. return false;
  12224. }
  12225. if (!this._cache.position.equals(this.position))
  12226. return false;
  12227. if (this.rotationQuaternion) {
  12228. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12229. return false;
  12230. }
  12231. if (!this._cache.rotation.equals(this.rotation))
  12232. return false;
  12233. if (!this._cache.scaling.equals(this.scaling))
  12234. return false;
  12235. return true;
  12236. };
  12237. AbstractMesh.prototype._initCache = function () {
  12238. _super.prototype._initCache.call(this);
  12239. this._cache.localMatrixUpdated = false;
  12240. this._cache.position = BABYLON.Vector3.Zero();
  12241. this._cache.scaling = BABYLON.Vector3.Zero();
  12242. this._cache.rotation = BABYLON.Vector3.Zero();
  12243. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12244. this._cache.billboardMode = -1;
  12245. };
  12246. AbstractMesh.prototype.markAsDirty = function (property) {
  12247. if (property === "rotation") {
  12248. this.rotationQuaternion = null;
  12249. }
  12250. this._currentRenderId = Number.MAX_VALUE;
  12251. this._isDirty = true;
  12252. return this;
  12253. };
  12254. /**
  12255. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12256. * Returns the AbstractMesh.
  12257. */
  12258. AbstractMesh.prototype._updateBoundingInfo = function () {
  12259. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12260. this._boundingInfo.update(this.worldMatrixFromCache);
  12261. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12262. return this;
  12263. };
  12264. /**
  12265. * Update a mesh's children BoundingInfo objects only.
  12266. * Returns the AbstractMesh.
  12267. */
  12268. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12269. if (!this.subMeshes) {
  12270. return;
  12271. }
  12272. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12273. var subMesh = this.subMeshes[subIndex];
  12274. if (!subMesh.IsGlobal) {
  12275. subMesh.updateBoundingInfo(matrix);
  12276. }
  12277. }
  12278. return this;
  12279. };
  12280. /**
  12281. * Computes the mesh World matrix and returns it.
  12282. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12283. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12284. * If the parameter `force`is set to `true`, the actual computation is done.
  12285. * Returns the mesh World Matrix.
  12286. */
  12287. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12288. if (this._isWorldMatrixFrozen) {
  12289. return this._worldMatrix;
  12290. }
  12291. if (!force && this.isSynchronized(true)) {
  12292. this._currentRenderId = this.getScene().getRenderId();
  12293. return this._worldMatrix;
  12294. }
  12295. this._cache.position.copyFrom(this.position);
  12296. this._cache.scaling.copyFrom(this.scaling);
  12297. this._cache.pivotMatrixUpdated = false;
  12298. this._cache.billboardMode = this.billboardMode;
  12299. this._currentRenderId = this.getScene().getRenderId();
  12300. this._isDirty = false;
  12301. // Scaling
  12302. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12303. // Rotation
  12304. //rotate, if quaternion is set and rotation was used
  12305. if (this.rotationQuaternion) {
  12306. var len = this.rotation.length();
  12307. if (len) {
  12308. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12309. this.rotation.copyFromFloats(0, 0, 0);
  12310. }
  12311. }
  12312. if (this.rotationQuaternion) {
  12313. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12314. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12315. }
  12316. else {
  12317. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12318. this._cache.rotation.copyFrom(this.rotation);
  12319. }
  12320. // Translation
  12321. if (this.infiniteDistance && !this.parent) {
  12322. var camera = this.getScene().activeCamera;
  12323. if (camera) {
  12324. var cameraWorldMatrix = camera.getWorldMatrix();
  12325. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12326. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12327. }
  12328. }
  12329. else {
  12330. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12331. }
  12332. // Composing transformations
  12333. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12334. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12335. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12336. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12337. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12338. // Need to decompose each rotation here
  12339. var currentPosition = BABYLON.Tmp.Vector3[3];
  12340. if (this.parent && this.parent.getWorldMatrix) {
  12341. if (this._meshToBoneReferal) {
  12342. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12343. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12344. }
  12345. else {
  12346. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12347. }
  12348. }
  12349. else {
  12350. currentPosition.copyFrom(this.position);
  12351. }
  12352. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12353. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12354. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12355. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12356. }
  12357. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12358. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12359. }
  12360. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12361. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12362. }
  12363. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12364. }
  12365. else {
  12366. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12367. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12368. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12369. }
  12370. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12371. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12372. }
  12373. // Local world
  12374. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12375. // Parent
  12376. if (this.parent && this.parent.getWorldMatrix) {
  12377. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12378. if (this._meshToBoneReferal) {
  12379. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12380. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12381. }
  12382. else {
  12383. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12384. }
  12385. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12386. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12387. this._worldMatrix.copyFrom(this._localWorld);
  12388. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12389. }
  12390. else {
  12391. if (this._meshToBoneReferal) {
  12392. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12393. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12394. }
  12395. else {
  12396. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12397. }
  12398. }
  12399. this._markSyncedWithParent();
  12400. }
  12401. else {
  12402. this._worldMatrix.copyFrom(this._localWorld);
  12403. }
  12404. // Bounding info
  12405. this._updateBoundingInfo();
  12406. // Absolute position
  12407. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12408. // Callbacks
  12409. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12410. if (!this._poseMatrix) {
  12411. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12412. }
  12413. return this._worldMatrix;
  12414. };
  12415. /**
  12416. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12417. * @param func: callback function to add
  12418. *
  12419. * Returns the AbstractMesh.
  12420. */
  12421. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12422. this.onAfterWorldMatrixUpdateObservable.add(func);
  12423. return this;
  12424. };
  12425. /**
  12426. * Removes a registered callback function.
  12427. * Returns the AbstractMesh.
  12428. */
  12429. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12430. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12431. return this;
  12432. };
  12433. /**
  12434. * Sets the mesh position in its local space.
  12435. * Returns the AbstractMesh.
  12436. */
  12437. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12438. this.computeWorldMatrix();
  12439. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12440. return this;
  12441. };
  12442. /**
  12443. * Returns the mesh position in the local space from the current World matrix values.
  12444. * Returns a new Vector3.
  12445. */
  12446. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12447. this.computeWorldMatrix();
  12448. var invLocalWorldMatrix = this._localWorld.clone();
  12449. invLocalWorldMatrix.invert();
  12450. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12451. };
  12452. /**
  12453. * Translates the mesh along the passed Vector3 in its local space.
  12454. * Returns the AbstractMesh.
  12455. */
  12456. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12457. this.computeWorldMatrix(true);
  12458. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12459. return this;
  12460. };
  12461. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12462. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12463. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12464. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12465. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12466. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12467. /// <returns>Mesh oriented towards targetMesh</returns>
  12468. if (yawCor === void 0) { yawCor = 0; }
  12469. if (pitchCor === void 0) { pitchCor = 0; }
  12470. if (rollCor === void 0) { rollCor = 0; }
  12471. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12472. var dv = AbstractMesh._lookAtVectorCache;
  12473. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12474. targetPoint.subtractToRef(pos, dv);
  12475. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12476. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12477. var pitch = Math.atan2(dv.y, len);
  12478. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12479. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12480. return this;
  12481. };
  12482. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12483. this._meshToBoneReferal = affectedMesh;
  12484. this.parent = bone;
  12485. if (bone.getWorldMatrix().determinant() < 0) {
  12486. this.scalingDeterminant *= -1;
  12487. }
  12488. return this;
  12489. };
  12490. AbstractMesh.prototype.detachFromBone = function () {
  12491. if (this.parent.getWorldMatrix().determinant() < 0) {
  12492. this.scalingDeterminant *= -1;
  12493. }
  12494. this._meshToBoneReferal = null;
  12495. this.parent = null;
  12496. return this;
  12497. };
  12498. /**
  12499. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12500. * A mesh is in the frustum if its bounding box intersects the frustum.
  12501. * Boolean returned.
  12502. */
  12503. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12504. return this._boundingInfo.isInFrustum(frustumPlanes);
  12505. };
  12506. /**
  12507. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12508. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12509. * Boolean returned.
  12510. */
  12511. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12512. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12513. ;
  12514. };
  12515. /**
  12516. * True if the mesh intersects another mesh or a SolidParticle object.
  12517. * 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)
  12518. * Returns a boolean.
  12519. */
  12520. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12521. if (!this._boundingInfo || !mesh._boundingInfo) {
  12522. return false;
  12523. }
  12524. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12525. };
  12526. /**
  12527. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12528. * Returns a boolean.
  12529. */
  12530. AbstractMesh.prototype.intersectsPoint = function (point) {
  12531. if (!this._boundingInfo) {
  12532. return false;
  12533. }
  12534. return this._boundingInfo.intersectsPoint(point);
  12535. };
  12536. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12537. return this.physicsImpostor;
  12538. };
  12539. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12540. if (!camera) {
  12541. camera = this.getScene().activeCamera;
  12542. }
  12543. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12544. };
  12545. /**
  12546. * Returns the distance from the mesh to the active camera.
  12547. * Returns a float.
  12548. */
  12549. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12550. if (!camera) {
  12551. camera = this.getScene().activeCamera;
  12552. }
  12553. return this.absolutePosition.subtract(camera.position).length();
  12554. };
  12555. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12556. if (!this.physicsImpostor) {
  12557. return;
  12558. }
  12559. this.physicsImpostor.applyImpulse(force, contactPoint);
  12560. return this;
  12561. };
  12562. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12563. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12564. return;
  12565. }
  12566. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12567. mainPivot: pivot1,
  12568. connectedPivot: pivot2,
  12569. nativeParams: options
  12570. });
  12571. return this;
  12572. };
  12573. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12574. // Collisions
  12575. /**
  12576. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12577. * Default `false`.
  12578. */
  12579. get: function () {
  12580. return this._checkCollisions;
  12581. },
  12582. set: function (collisionEnabled) {
  12583. this._checkCollisions = collisionEnabled;
  12584. if (this.getScene().workerCollisions) {
  12585. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12586. }
  12587. },
  12588. enumerable: true,
  12589. configurable: true
  12590. });
  12591. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12592. var globalPosition = this.getAbsolutePosition();
  12593. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12594. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12595. if (!this._collider) {
  12596. this._collider = new BABYLON.Collider();
  12597. }
  12598. this._collider.radius = this.ellipsoid;
  12599. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12600. return this;
  12601. };
  12602. // Submeshes octree
  12603. /**
  12604. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12605. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12606. * Returns an Octree of submeshes.
  12607. */
  12608. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12609. if (maxCapacity === void 0) { maxCapacity = 64; }
  12610. if (maxDepth === void 0) { maxDepth = 2; }
  12611. if (!this._submeshesOctree) {
  12612. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12613. }
  12614. this.computeWorldMatrix(true);
  12615. // Update octree
  12616. var bbox = this.getBoundingInfo().boundingBox;
  12617. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12618. return this._submeshesOctree;
  12619. };
  12620. // Collisions
  12621. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12622. this._generatePointsArray();
  12623. // Transformation
  12624. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12625. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12626. subMesh._lastColliderWorldVertices = [];
  12627. subMesh._trianglePlanes = [];
  12628. var start = subMesh.verticesStart;
  12629. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12630. for (var i = start; i < end; i++) {
  12631. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12632. }
  12633. }
  12634. // Collide
  12635. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12636. if (collider.collisionFound) {
  12637. collider.collidedMesh = this;
  12638. }
  12639. return this;
  12640. };
  12641. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12642. var subMeshes;
  12643. var len;
  12644. // Octrees
  12645. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12646. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12647. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12648. len = intersections.length;
  12649. subMeshes = intersections.data;
  12650. }
  12651. else {
  12652. subMeshes = this.subMeshes;
  12653. len = subMeshes.length;
  12654. }
  12655. for (var index = 0; index < len; index++) {
  12656. var subMesh = subMeshes[index];
  12657. // Bounding test
  12658. if (len > 1 && !subMesh._checkCollision(collider))
  12659. continue;
  12660. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12661. }
  12662. return this;
  12663. };
  12664. AbstractMesh.prototype._checkCollision = function (collider) {
  12665. // Bounding box test
  12666. if (!this._boundingInfo._checkCollision(collider))
  12667. return this;
  12668. // Transformation matrix
  12669. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12670. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12671. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12672. return this;
  12673. };
  12674. // Picking
  12675. AbstractMesh.prototype._generatePointsArray = function () {
  12676. return false;
  12677. };
  12678. /**
  12679. * Checks if the passed Ray intersects with the mesh.
  12680. * Returns an object PickingInfo.
  12681. */
  12682. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12683. var pickingInfo = new BABYLON.PickingInfo();
  12684. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12685. return pickingInfo;
  12686. }
  12687. if (!this._generatePointsArray()) {
  12688. return pickingInfo;
  12689. }
  12690. var intersectInfo = null;
  12691. // Octrees
  12692. var subMeshes;
  12693. var len;
  12694. if (this._submeshesOctree && this.useOctreeForPicking) {
  12695. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12696. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12697. len = intersections.length;
  12698. subMeshes = intersections.data;
  12699. }
  12700. else {
  12701. subMeshes = this.subMeshes;
  12702. len = subMeshes.length;
  12703. }
  12704. for (var index = 0; index < len; index++) {
  12705. var subMesh = subMeshes[index];
  12706. // Bounding test
  12707. if (len > 1 && !subMesh.canIntersects(ray))
  12708. continue;
  12709. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12710. if (currentIntersectInfo) {
  12711. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12712. intersectInfo = currentIntersectInfo;
  12713. intersectInfo.subMeshId = index;
  12714. if (fastCheck) {
  12715. break;
  12716. }
  12717. }
  12718. }
  12719. }
  12720. if (intersectInfo) {
  12721. // Get picked point
  12722. var world = this.getWorldMatrix();
  12723. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12724. var direction = ray.direction.clone();
  12725. direction = direction.scale(intersectInfo.distance);
  12726. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12727. var pickedPoint = worldOrigin.add(worldDirection);
  12728. // Return result
  12729. pickingInfo.hit = true;
  12730. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12731. pickingInfo.pickedPoint = pickedPoint;
  12732. pickingInfo.pickedMesh = this;
  12733. pickingInfo.bu = intersectInfo.bu;
  12734. pickingInfo.bv = intersectInfo.bv;
  12735. pickingInfo.faceId = intersectInfo.faceId;
  12736. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12737. return pickingInfo;
  12738. }
  12739. return pickingInfo;
  12740. };
  12741. /**
  12742. * Clones the mesh, used by the class Mesh.
  12743. * Just returns `null` for an AbstractMesh.
  12744. */
  12745. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12746. return null;
  12747. };
  12748. /**
  12749. * Disposes all the mesh submeshes.
  12750. * Returns the AbstractMesh.
  12751. */
  12752. AbstractMesh.prototype.releaseSubMeshes = function () {
  12753. if (this.subMeshes) {
  12754. while (this.subMeshes.length) {
  12755. this.subMeshes[0].dispose();
  12756. }
  12757. }
  12758. else {
  12759. this.subMeshes = new Array();
  12760. }
  12761. return this;
  12762. };
  12763. /**
  12764. * Disposes the AbstractMesh.
  12765. * Some internal references are kept for further use.
  12766. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12767. * Returns nothing.
  12768. */
  12769. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12770. var _this = this;
  12771. var index;
  12772. // Action manager
  12773. if (this.actionManager) {
  12774. this.actionManager.dispose();
  12775. this.actionManager = null;
  12776. }
  12777. // Skeleton
  12778. this.skeleton = null;
  12779. // Animations
  12780. this.getScene().stopAnimation(this);
  12781. // Physics
  12782. if (this.physicsImpostor) {
  12783. this.physicsImpostor.dispose();
  12784. }
  12785. // Intersections in progress
  12786. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12787. var other = this._intersectionsInProgress[index];
  12788. var pos = other._intersectionsInProgress.indexOf(this);
  12789. other._intersectionsInProgress.splice(pos, 1);
  12790. }
  12791. this._intersectionsInProgress = [];
  12792. // Lights
  12793. var lights = this.getScene().lights;
  12794. lights.forEach(function (light) {
  12795. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12796. if (meshIndex !== -1) {
  12797. light.includedOnlyMeshes.splice(meshIndex, 1);
  12798. }
  12799. meshIndex = light.excludedMeshes.indexOf(_this);
  12800. if (meshIndex !== -1) {
  12801. light.excludedMeshes.splice(meshIndex, 1);
  12802. }
  12803. // Shadow generators
  12804. var generator = light.getShadowGenerator();
  12805. if (generator) {
  12806. var shadowMap = generator.getShadowMap();
  12807. meshIndex = shadowMap.renderList.indexOf(_this);
  12808. if (meshIndex !== -1) {
  12809. shadowMap.renderList.splice(meshIndex, 1);
  12810. }
  12811. }
  12812. });
  12813. // Edges
  12814. if (this._edgesRenderer) {
  12815. this._edgesRenderer.dispose();
  12816. this._edgesRenderer = null;
  12817. }
  12818. // SubMeshes
  12819. if (this.getClassName() !== "InstancedMesh") {
  12820. this.releaseSubMeshes();
  12821. }
  12822. // Octree
  12823. var sceneOctree = this.getScene().selectionOctree;
  12824. if (sceneOctree) {
  12825. var index = sceneOctree.dynamicContent.indexOf(this);
  12826. if (index !== -1) {
  12827. sceneOctree.dynamicContent.splice(index, 1);
  12828. }
  12829. }
  12830. // Engine
  12831. this.getScene().getEngine().wipeCaches();
  12832. // Remove from scene
  12833. this.getScene().removeMesh(this);
  12834. if (!doNotRecurse) {
  12835. // Particles
  12836. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12837. if (this.getScene().particleSystems[index].emitter === this) {
  12838. this.getScene().particleSystems[index].dispose();
  12839. index--;
  12840. }
  12841. }
  12842. // Children
  12843. var objects = this.getDescendants(true);
  12844. for (index = 0; index < objects.length; index++) {
  12845. objects[index].dispose();
  12846. }
  12847. }
  12848. else {
  12849. var childMeshes = this.getChildMeshes(true);
  12850. for (index = 0; index < childMeshes.length; index++) {
  12851. var child = childMeshes[index];
  12852. child.parent = null;
  12853. child.computeWorldMatrix(true);
  12854. }
  12855. }
  12856. // facet data
  12857. if (this._facetDataEnabled) {
  12858. this.disableFacetData();
  12859. }
  12860. this.onAfterWorldMatrixUpdateObservable.clear();
  12861. this.onCollideObservable.clear();
  12862. this.onCollisionPositionChangeObservable.clear();
  12863. this._isDisposed = true;
  12864. _super.prototype.dispose.call(this);
  12865. };
  12866. /**
  12867. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12868. * This Vector3 is expressed in the World space.
  12869. */
  12870. AbstractMesh.prototype.getDirection = function (localAxis) {
  12871. var result = BABYLON.Vector3.Zero();
  12872. this.getDirectionToRef(localAxis, result);
  12873. return result;
  12874. };
  12875. /**
  12876. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12877. * localAxis is expressed in the mesh local space.
  12878. * result is computed in the Wordl space from the mesh World matrix.
  12879. * Returns the AbstractMesh.
  12880. */
  12881. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12882. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12883. return this;
  12884. };
  12885. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12886. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12887. if (this.getScene().getRenderId() == 0) {
  12888. this.computeWorldMatrix(true);
  12889. }
  12890. var wm = this.getWorldMatrix();
  12891. if (space == BABYLON.Space.WORLD) {
  12892. var tmat = BABYLON.Tmp.Matrix[0];
  12893. wm.invertToRef(tmat);
  12894. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12895. }
  12896. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12897. this._pivotMatrix.m[12] = -point.x;
  12898. this._pivotMatrix.m[13] = -point.y;
  12899. this._pivotMatrix.m[14] = -point.z;
  12900. this._cache.pivotMatrixUpdated = true;
  12901. return this;
  12902. };
  12903. /**
  12904. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12905. */
  12906. AbstractMesh.prototype.getPivotPoint = function () {
  12907. var point = BABYLON.Vector3.Zero();
  12908. this.getPivotPointToRef(point);
  12909. return point;
  12910. };
  12911. /**
  12912. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12916. result.x = -this._pivotMatrix.m[12];
  12917. result.y = -this._pivotMatrix.m[13];
  12918. result.z = -this._pivotMatrix.m[14];
  12919. return this;
  12920. };
  12921. /**
  12922. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12923. */
  12924. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12925. var point = BABYLON.Vector3.Zero();
  12926. this.getAbsolutePivotPointToRef(point);
  12927. return point;
  12928. };
  12929. /**
  12930. * Defines the passed mesh as the parent of the current mesh.
  12931. * Returns the AbstractMesh.
  12932. */
  12933. AbstractMesh.prototype.setParent = function (mesh) {
  12934. var child = this;
  12935. var parent = mesh;
  12936. if (mesh == null) {
  12937. var rotation = BABYLON.Tmp.Quaternion[0];
  12938. var position = BABYLON.Tmp.Vector3[0];
  12939. var scale = BABYLON.Tmp.Vector3[1];
  12940. child.getWorldMatrix().decompose(scale, rotation, position);
  12941. if (child.rotationQuaternion) {
  12942. child.rotationQuaternion.copyFrom(rotation);
  12943. }
  12944. else {
  12945. rotation.toEulerAnglesToRef(child.rotation);
  12946. }
  12947. child.position.x = position.x;
  12948. child.position.y = position.y;
  12949. child.position.z = position.z;
  12950. }
  12951. else {
  12952. var rotation = BABYLON.Tmp.Quaternion[0];
  12953. var position = BABYLON.Tmp.Vector3[0];
  12954. var scale = BABYLON.Tmp.Vector3[1];
  12955. var m1 = BABYLON.Tmp.Matrix[0];
  12956. var m2 = BABYLON.Tmp.Matrix[1];
  12957. parent.getWorldMatrix().decompose(scale, rotation, position);
  12958. rotation.toRotationMatrix(m1);
  12959. m2.setTranslation(position);
  12960. m2.multiplyToRef(m1, m1);
  12961. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12962. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12963. m.decompose(scale, rotation, position);
  12964. if (child.rotationQuaternion) {
  12965. child.rotationQuaternion.copyFrom(rotation);
  12966. }
  12967. else {
  12968. rotation.toEulerAnglesToRef(child.rotation);
  12969. }
  12970. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12971. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12972. m.decompose(scale, rotation, position);
  12973. child.position.x = position.x;
  12974. child.position.y = position.y;
  12975. child.position.z = position.z;
  12976. }
  12977. child.parent = parent;
  12978. return this;
  12979. };
  12980. /**
  12981. * Adds the passed mesh as a child to the current mesh.
  12982. * Returns the AbstractMesh.
  12983. */
  12984. AbstractMesh.prototype.addChild = function (mesh) {
  12985. mesh.setParent(this);
  12986. return this;
  12987. };
  12988. /**
  12989. * Removes the passed mesh from the current mesh children list.
  12990. * Returns the AbstractMesh.
  12991. */
  12992. AbstractMesh.prototype.removeChild = function (mesh) {
  12993. mesh.setParent(null);
  12994. return this;
  12995. };
  12996. /**
  12997. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12998. * Returns the AbstractMesh.
  12999. */
  13000. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13001. result.x = this._pivotMatrix.m[12];
  13002. result.y = this._pivotMatrix.m[13];
  13003. result.z = this._pivotMatrix.m[14];
  13004. this.getPivotPointToRef(result);
  13005. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13006. return this;
  13007. };
  13008. // Facet data
  13009. /**
  13010. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13011. * Returns the AbstractMesh.
  13012. */
  13013. AbstractMesh.prototype._initFacetData = function () {
  13014. if (!this._facetNormals) {
  13015. this._facetNormals = new Array();
  13016. }
  13017. if (!this._facetPositions) {
  13018. this._facetPositions = new Array();
  13019. }
  13020. if (!this._facetPartitioning) {
  13021. this._facetPartitioning = new Array();
  13022. }
  13023. this._facetNb = this.getIndices().length / 3;
  13024. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13025. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13026. for (var f = 0; f < this._facetNb; f++) {
  13027. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13028. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13029. }
  13030. this._facetDataEnabled = true;
  13031. return this;
  13032. };
  13033. /**
  13034. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13035. * This method can be called within the render loop.
  13036. * 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.
  13037. * Returns the AbstractMesh.
  13038. */
  13039. AbstractMesh.prototype.updateFacetData = function () {
  13040. if (!this._facetDataEnabled) {
  13041. this._initFacetData();
  13042. }
  13043. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13044. var indices = this.getIndices();
  13045. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13046. var bInfo = this.getBoundingInfo();
  13047. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13048. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13049. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13050. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13051. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13052. this._subDiv.max = this._partitioningSubdivisions;
  13053. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13054. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13055. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13056. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13057. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13058. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13059. // set the parameters for ComputeNormals()
  13060. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13061. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13062. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13063. this._facetParameters.bInfo = bInfo;
  13064. this._facetParameters.bbSize = this._bbSize;
  13065. this._facetParameters.subDiv = this._subDiv;
  13066. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13067. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13068. return this;
  13069. };
  13070. /**
  13071. * Returns the facetLocalNormals array.
  13072. * The normals are expressed in the mesh local space.
  13073. */
  13074. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13075. if (!this._facetNormals) {
  13076. this.updateFacetData();
  13077. }
  13078. return this._facetNormals;
  13079. };
  13080. /**
  13081. * Returns the facetLocalPositions array.
  13082. * The facet positions are expressed in the mesh local space.
  13083. */
  13084. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13085. if (!this._facetPositions) {
  13086. this.updateFacetData();
  13087. }
  13088. return this._facetPositions;
  13089. };
  13090. /**
  13091. * Returns the facetLocalPartioning array.
  13092. */
  13093. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13094. if (!this._facetPartitioning) {
  13095. this.updateFacetData();
  13096. }
  13097. return this._facetPartitioning;
  13098. };
  13099. /**
  13100. * Returns the i-th facet position in the world system.
  13101. * This method allocates a new Vector3 per call.
  13102. */
  13103. AbstractMesh.prototype.getFacetPosition = function (i) {
  13104. var pos = BABYLON.Vector3.Zero();
  13105. this.getFacetPositionToRef(i, pos);
  13106. return pos;
  13107. };
  13108. /**
  13109. * Sets the reference Vector3 with the i-th facet position in the world system.
  13110. * Returns the AbstractMesh.
  13111. */
  13112. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13113. var localPos = (this.getFacetLocalPositions())[i];
  13114. var world = this.getWorldMatrix();
  13115. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13116. return this;
  13117. };
  13118. /**
  13119. * Returns the i-th facet normal in the world system.
  13120. * This method allocates a new Vector3 per call.
  13121. */
  13122. AbstractMesh.prototype.getFacetNormal = function (i) {
  13123. var norm = BABYLON.Vector3.Zero();
  13124. this.getFacetNormalToRef(i, norm);
  13125. return norm;
  13126. };
  13127. /**
  13128. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13129. * Returns the AbstractMesh.
  13130. */
  13131. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13132. var localNorm = (this.getFacetLocalNormals())[i];
  13133. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13134. return this;
  13135. };
  13136. /**
  13137. * 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).
  13138. */
  13139. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13140. var bInfo = this.getBoundingInfo();
  13141. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13142. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13143. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13144. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13145. return null;
  13146. }
  13147. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13148. };
  13149. /**
  13150. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13151. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13152. * 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.
  13153. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13154. * 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.
  13155. */
  13156. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13157. if (checkFace === void 0) { checkFace = false; }
  13158. if (facing === void 0) { facing = true; }
  13159. var world = this.getWorldMatrix();
  13160. var invMat = BABYLON.Tmp.Matrix[5];
  13161. world.invertToRef(invMat);
  13162. var invVect = BABYLON.Tmp.Vector3[8];
  13163. var closest = null;
  13164. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13165. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13166. if (projected) {
  13167. // tranform the local computed projected vector to world coordinates
  13168. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13169. }
  13170. return closest;
  13171. };
  13172. /**
  13173. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13174. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13175. * 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.
  13176. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13177. * 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.
  13178. */
  13179. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13180. if (checkFace === void 0) { checkFace = false; }
  13181. if (facing === void 0) { facing = true; }
  13182. var closest = null;
  13183. var tmpx = 0.0;
  13184. var tmpy = 0.0;
  13185. var tmpz = 0.0;
  13186. var d = 0.0; // tmp dot facet normal * facet position
  13187. var t0 = 0.0;
  13188. var projx = 0.0;
  13189. var projy = 0.0;
  13190. var projz = 0.0;
  13191. // Get all the facets in the same partitioning block than (x, y, z)
  13192. var facetPositions = this.getFacetLocalPositions();
  13193. var facetNormals = this.getFacetLocalNormals();
  13194. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13195. if (!facetsInBlock) {
  13196. return null;
  13197. }
  13198. // Get the closest facet to (x, y, z)
  13199. var shortest = Number.MAX_VALUE; // init distance vars
  13200. var tmpDistance = shortest;
  13201. var fib; // current facet in the block
  13202. var norm; // current facet normal
  13203. var p0; // current facet barycenter position
  13204. // loop on all the facets in the current partitioning block
  13205. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13206. fib = facetsInBlock[idx];
  13207. norm = facetNormals[fib];
  13208. p0 = facetPositions[fib];
  13209. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13210. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13211. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13212. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13213. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13214. projx = x + norm.x * t0;
  13215. projy = y + norm.y * t0;
  13216. projz = z + norm.z * t0;
  13217. tmpx = projx - x;
  13218. tmpy = projy - y;
  13219. tmpz = projz - z;
  13220. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13221. if (tmpDistance < shortest) {
  13222. shortest = tmpDistance;
  13223. closest = fib;
  13224. if (projected) {
  13225. projected.x = projx;
  13226. projected.y = projy;
  13227. projected.z = projz;
  13228. }
  13229. }
  13230. }
  13231. }
  13232. return closest;
  13233. };
  13234. /**
  13235. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13236. */
  13237. AbstractMesh.prototype.getFacetDataParameters = function () {
  13238. return this._facetParameters;
  13239. };
  13240. /**
  13241. * Disables the feature FacetData and frees the related memory.
  13242. * Returns the AbstractMesh.
  13243. */
  13244. AbstractMesh.prototype.disableFacetData = function () {
  13245. if (this._facetDataEnabled) {
  13246. this._facetDataEnabled = false;
  13247. this._facetPositions = null;
  13248. this._facetNormals = null;
  13249. this._facetPartitioning = null;
  13250. this._facetParameters = null;
  13251. }
  13252. return this;
  13253. };
  13254. /**
  13255. * Creates new normals data for the mesh.
  13256. * @param updatable.
  13257. */
  13258. AbstractMesh.prototype.createNormals = function (updatable) {
  13259. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13260. var indices = this.getIndices();
  13261. var normals;
  13262. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13263. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13264. }
  13265. else {
  13266. normals = [];
  13267. }
  13268. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13269. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13270. };
  13271. return AbstractMesh;
  13272. }(BABYLON.Node));
  13273. // Statics
  13274. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13275. AbstractMesh._BILLBOARDMODE_X = 1;
  13276. AbstractMesh._BILLBOARDMODE_Y = 2;
  13277. AbstractMesh._BILLBOARDMODE_Z = 4;
  13278. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13279. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13280. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13281. BABYLON.AbstractMesh = AbstractMesh;
  13282. })(BABYLON || (BABYLON = {}));
  13283. //# sourceMappingURL=babylon.abstractMesh.js.map
  13284. var BABYLON;
  13285. (function (BABYLON) {
  13286. var Light = (function (_super) {
  13287. __extends(Light, _super);
  13288. /**
  13289. * Creates a Light object in the scene.
  13290. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13291. */
  13292. function Light(name, scene) {
  13293. var _this = _super.call(this, name, scene) || this;
  13294. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13295. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13296. _this.intensity = 1.0;
  13297. _this.range = Number.MAX_VALUE;
  13298. /**
  13299. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13300. * of light.
  13301. */
  13302. _this._photometricScale = 1.0;
  13303. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13304. _this._radius = 0.00001;
  13305. _this.renderPriority = 0;
  13306. /**
  13307. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13308. * the current shadow generator.
  13309. */
  13310. _this.shadowEnabled = true;
  13311. _this._excludeWithLayerMask = 0;
  13312. _this._includeOnlyWithLayerMask = 0;
  13313. _this._lightmapMode = 0;
  13314. _this._excludedMeshesIds = new Array();
  13315. _this._includedOnlyMeshesIds = new Array();
  13316. _this.getScene().addLight(_this);
  13317. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13318. _this._buildUniformLayout();
  13319. _this.includedOnlyMeshes = new Array();
  13320. _this.excludedMeshes = new Array();
  13321. _this._resyncMeshes();
  13322. return _this;
  13323. }
  13324. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13325. /**
  13326. * If every light affecting the material is in this lightmapMode,
  13327. * material.lightmapTexture adds or multiplies
  13328. * (depends on material.useLightmapAsShadowmap)
  13329. * after every other light calculations.
  13330. */
  13331. get: function () {
  13332. return Light._LIGHTMAP_DEFAULT;
  13333. },
  13334. enumerable: true,
  13335. configurable: true
  13336. });
  13337. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13338. /**
  13339. * material.lightmapTexture as only diffuse lighting from this light
  13340. * adds pnly specular lighting from this light
  13341. * adds dynamic shadows
  13342. */
  13343. get: function () {
  13344. return Light._LIGHTMAP_SPECULAR;
  13345. },
  13346. enumerable: true,
  13347. configurable: true
  13348. });
  13349. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13350. /**
  13351. * material.lightmapTexture as only lighting
  13352. * no light calculation from this light
  13353. * only adds dynamic shadows from this light
  13354. */
  13355. get: function () {
  13356. return Light._LIGHTMAP_SHADOWSONLY;
  13357. },
  13358. enumerable: true,
  13359. configurable: true
  13360. });
  13361. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13362. /**
  13363. * Each light type uses the default quantity according to its type:
  13364. * point/spot lights use luminous intensity
  13365. * directional lights use illuminance
  13366. */
  13367. get: function () {
  13368. return Light._INTENSITYMODE_AUTOMATIC;
  13369. },
  13370. enumerable: true,
  13371. configurable: true
  13372. });
  13373. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13374. /**
  13375. * lumen (lm)
  13376. */
  13377. get: function () {
  13378. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13379. },
  13380. enumerable: true,
  13381. configurable: true
  13382. });
  13383. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13384. /**
  13385. * candela (lm/sr)
  13386. */
  13387. get: function () {
  13388. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13389. },
  13390. enumerable: true,
  13391. configurable: true
  13392. });
  13393. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13394. /**
  13395. * lux (lm/m^2)
  13396. */
  13397. get: function () {
  13398. return Light._INTENSITYMODE_ILLUMINANCE;
  13399. },
  13400. enumerable: true,
  13401. configurable: true
  13402. });
  13403. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13404. /**
  13405. * nit (cd/m^2)
  13406. */
  13407. get: function () {
  13408. return Light._INTENSITYMODE_LUMINANCE;
  13409. },
  13410. enumerable: true,
  13411. configurable: true
  13412. });
  13413. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13414. /**
  13415. * Light type const id of the point light.
  13416. */
  13417. get: function () {
  13418. return Light._LIGHTTYPEID_POINTLIGHT;
  13419. },
  13420. enumerable: true,
  13421. configurable: true
  13422. });
  13423. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13424. /**
  13425. * Light type const id of the directional light.
  13426. */
  13427. get: function () {
  13428. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13429. },
  13430. enumerable: true,
  13431. configurable: true
  13432. });
  13433. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13434. /**
  13435. * Light type const id of the spot light.
  13436. */
  13437. get: function () {
  13438. return Light._LIGHTTYPEID_SPOTLIGHT;
  13439. },
  13440. enumerable: true,
  13441. configurable: true
  13442. });
  13443. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13444. /**
  13445. * Light type const id of the hemispheric light.
  13446. */
  13447. get: function () {
  13448. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13449. },
  13450. enumerable: true,
  13451. configurable: true
  13452. });
  13453. Object.defineProperty(Light.prototype, "intensityMode", {
  13454. /**
  13455. * Gets the photometric scale used to interpret the intensity.
  13456. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13457. */
  13458. get: function () {
  13459. return this._intensityMode;
  13460. },
  13461. /**
  13462. * Sets the photometric scale used to interpret the intensity.
  13463. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13464. */
  13465. set: function (value) {
  13466. this._intensityMode = value;
  13467. this._computePhotometricScale();
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. ;
  13473. ;
  13474. Object.defineProperty(Light.prototype, "radius", {
  13475. /**
  13476. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13477. */
  13478. get: function () {
  13479. return this._radius;
  13480. },
  13481. /**
  13482. * sets the light radius used by PBR Materials to simulate soft area lights.
  13483. */
  13484. set: function (value) {
  13485. this._radius = value;
  13486. this._computePhotometricScale();
  13487. },
  13488. enumerable: true,
  13489. configurable: true
  13490. });
  13491. ;
  13492. ;
  13493. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13494. get: function () {
  13495. return this._includedOnlyMeshes;
  13496. },
  13497. set: function (value) {
  13498. this._includedOnlyMeshes = value;
  13499. this._hookArrayForIncludedOnly(value);
  13500. },
  13501. enumerable: true,
  13502. configurable: true
  13503. });
  13504. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13505. get: function () {
  13506. return this._excludedMeshes;
  13507. },
  13508. set: function (value) {
  13509. this._excludedMeshes = value;
  13510. this._hookArrayForExcluded(value);
  13511. },
  13512. enumerable: true,
  13513. configurable: true
  13514. });
  13515. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13516. get: function () {
  13517. return this._excludeWithLayerMask;
  13518. },
  13519. set: function (value) {
  13520. this._excludeWithLayerMask = value;
  13521. this._resyncMeshes();
  13522. },
  13523. enumerable: true,
  13524. configurable: true
  13525. });
  13526. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13527. get: function () {
  13528. return this._includeOnlyWithLayerMask;
  13529. },
  13530. set: function (value) {
  13531. this._includeOnlyWithLayerMask = value;
  13532. this._resyncMeshes();
  13533. },
  13534. enumerable: true,
  13535. configurable: true
  13536. });
  13537. Object.defineProperty(Light.prototype, "lightmapMode", {
  13538. get: function () {
  13539. return this._lightmapMode;
  13540. },
  13541. set: function (value) {
  13542. if (this._lightmapMode === value) {
  13543. return;
  13544. }
  13545. this._lightmapMode = value;
  13546. this._markMeshesAsLightDirty();
  13547. },
  13548. enumerable: true,
  13549. configurable: true
  13550. });
  13551. Light.prototype._buildUniformLayout = function () {
  13552. // Overridden
  13553. };
  13554. /**
  13555. * Returns the string "Light".
  13556. */
  13557. Light.prototype.getClassName = function () {
  13558. return "Light";
  13559. };
  13560. /**
  13561. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13562. */
  13563. Light.prototype.toString = function (fullDetails) {
  13564. var ret = "Name: " + this.name;
  13565. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13566. if (this.animations) {
  13567. for (var i = 0; i < this.animations.length; i++) {
  13568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13569. }
  13570. }
  13571. if (fullDetails) {
  13572. }
  13573. return ret;
  13574. };
  13575. /**
  13576. * Set the enabled state of this node.
  13577. * @param {boolean} value - the new enabled state
  13578. * @see isEnabled
  13579. */
  13580. Light.prototype.setEnabled = function (value) {
  13581. _super.prototype.setEnabled.call(this, value);
  13582. this._resyncMeshes();
  13583. };
  13584. /**
  13585. * Returns the Light associated shadow generator.
  13586. */
  13587. Light.prototype.getShadowGenerator = function () {
  13588. return this._shadowGenerator;
  13589. };
  13590. /**
  13591. * Returns a Vector3, the absolute light position in the World.
  13592. */
  13593. Light.prototype.getAbsolutePosition = function () {
  13594. return BABYLON.Vector3.Zero();
  13595. };
  13596. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13597. };
  13598. Light.prototype._getWorldMatrix = function () {
  13599. return BABYLON.Matrix.Identity();
  13600. };
  13601. /**
  13602. * Boolean : True if the light will affect the passed mesh.
  13603. */
  13604. Light.prototype.canAffectMesh = function (mesh) {
  13605. if (!mesh) {
  13606. return true;
  13607. }
  13608. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13609. return false;
  13610. }
  13611. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13612. return false;
  13613. }
  13614. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13615. return false;
  13616. }
  13617. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13618. return false;
  13619. }
  13620. return true;
  13621. };
  13622. /**
  13623. * Returns the light World matrix.
  13624. */
  13625. Light.prototype.getWorldMatrix = function () {
  13626. this._currentRenderId = this.getScene().getRenderId();
  13627. var worldMatrix = this._getWorldMatrix();
  13628. if (this.parent && this.parent.getWorldMatrix) {
  13629. if (!this._parentedWorldMatrix) {
  13630. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13631. }
  13632. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13633. this._markSyncedWithParent();
  13634. return this._parentedWorldMatrix;
  13635. }
  13636. return worldMatrix;
  13637. };
  13638. /**
  13639. * Sort function to order lights for rendering.
  13640. * @param a First Light object to compare to second.
  13641. * @param b Second Light object to compare first.
  13642. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13643. */
  13644. Light.compareLightsPriority = function (a, b) {
  13645. //shadow-casting lights have priority over non-shadow-casting lights
  13646. //the renderPrioirty is a secondary sort criterion
  13647. if (a.shadowEnabled !== b.shadowEnabled) {
  13648. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13649. }
  13650. return b.renderPriority - a.renderPriority;
  13651. };
  13652. /**
  13653. * Disposes the light.
  13654. */
  13655. Light.prototype.dispose = function () {
  13656. if (this._shadowGenerator) {
  13657. this._shadowGenerator.dispose();
  13658. this._shadowGenerator = null;
  13659. }
  13660. // Animations
  13661. this.getScene().stopAnimation(this);
  13662. // Remove from meshes
  13663. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13664. var mesh = _a[_i];
  13665. mesh._removeLightSource(this);
  13666. }
  13667. this._uniformBuffer.dispose();
  13668. // Remove from scene
  13669. this.getScene().removeLight(this);
  13670. _super.prototype.dispose.call(this);
  13671. };
  13672. /**
  13673. * Returns the light type ID (integer).
  13674. */
  13675. Light.prototype.getTypeID = function () {
  13676. return 0;
  13677. };
  13678. /**
  13679. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13680. */
  13681. Light.prototype.getScaledIntensity = function () {
  13682. return this._photometricScale * this.intensity;
  13683. };
  13684. /**
  13685. * Returns a new Light object, named "name", from the current one.
  13686. */
  13687. Light.prototype.clone = function (name) {
  13688. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13689. };
  13690. /**
  13691. * Serializes the current light into a Serialization object.
  13692. * Returns the serialized object.
  13693. */
  13694. Light.prototype.serialize = function () {
  13695. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13696. // Type
  13697. serializationObject.type = this.getTypeID();
  13698. // Parent
  13699. if (this.parent) {
  13700. serializationObject.parentId = this.parent.id;
  13701. }
  13702. // Inclusion / exclusions
  13703. if (this.excludedMeshes.length > 0) {
  13704. serializationObject.excludedMeshesIds = [];
  13705. this.excludedMeshes.forEach(function (mesh) {
  13706. serializationObject.excludedMeshesIds.push(mesh.id);
  13707. });
  13708. }
  13709. if (this.includedOnlyMeshes.length > 0) {
  13710. serializationObject.includedOnlyMeshesIds = [];
  13711. this.includedOnlyMeshes.forEach(function (mesh) {
  13712. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13713. });
  13714. }
  13715. // Animations
  13716. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13717. serializationObject.ranges = this.serializeAnimationRanges();
  13718. return serializationObject;
  13719. };
  13720. /**
  13721. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13722. * This new light is named "name" and added to the passed scene.
  13723. */
  13724. Light.GetConstructorFromName = function (type, name, scene) {
  13725. switch (type) {
  13726. case 0:
  13727. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13728. case 1:
  13729. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13730. case 2:
  13731. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13732. case 3:
  13733. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13734. }
  13735. };
  13736. /**
  13737. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13738. */
  13739. Light.Parse = function (parsedLight, scene) {
  13740. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13741. // Inclusion / exclusions
  13742. if (parsedLight.excludedMeshesIds) {
  13743. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13744. }
  13745. if (parsedLight.includedOnlyMeshesIds) {
  13746. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13747. }
  13748. // Parent
  13749. if (parsedLight.parentId) {
  13750. light._waitingParentId = parsedLight.parentId;
  13751. }
  13752. // Animations
  13753. if (parsedLight.animations) {
  13754. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13755. var parsedAnimation = parsedLight.animations[animationIndex];
  13756. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13757. }
  13758. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13759. }
  13760. if (parsedLight.autoAnimate) {
  13761. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13762. }
  13763. return light;
  13764. };
  13765. Light.prototype._hookArrayForExcluded = function (array) {
  13766. var _this = this;
  13767. var oldPush = array.push;
  13768. array.push = function () {
  13769. var items = [];
  13770. for (var _i = 0; _i < arguments.length; _i++) {
  13771. items[_i] = arguments[_i];
  13772. }
  13773. var result = oldPush.apply(array, items);
  13774. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13775. var item = items_1[_a];
  13776. item._resyncLighSource(_this);
  13777. }
  13778. return result;
  13779. };
  13780. var oldSplice = array.splice;
  13781. array.splice = function (index, deleteCount) {
  13782. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13783. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13784. var item = deleted_1[_i];
  13785. item._resyncLighSource(_this);
  13786. }
  13787. return deleted;
  13788. };
  13789. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13790. var item = array_1[_i];
  13791. item._resyncLighSource(this);
  13792. }
  13793. };
  13794. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13795. var _this = this;
  13796. var oldPush = array.push;
  13797. array.push = function () {
  13798. var items = [];
  13799. for (var _i = 0; _i < arguments.length; _i++) {
  13800. items[_i] = arguments[_i];
  13801. }
  13802. var result = oldPush.apply(array, items);
  13803. _this._resyncMeshes();
  13804. return result;
  13805. };
  13806. var oldSplice = array.splice;
  13807. array.splice = function (index, deleteCount) {
  13808. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13809. _this._resyncMeshes();
  13810. return deleted;
  13811. };
  13812. this._resyncMeshes();
  13813. };
  13814. Light.prototype._resyncMeshes = function () {
  13815. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13816. var mesh = _a[_i];
  13817. mesh._resyncLighSource(this);
  13818. }
  13819. };
  13820. Light.prototype._markMeshesAsLightDirty = function () {
  13821. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13822. var mesh = _a[_i];
  13823. if (mesh._lightSources.indexOf(this) !== -1) {
  13824. mesh._markSubMeshesAsLightDirty();
  13825. }
  13826. }
  13827. };
  13828. /**
  13829. * Recomputes the cached photometric scale if needed.
  13830. */
  13831. Light.prototype._computePhotometricScale = function () {
  13832. this._photometricScale = this._getPhotometricScale();
  13833. this.getScene().resetCachedMaterial();
  13834. };
  13835. /**
  13836. * Returns the Photometric Scale according to the light type and intensity mode.
  13837. */
  13838. Light.prototype._getPhotometricScale = function () {
  13839. var photometricScale = 0.0;
  13840. var lightTypeID = this.getTypeID();
  13841. //get photometric mode
  13842. var photometricMode = this.intensityMode;
  13843. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13844. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13845. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13846. }
  13847. else {
  13848. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13849. }
  13850. }
  13851. //compute photometric scale
  13852. switch (lightTypeID) {
  13853. case Light.LIGHTTYPEID_POINTLIGHT:
  13854. case Light.LIGHTTYPEID_SPOTLIGHT:
  13855. switch (photometricMode) {
  13856. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13857. photometricScale = 1.0 / (4.0 * Math.PI);
  13858. break;
  13859. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13860. photometricScale = 1.0;
  13861. break;
  13862. case Light.INTENSITYMODE_LUMINANCE:
  13863. photometricScale = this.radius * this.radius;
  13864. break;
  13865. }
  13866. break;
  13867. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13868. switch (photometricMode) {
  13869. case Light.INTENSITYMODE_ILLUMINANCE:
  13870. photometricScale = 1.0;
  13871. break;
  13872. case Light.INTENSITYMODE_LUMINANCE:
  13873. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13874. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13875. var apexAngleRadians = this.radius;
  13876. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13877. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13878. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13879. photometricScale = solidAngle;
  13880. break;
  13881. }
  13882. break;
  13883. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13884. // No fall off in hemisperic light.
  13885. photometricScale = 1.0;
  13886. break;
  13887. }
  13888. return photometricScale;
  13889. };
  13890. Light.prototype._reorderLightsInScene = function () {
  13891. var scene = this.getScene();
  13892. if (this.renderPriority != 0) {
  13893. scene.requireLightSorting = true;
  13894. }
  13895. this.getScene().sortLightsByPriority();
  13896. };
  13897. return Light;
  13898. }(BABYLON.Node));
  13899. //lightmapMode Consts
  13900. Light._LIGHTMAP_DEFAULT = 0;
  13901. Light._LIGHTMAP_SPECULAR = 1;
  13902. Light._LIGHTMAP_SHADOWSONLY = 2;
  13903. // Intensity Mode Consts
  13904. Light._INTENSITYMODE_AUTOMATIC = 0;
  13905. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13906. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13907. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13908. Light._INTENSITYMODE_LUMINANCE = 4;
  13909. // Light types ids const.
  13910. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13911. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13912. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13913. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13914. __decorate([
  13915. BABYLON.serializeAsColor3()
  13916. ], Light.prototype, "diffuse", void 0);
  13917. __decorate([
  13918. BABYLON.serializeAsColor3()
  13919. ], Light.prototype, "specular", void 0);
  13920. __decorate([
  13921. BABYLON.serialize()
  13922. ], Light.prototype, "intensity", void 0);
  13923. __decorate([
  13924. BABYLON.serialize()
  13925. ], Light.prototype, "range", void 0);
  13926. __decorate([
  13927. BABYLON.serialize()
  13928. ], Light.prototype, "intensityMode", null);
  13929. __decorate([
  13930. BABYLON.serialize()
  13931. ], Light.prototype, "radius", null);
  13932. __decorate([
  13933. BABYLON.serialize()
  13934. ], Light.prototype, "_renderPriority", void 0);
  13935. __decorate([
  13936. BABYLON.expandToProperty("_reorderLightsInScene")
  13937. ], Light.prototype, "renderPriority", void 0);
  13938. __decorate([
  13939. BABYLON.serialize()
  13940. ], Light.prototype, "shadowEnabled", void 0);
  13941. __decorate([
  13942. BABYLON.serialize("excludeWithLayerMask")
  13943. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13944. __decorate([
  13945. BABYLON.serialize("includeOnlyWithLayerMask")
  13946. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13947. __decorate([
  13948. BABYLON.serialize("lightmapMode")
  13949. ], Light.prototype, "_lightmapMode", void 0);
  13950. BABYLON.Light = Light;
  13951. })(BABYLON || (BABYLON = {}));
  13952. //# sourceMappingURL=babylon.light.js.map
  13953. var BABYLON;
  13954. (function (BABYLON) {
  13955. var Camera = (function (_super) {
  13956. __extends(Camera, _super);
  13957. function Camera(name, position, scene) {
  13958. var _this = _super.call(this, name, scene) || this;
  13959. _this.upVector = BABYLON.Vector3.Up();
  13960. _this.orthoLeft = null;
  13961. _this.orthoRight = null;
  13962. _this.orthoBottom = null;
  13963. _this.orthoTop = null;
  13964. _this.fov = 0.8;
  13965. _this.minZ = 1.0;
  13966. _this.maxZ = 10000.0;
  13967. _this.inertia = 0.9;
  13968. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13969. _this.isIntermediate = false;
  13970. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13971. _this.layerMask = 0x0FFFFFFF;
  13972. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13973. // Camera rig members
  13974. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13975. _this._rigCameras = new Array();
  13976. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13977. _this.customRenderTargets = new Array();
  13978. // Cache
  13979. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13980. _this._projectionMatrix = new BABYLON.Matrix();
  13981. _this._doNotComputeProjectionMatrix = false;
  13982. _this._postProcesses = new Array();
  13983. _this._transformMatrix = BABYLON.Matrix.Zero();
  13984. _this._activeMeshes = new BABYLON.SmartArray(256);
  13985. _this._globalPosition = BABYLON.Vector3.Zero();
  13986. _this._refreshFrustumPlanes = true;
  13987. _this.getScene().addCamera(_this);
  13988. if (!_this.getScene().activeCamera) {
  13989. _this.getScene().activeCamera = _this;
  13990. }
  13991. _this.position = position;
  13992. return _this;
  13993. }
  13994. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13995. get: function () {
  13996. return Camera._PERSPECTIVE_CAMERA;
  13997. },
  13998. enumerable: true,
  13999. configurable: true
  14000. });
  14001. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14002. get: function () {
  14003. return Camera._ORTHOGRAPHIC_CAMERA;
  14004. },
  14005. enumerable: true,
  14006. configurable: true
  14007. });
  14008. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14009. get: function () {
  14010. return Camera._FOVMODE_VERTICAL_FIXED;
  14011. },
  14012. enumerable: true,
  14013. configurable: true
  14014. });
  14015. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14016. get: function () {
  14017. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14018. },
  14019. enumerable: true,
  14020. configurable: true
  14021. });
  14022. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14023. get: function () {
  14024. return Camera._RIG_MODE_NONE;
  14025. },
  14026. enumerable: true,
  14027. configurable: true
  14028. });
  14029. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14030. get: function () {
  14031. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14032. },
  14033. enumerable: true,
  14034. configurable: true
  14035. });
  14036. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14037. get: function () {
  14038. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14039. },
  14040. enumerable: true,
  14041. configurable: true
  14042. });
  14043. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14044. get: function () {
  14045. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14046. },
  14047. enumerable: true,
  14048. configurable: true
  14049. });
  14050. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14051. get: function () {
  14052. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14053. },
  14054. enumerable: true,
  14055. configurable: true
  14056. });
  14057. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14058. get: function () {
  14059. return Camera._RIG_MODE_VR;
  14060. },
  14061. enumerable: true,
  14062. configurable: true
  14063. });
  14064. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14065. get: function () {
  14066. return Camera._RIG_MODE_WEBVR;
  14067. },
  14068. enumerable: true,
  14069. configurable: true
  14070. });
  14071. Camera.prototype.getClassName = function () {
  14072. return "Camera";
  14073. };
  14074. /**
  14075. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14076. */
  14077. Camera.prototype.toString = function (fullDetails) {
  14078. var ret = "Name: " + this.name;
  14079. ret += ", type: " + this.getClassName();
  14080. if (this.animations) {
  14081. for (var i = 0; i < this.animations.length; i++) {
  14082. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14083. }
  14084. }
  14085. if (fullDetails) {
  14086. }
  14087. return ret;
  14088. };
  14089. Object.defineProperty(Camera.prototype, "globalPosition", {
  14090. get: function () {
  14091. return this._globalPosition;
  14092. },
  14093. enumerable: true,
  14094. configurable: true
  14095. });
  14096. Camera.prototype.getActiveMeshes = function () {
  14097. return this._activeMeshes;
  14098. };
  14099. Camera.prototype.isActiveMesh = function (mesh) {
  14100. return (this._activeMeshes.indexOf(mesh) !== -1);
  14101. };
  14102. //Cache
  14103. Camera.prototype._initCache = function () {
  14104. _super.prototype._initCache.call(this);
  14105. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14106. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14107. this._cache.mode = undefined;
  14108. this._cache.minZ = undefined;
  14109. this._cache.maxZ = undefined;
  14110. this._cache.fov = undefined;
  14111. this._cache.fovMode = undefined;
  14112. this._cache.aspectRatio = undefined;
  14113. this._cache.orthoLeft = undefined;
  14114. this._cache.orthoRight = undefined;
  14115. this._cache.orthoBottom = undefined;
  14116. this._cache.orthoTop = undefined;
  14117. this._cache.renderWidth = undefined;
  14118. this._cache.renderHeight = undefined;
  14119. };
  14120. Camera.prototype._updateCache = function (ignoreParentClass) {
  14121. if (!ignoreParentClass) {
  14122. _super.prototype._updateCache.call(this);
  14123. }
  14124. var engine = this.getEngine();
  14125. this._cache.position.copyFrom(this.position);
  14126. this._cache.upVector.copyFrom(this.upVector);
  14127. this._cache.mode = this.mode;
  14128. this._cache.minZ = this.minZ;
  14129. this._cache.maxZ = this.maxZ;
  14130. this._cache.fov = this.fov;
  14131. this._cache.fovMode = this.fovMode;
  14132. this._cache.aspectRatio = engine.getAspectRatio(this);
  14133. this._cache.orthoLeft = this.orthoLeft;
  14134. this._cache.orthoRight = this.orthoRight;
  14135. this._cache.orthoBottom = this.orthoBottom;
  14136. this._cache.orthoTop = this.orthoTop;
  14137. this._cache.renderWidth = engine.getRenderWidth();
  14138. this._cache.renderHeight = engine.getRenderHeight();
  14139. };
  14140. Camera.prototype._updateFromScene = function () {
  14141. this.updateCache();
  14142. this.update();
  14143. };
  14144. // Synchronized
  14145. Camera.prototype._isSynchronized = function () {
  14146. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14147. };
  14148. Camera.prototype._isSynchronizedViewMatrix = function () {
  14149. if (!_super.prototype._isSynchronized.call(this))
  14150. return false;
  14151. return this._cache.position.equals(this.position)
  14152. && this._cache.upVector.equals(this.upVector)
  14153. && this.isSynchronizedWithParent();
  14154. };
  14155. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14156. var check = this._cache.mode === this.mode
  14157. && this._cache.minZ === this.minZ
  14158. && this._cache.maxZ === this.maxZ;
  14159. if (!check) {
  14160. return false;
  14161. }
  14162. var engine = this.getEngine();
  14163. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14164. check = this._cache.fov === this.fov
  14165. && this._cache.fovMode === this.fovMode
  14166. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14167. }
  14168. else {
  14169. check = this._cache.orthoLeft === this.orthoLeft
  14170. && this._cache.orthoRight === this.orthoRight
  14171. && this._cache.orthoBottom === this.orthoBottom
  14172. && this._cache.orthoTop === this.orthoTop
  14173. && this._cache.renderWidth === engine.getRenderWidth()
  14174. && this._cache.renderHeight === engine.getRenderHeight();
  14175. }
  14176. return check;
  14177. };
  14178. // Controls
  14179. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14180. };
  14181. Camera.prototype.detachControl = function (element) {
  14182. };
  14183. Camera.prototype.update = function () {
  14184. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14185. this._updateRigCameras();
  14186. }
  14187. this._checkInputs();
  14188. };
  14189. Camera.prototype._checkInputs = function () {
  14190. };
  14191. Object.defineProperty(Camera.prototype, "rigCameras", {
  14192. get: function () {
  14193. return this._rigCameras;
  14194. },
  14195. enumerable: true,
  14196. configurable: true
  14197. });
  14198. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14199. get: function () {
  14200. return this._rigPostProcess;
  14201. },
  14202. enumerable: true,
  14203. configurable: true
  14204. });
  14205. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14206. // invalidate framebuffer
  14207. if (this._postProcesses.length > 0) {
  14208. this._postProcesses[0].markTextureDirty();
  14209. }
  14210. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14211. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14212. var cam = this._rigCameras[i];
  14213. var rigPostProcess = cam._rigPostProcess;
  14214. // for VR rig, there does not have to be a post process
  14215. if (rigPostProcess) {
  14216. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14217. if (isPass) {
  14218. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14219. cam.isIntermediate = this._postProcesses.length === 0;
  14220. }
  14221. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14222. rigPostProcess.markTextureDirty();
  14223. }
  14224. else {
  14225. cam._postProcesses = this._postProcesses.slice(0);
  14226. }
  14227. }
  14228. };
  14229. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14230. if (insertAt === void 0) { insertAt = null; }
  14231. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14232. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14233. return 0;
  14234. }
  14235. if (insertAt == null || insertAt < 0) {
  14236. this._postProcesses.push(postProcess);
  14237. }
  14238. else {
  14239. this._postProcesses.splice(insertAt, 0, postProcess);
  14240. }
  14241. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14242. return this._postProcesses.indexOf(postProcess);
  14243. };
  14244. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14245. if (atIndices === void 0) { atIndices = null; }
  14246. var result = [];
  14247. var i;
  14248. var index;
  14249. if (!atIndices) {
  14250. var idx = this._postProcesses.indexOf(postProcess);
  14251. if (idx !== -1) {
  14252. this._postProcesses.splice(idx, 1);
  14253. }
  14254. }
  14255. else {
  14256. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14257. // iterate descending, so can just splice as we go
  14258. for (i = atIndices.length - 1; i >= 0; i--) {
  14259. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14260. result.push(i);
  14261. continue;
  14262. }
  14263. index = atIndices[i];
  14264. this._postProcesses.splice(index, 1);
  14265. }
  14266. }
  14267. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14268. return result;
  14269. };
  14270. Camera.prototype.getWorldMatrix = function () {
  14271. if (!this._worldMatrix) {
  14272. this._worldMatrix = BABYLON.Matrix.Identity();
  14273. }
  14274. var viewMatrix = this.getViewMatrix();
  14275. viewMatrix.invertToRef(this._worldMatrix);
  14276. return this._worldMatrix;
  14277. };
  14278. Camera.prototype._getViewMatrix = function () {
  14279. return BABYLON.Matrix.Identity();
  14280. };
  14281. Camera.prototype.getViewMatrix = function (force) {
  14282. this._computedViewMatrix = this._computeViewMatrix(force);
  14283. if (!force && this._isSynchronizedViewMatrix()) {
  14284. return this._computedViewMatrix;
  14285. }
  14286. this._refreshFrustumPlanes = true;
  14287. if (!this.parent || !this.parent.getWorldMatrix) {
  14288. this._globalPosition.copyFrom(this.position);
  14289. }
  14290. else {
  14291. if (!this._worldMatrix) {
  14292. this._worldMatrix = BABYLON.Matrix.Identity();
  14293. }
  14294. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14295. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14296. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14297. this._computedViewMatrix.invert();
  14298. this._markSyncedWithParent();
  14299. }
  14300. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14301. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14302. }
  14303. this._currentRenderId = this.getScene().getRenderId();
  14304. return this._computedViewMatrix;
  14305. };
  14306. Camera.prototype._computeViewMatrix = function (force) {
  14307. if (!force && this._isSynchronizedViewMatrix()) {
  14308. return this._computedViewMatrix;
  14309. }
  14310. this._computedViewMatrix = this._getViewMatrix();
  14311. this._currentRenderId = this.getScene().getRenderId();
  14312. return this._computedViewMatrix;
  14313. };
  14314. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14315. this._doNotComputeProjectionMatrix = true;
  14316. if (projection !== undefined) {
  14317. this._projectionMatrix = projection;
  14318. }
  14319. };
  14320. ;
  14321. Camera.prototype.unfreezeProjectionMatrix = function () {
  14322. this._doNotComputeProjectionMatrix = false;
  14323. };
  14324. ;
  14325. Camera.prototype.getProjectionMatrix = function (force) {
  14326. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14327. return this._projectionMatrix;
  14328. }
  14329. this._refreshFrustumPlanes = true;
  14330. var engine = this.getEngine();
  14331. var scene = this.getScene();
  14332. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14333. if (this.minZ <= 0) {
  14334. this.minZ = 0.1;
  14335. }
  14336. if (scene.useRightHandedSystem) {
  14337. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14338. }
  14339. else {
  14340. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14341. }
  14342. return this._projectionMatrix;
  14343. }
  14344. var halfWidth = engine.getRenderWidth() / 2.0;
  14345. var halfHeight = engine.getRenderHeight() / 2.0;
  14346. if (scene.useRightHandedSystem) {
  14347. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14348. }
  14349. else {
  14350. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14351. }
  14352. return this._projectionMatrix;
  14353. };
  14354. Camera.prototype.getTranformationMatrix = function () {
  14355. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14356. return this._transformMatrix;
  14357. };
  14358. Camera.prototype.updateFrustumPlanes = function () {
  14359. if (!this._refreshFrustumPlanes) {
  14360. return;
  14361. }
  14362. this.getTranformationMatrix();
  14363. if (!this._frustumPlanes) {
  14364. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14365. }
  14366. else {
  14367. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14368. }
  14369. this._refreshFrustumPlanes = false;
  14370. };
  14371. Camera.prototype.isInFrustum = function (target) {
  14372. this.updateFrustumPlanes();
  14373. return target.isInFrustum(this._frustumPlanes);
  14374. };
  14375. Camera.prototype.isCompletelyInFrustum = function (target) {
  14376. this.updateFrustumPlanes();
  14377. return target.isCompletelyInFrustum(this._frustumPlanes);
  14378. };
  14379. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14380. if (length === void 0) { length = 100; }
  14381. if (!transform) {
  14382. transform = this.getWorldMatrix();
  14383. }
  14384. if (!origin) {
  14385. origin = this.position;
  14386. }
  14387. var forward = new BABYLON.Vector3(0, 0, 1);
  14388. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14389. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14390. return new BABYLON.Ray(origin, direction, length);
  14391. };
  14392. Camera.prototype.dispose = function () {
  14393. // Animations
  14394. this.getScene().stopAnimation(this);
  14395. // Remove from scene
  14396. this.getScene().removeCamera(this);
  14397. while (this._rigCameras.length > 0) {
  14398. this._rigCameras.pop().dispose();
  14399. }
  14400. // Postprocesses
  14401. var i = this._postProcesses.length;
  14402. while (--i >= 0) {
  14403. this._postProcesses[i].dispose(this);
  14404. }
  14405. _super.prototype.dispose.call(this);
  14406. };
  14407. Object.defineProperty(Camera.prototype, "leftCamera", {
  14408. // ---- Camera rigs section ----
  14409. get: function () {
  14410. if (this._rigCameras.length < 1) {
  14411. return undefined;
  14412. }
  14413. return this._rigCameras[0];
  14414. },
  14415. enumerable: true,
  14416. configurable: true
  14417. });
  14418. Object.defineProperty(Camera.prototype, "rightCamera", {
  14419. get: function () {
  14420. if (this._rigCameras.length < 2) {
  14421. return undefined;
  14422. }
  14423. return this._rigCameras[1];
  14424. },
  14425. enumerable: true,
  14426. configurable: true
  14427. });
  14428. Camera.prototype.getLeftTarget = function () {
  14429. if (this._rigCameras.length < 1) {
  14430. return undefined;
  14431. }
  14432. return this._rigCameras[0].getTarget();
  14433. };
  14434. Camera.prototype.getRightTarget = function () {
  14435. if (this._rigCameras.length < 2) {
  14436. return undefined;
  14437. }
  14438. return this._rigCameras[1].getTarget();
  14439. };
  14440. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14441. while (this._rigCameras.length > 0) {
  14442. this._rigCameras.pop().dispose();
  14443. }
  14444. this.cameraRigMode = mode;
  14445. this._cameraRigParams = {};
  14446. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14447. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14448. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14449. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14450. // create the rig cameras, unless none
  14451. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14452. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14453. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14454. }
  14455. switch (this.cameraRigMode) {
  14456. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14457. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14458. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14459. break;
  14460. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14461. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14462. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14463. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14464. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14465. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14466. break;
  14467. case Camera.RIG_MODE_VR:
  14468. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14469. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14470. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14471. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14472. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14473. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14474. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14475. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14476. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14477. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14478. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14479. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14480. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14481. if (metrics.compensateDistortion) {
  14482. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14483. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14484. }
  14485. break;
  14486. case Camera.RIG_MODE_WEBVR:
  14487. if (rigParams.vrDisplay) {
  14488. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14489. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14490. //Left eye
  14491. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14492. this._rigCameras[0].setCameraRigParameter("left", true);
  14493. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14494. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14495. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14496. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14497. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14498. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14499. this._rigCameras[0].parent = this;
  14500. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14501. //Right eye
  14502. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14503. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14504. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14505. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14506. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14507. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14508. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14509. this._rigCameras[1].parent = this;
  14510. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14511. }
  14512. break;
  14513. }
  14514. this._cascadePostProcessesToRigCams();
  14515. this.
  14516. update();
  14517. };
  14518. Camera.prototype._getVRProjectionMatrix = function () {
  14519. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14520. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14521. return this._projectionMatrix;
  14522. };
  14523. Camera.prototype._updateCameraRotationMatrix = function () {
  14524. //Here for WebVR
  14525. };
  14526. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14527. //Here for WebVR
  14528. };
  14529. /**
  14530. * This function MUST be overwritten by the different WebVR cameras available.
  14531. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14532. */
  14533. Camera.prototype._getWebVRProjectionMatrix = function () {
  14534. return BABYLON.Matrix.Identity();
  14535. };
  14536. /**
  14537. * This function MUST be overwritten by the different WebVR cameras available.
  14538. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14539. */
  14540. Camera.prototype._getWebVRViewMatrix = function () {
  14541. return BABYLON.Matrix.Identity();
  14542. };
  14543. Camera.prototype.setCameraRigParameter = function (name, value) {
  14544. if (!this._cameraRigParams) {
  14545. this._cameraRigParams = {};
  14546. }
  14547. this._cameraRigParams[name] = value;
  14548. //provisionnally:
  14549. if (name === "interaxialDistance") {
  14550. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14551. }
  14552. };
  14553. /**
  14554. * needs to be overridden by children so sub has required properties to be copied
  14555. */
  14556. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14557. return null;
  14558. };
  14559. /**
  14560. * May need to be overridden by children
  14561. */
  14562. Camera.prototype._updateRigCameras = function () {
  14563. for (var i = 0; i < this._rigCameras.length; i++) {
  14564. this._rigCameras[i].minZ = this.minZ;
  14565. this._rigCameras[i].maxZ = this.maxZ;
  14566. this._rigCameras[i].fov = this.fov;
  14567. }
  14568. // only update viewport when ANAGLYPH
  14569. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14570. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14571. }
  14572. };
  14573. Camera.prototype._setupInputs = function () {
  14574. };
  14575. Camera.prototype.serialize = function () {
  14576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14577. // Type
  14578. serializationObject.type = this.getClassName();
  14579. // Parent
  14580. if (this.parent) {
  14581. serializationObject.parentId = this.parent.id;
  14582. }
  14583. if (this.inputs) {
  14584. this.inputs.serialize(serializationObject);
  14585. }
  14586. // Animations
  14587. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14588. serializationObject.ranges = this.serializeAnimationRanges();
  14589. return serializationObject;
  14590. };
  14591. Camera.prototype.clone = function (name) {
  14592. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14593. };
  14594. Camera.prototype.getDirection = function (localAxis) {
  14595. var result = BABYLON.Vector3.Zero();
  14596. this.getDirectionToRef(localAxis, result);
  14597. return result;
  14598. };
  14599. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14600. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14601. };
  14602. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14603. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14604. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14605. switch (type) {
  14606. case "ArcRotateCamera":
  14607. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14608. case "DeviceOrientationCamera":
  14609. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14610. case "FollowCamera":
  14611. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14612. case "ArcFollowCamera":
  14613. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14614. case "GamepadCamera":
  14615. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14616. case "TouchCamera":
  14617. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14618. case "VirtualJoysticksCamera":
  14619. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14620. case "WebVRFreeCamera":
  14621. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14622. case "WebVRGamepadCamera":
  14623. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14624. case "VRDeviceOrientationFreeCamera":
  14625. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14626. case "VRDeviceOrientationGamepadCamera":
  14627. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14628. case "AnaglyphArcRotateCamera":
  14629. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14630. case "AnaglyphFreeCamera":
  14631. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14632. case "AnaglyphGamepadCamera":
  14633. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14634. case "AnaglyphUniversalCamera":
  14635. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14636. case "StereoscopicArcRotateCamera":
  14637. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14638. case "StereoscopicFreeCamera":
  14639. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14640. case "StereoscopicGamepadCamera":
  14641. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14642. case "StereoscopicUniversalCamera":
  14643. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14644. case "FreeCamera":
  14645. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14646. default:
  14647. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14648. }
  14649. };
  14650. Camera.Parse = function (parsedCamera, scene) {
  14651. var type = parsedCamera.type;
  14652. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14653. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14654. // Parent
  14655. if (parsedCamera.parentId) {
  14656. camera._waitingParentId = parsedCamera.parentId;
  14657. }
  14658. //If camera has an input manager, let it parse inputs settings
  14659. if (camera.inputs) {
  14660. camera.inputs.parse(parsedCamera);
  14661. camera._setupInputs();
  14662. }
  14663. if (camera.setPosition) {
  14664. camera.position.copyFromFloats(0, 0, 0);
  14665. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14666. }
  14667. // Target
  14668. if (parsedCamera.target) {
  14669. if (camera.setTarget) {
  14670. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14671. }
  14672. }
  14673. // Apply 3d rig, when found
  14674. if (parsedCamera.cameraRigMode) {
  14675. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14676. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14677. }
  14678. // Animations
  14679. if (parsedCamera.animations) {
  14680. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14681. var parsedAnimation = parsedCamera.animations[animationIndex];
  14682. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14683. }
  14684. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14685. }
  14686. if (parsedCamera.autoAnimate) {
  14687. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14688. }
  14689. return camera;
  14690. };
  14691. return Camera;
  14692. }(BABYLON.Node));
  14693. // Statics
  14694. Camera._PERSPECTIVE_CAMERA = 0;
  14695. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14696. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14697. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14698. Camera._RIG_MODE_NONE = 0;
  14699. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14700. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14701. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14702. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14703. Camera._RIG_MODE_VR = 20;
  14704. Camera._RIG_MODE_WEBVR = 21;
  14705. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14706. __decorate([
  14707. BABYLON.serializeAsVector3()
  14708. ], Camera.prototype, "position", void 0);
  14709. __decorate([
  14710. BABYLON.serializeAsVector3()
  14711. ], Camera.prototype, "upVector", void 0);
  14712. __decorate([
  14713. BABYLON.serialize()
  14714. ], Camera.prototype, "orthoLeft", void 0);
  14715. __decorate([
  14716. BABYLON.serialize()
  14717. ], Camera.prototype, "orthoRight", void 0);
  14718. __decorate([
  14719. BABYLON.serialize()
  14720. ], Camera.prototype, "orthoBottom", void 0);
  14721. __decorate([
  14722. BABYLON.serialize()
  14723. ], Camera.prototype, "orthoTop", void 0);
  14724. __decorate([
  14725. BABYLON.serialize()
  14726. ], Camera.prototype, "fov", void 0);
  14727. __decorate([
  14728. BABYLON.serialize()
  14729. ], Camera.prototype, "minZ", void 0);
  14730. __decorate([
  14731. BABYLON.serialize()
  14732. ], Camera.prototype, "maxZ", void 0);
  14733. __decorate([
  14734. BABYLON.serialize()
  14735. ], Camera.prototype, "inertia", void 0);
  14736. __decorate([
  14737. BABYLON.serialize()
  14738. ], Camera.prototype, "mode", void 0);
  14739. __decorate([
  14740. BABYLON.serialize()
  14741. ], Camera.prototype, "layerMask", void 0);
  14742. __decorate([
  14743. BABYLON.serialize()
  14744. ], Camera.prototype, "fovMode", void 0);
  14745. __decorate([
  14746. BABYLON.serialize()
  14747. ], Camera.prototype, "cameraRigMode", void 0);
  14748. __decorate([
  14749. BABYLON.serialize()
  14750. ], Camera.prototype, "interaxialDistance", void 0);
  14751. __decorate([
  14752. BABYLON.serialize()
  14753. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14754. BABYLON.Camera = Camera;
  14755. })(BABYLON || (BABYLON = {}));
  14756. //# sourceMappingURL=babylon.camera.js.map
  14757. var BABYLON;
  14758. (function (BABYLON) {
  14759. var RenderingManager = (function () {
  14760. function RenderingManager(scene) {
  14761. this._renderingGroups = new Array();
  14762. this._autoClearDepthStencil = {};
  14763. this._customOpaqueSortCompareFn = {};
  14764. this._customAlphaTestSortCompareFn = {};
  14765. this._customTransparentSortCompareFn = {};
  14766. this._renderinGroupInfo = null;
  14767. this._scene = scene;
  14768. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14769. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14770. }
  14771. }
  14772. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14773. if (depth === void 0) { depth = true; }
  14774. if (stencil === void 0) { stencil = true; }
  14775. if (this._depthStencilBufferAlreadyCleaned) {
  14776. return;
  14777. }
  14778. this._scene.getEngine().clear(null, false, depth, stencil);
  14779. this._depthStencilBufferAlreadyCleaned = true;
  14780. };
  14781. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14782. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14783. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14784. var info = null;
  14785. if (observable) {
  14786. if (!this._renderinGroupInfo) {
  14787. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14788. }
  14789. info = this._renderinGroupInfo;
  14790. info.scene = this._scene;
  14791. info.camera = this._scene.activeCamera;
  14792. }
  14793. // Dispatch sprites
  14794. if (renderSprites) {
  14795. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14796. var manager = this._scene.spriteManagers[index];
  14797. this.dispatchSprites(manager);
  14798. }
  14799. }
  14800. // Render
  14801. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14802. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14803. var renderingGroup = this._renderingGroups[index];
  14804. if (!renderingGroup && !observable)
  14805. continue;
  14806. this._currentIndex = index;
  14807. var renderingGroupMask = 0;
  14808. // Fire PRECLEAR stage
  14809. if (observable) {
  14810. renderingGroupMask = Math.pow(2, index);
  14811. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14812. info.renderingGroupId = index;
  14813. observable.notifyObservers(info, renderingGroupMask);
  14814. }
  14815. // Clear depth/stencil if needed
  14816. if (RenderingManager.AUTOCLEAR) {
  14817. var autoClear = this._autoClearDepthStencil[index];
  14818. if (autoClear && autoClear.autoClear) {
  14819. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14820. }
  14821. }
  14822. if (observable) {
  14823. // Fire PREOPAQUE stage
  14824. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14825. observable.notifyObservers(info, renderingGroupMask);
  14826. // Fire PRETRANSPARENT stage
  14827. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14828. observable.notifyObservers(info, renderingGroupMask);
  14829. }
  14830. if (renderingGroup)
  14831. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14832. // Fire POSTTRANSPARENT stage
  14833. if (observable) {
  14834. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14835. observable.notifyObservers(info, renderingGroupMask);
  14836. }
  14837. }
  14838. };
  14839. RenderingManager.prototype.reset = function () {
  14840. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14841. var renderingGroup = this._renderingGroups[index];
  14842. if (renderingGroup) {
  14843. renderingGroup.prepare();
  14844. }
  14845. }
  14846. };
  14847. RenderingManager.prototype.dispose = function () {
  14848. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14849. var renderingGroup = this._renderingGroups[index];
  14850. if (renderingGroup) {
  14851. renderingGroup.dispose();
  14852. }
  14853. }
  14854. this._renderingGroups.length = 0;
  14855. };
  14856. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14857. if (!this._renderingGroups[renderingGroupId]) {
  14858. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14859. }
  14860. };
  14861. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14862. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14863. this._prepareRenderingGroup(renderingGroupId);
  14864. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14865. };
  14866. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14867. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14868. this._prepareRenderingGroup(renderingGroupId);
  14869. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14870. };
  14871. RenderingManager.prototype.dispatch = function (subMesh) {
  14872. var mesh = subMesh.getMesh();
  14873. var renderingGroupId = mesh.renderingGroupId || 0;
  14874. this._prepareRenderingGroup(renderingGroupId);
  14875. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14876. };
  14877. /**
  14878. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14879. * This allowed control for front to back rendering or reversly depending of the special needs.
  14880. *
  14881. * @param renderingGroupId The rendering group id corresponding to its index
  14882. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14883. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14884. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14885. */
  14886. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14887. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14888. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14889. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14890. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14891. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14892. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14893. if (this._renderingGroups[renderingGroupId]) {
  14894. var group = this._renderingGroups[renderingGroupId];
  14895. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14896. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14897. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14898. }
  14899. };
  14900. /**
  14901. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14902. *
  14903. * @param renderingGroupId The rendering group id corresponding to its index
  14904. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14905. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14906. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14907. */
  14908. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14909. if (depth === void 0) { depth = true; }
  14910. if (stencil === void 0) { stencil = true; }
  14911. this._autoClearDepthStencil[renderingGroupId] = {
  14912. autoClear: autoClearDepthStencil,
  14913. depth: depth,
  14914. stencil: stencil
  14915. };
  14916. };
  14917. return RenderingManager;
  14918. }());
  14919. /**
  14920. * The max id used for rendering groups (not included)
  14921. */
  14922. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14923. /**
  14924. * The min id used for rendering groups (included)
  14925. */
  14926. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14927. /**
  14928. * Used to globally prevent autoclearing scenes.
  14929. */
  14930. RenderingManager.AUTOCLEAR = true;
  14931. BABYLON.RenderingManager = RenderingManager;
  14932. })(BABYLON || (BABYLON = {}));
  14933. //# sourceMappingURL=babylon.renderingManager.js.map
  14934. var BABYLON;
  14935. (function (BABYLON) {
  14936. var RenderingGroup = (function () {
  14937. /**
  14938. * Creates a new rendering group.
  14939. * @param index The rendering group index
  14940. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14941. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14942. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14943. */
  14944. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14945. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14946. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14947. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14948. this.index = index;
  14949. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14950. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14951. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14952. this._particleSystems = new BABYLON.SmartArray(256);
  14953. this._spriteManagers = new BABYLON.SmartArray(256);
  14954. this._edgesRenderers = new BABYLON.SmartArray(16);
  14955. this._scene = scene;
  14956. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14957. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14958. this.transparentSortCompareFn = transparentSortCompareFn;
  14959. }
  14960. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14961. /**
  14962. * Set the opaque sort comparison function.
  14963. * If null the sub meshes will be render in the order they were created
  14964. */
  14965. set: function (value) {
  14966. this._opaqueSortCompareFn = value;
  14967. if (value) {
  14968. this._renderOpaque = this.renderOpaqueSorted;
  14969. }
  14970. else {
  14971. this._renderOpaque = RenderingGroup.renderUnsorted;
  14972. }
  14973. },
  14974. enumerable: true,
  14975. configurable: true
  14976. });
  14977. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14978. /**
  14979. * Set the alpha test sort comparison function.
  14980. * If null the sub meshes will be render in the order they were created
  14981. */
  14982. set: function (value) {
  14983. this._alphaTestSortCompareFn = value;
  14984. if (value) {
  14985. this._renderAlphaTest = this.renderAlphaTestSorted;
  14986. }
  14987. else {
  14988. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14989. }
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14995. /**
  14996. * Set the transparent sort comparison function.
  14997. * If null the sub meshes will be render in the order they were created
  14998. */
  14999. set: function (value) {
  15000. if (value) {
  15001. this._transparentSortCompareFn = value;
  15002. }
  15003. else {
  15004. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15005. }
  15006. this._renderTransparent = this.renderTransparentSorted;
  15007. },
  15008. enumerable: true,
  15009. configurable: true
  15010. });
  15011. /**
  15012. * Render all the sub meshes contained in the group.
  15013. * @param customRenderFunction Used to override the default render behaviour of the group.
  15014. * @returns true if rendered some submeshes.
  15015. */
  15016. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15017. if (customRenderFunction) {
  15018. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15019. return;
  15020. }
  15021. var engine = this._scene.getEngine();
  15022. // Opaque
  15023. if (this._opaqueSubMeshes.length !== 0) {
  15024. this._renderOpaque(this._opaqueSubMeshes);
  15025. }
  15026. // Alpha test
  15027. if (this._alphaTestSubMeshes.length !== 0) {
  15028. engine.setAlphaTesting(true);
  15029. this._renderAlphaTest(this._alphaTestSubMeshes);
  15030. engine.setAlphaTesting(false);
  15031. }
  15032. var stencilState = engine.getStencilBuffer();
  15033. engine.setStencilBuffer(false);
  15034. // Sprites
  15035. if (renderSprites) {
  15036. this._renderSprites();
  15037. }
  15038. // Particles
  15039. if (renderParticles) {
  15040. this._renderParticles(activeMeshes);
  15041. }
  15042. if (this.onBeforeTransparentRendering) {
  15043. this.onBeforeTransparentRendering();
  15044. }
  15045. // Transparent
  15046. if (this._transparentSubMeshes.length !== 0) {
  15047. this._renderTransparent(this._transparentSubMeshes);
  15048. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15049. }
  15050. engine.setStencilBuffer(stencilState);
  15051. // Edges
  15052. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15053. this._edgesRenderers.data[edgesRendererIndex].render();
  15054. }
  15055. };
  15056. /**
  15057. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15058. * @param subMeshes The submeshes to render
  15059. */
  15060. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15061. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15062. };
  15063. /**
  15064. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15065. * @param subMeshes The submeshes to render
  15066. */
  15067. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15068. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15069. };
  15070. /**
  15071. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15072. * @param subMeshes The submeshes to render
  15073. */
  15074. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15075. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15076. };
  15077. /**
  15078. * Renders the submeshes in a specified order.
  15079. * @param subMeshes The submeshes to sort before render
  15080. * @param sortCompareFn The comparison function use to sort
  15081. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15082. * @param transparent Specifies to activate blending if true
  15083. */
  15084. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15085. var subIndex = 0;
  15086. var subMesh;
  15087. for (; subIndex < subMeshes.length; subIndex++) {
  15088. subMesh = subMeshes.data[subIndex];
  15089. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15090. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15091. }
  15092. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15093. sortedArray.sort(sortCompareFn);
  15094. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15095. subMesh = sortedArray[subIndex];
  15096. subMesh.render(transparent);
  15097. }
  15098. };
  15099. /**
  15100. * Renders the submeshes in the order they were dispatched (no sort applied).
  15101. * @param subMeshes The submeshes to render
  15102. */
  15103. RenderingGroup.renderUnsorted = function (subMeshes) {
  15104. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15105. var submesh = subMeshes.data[subIndex];
  15106. submesh.render(false);
  15107. }
  15108. };
  15109. /**
  15110. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15111. * are rendered back to front if in the same alpha index.
  15112. *
  15113. * @param a The first submesh
  15114. * @param b The second submesh
  15115. * @returns The result of the comparison
  15116. */
  15117. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15118. // Alpha index first
  15119. if (a._alphaIndex > b._alphaIndex) {
  15120. return 1;
  15121. }
  15122. if (a._alphaIndex < b._alphaIndex) {
  15123. return -1;
  15124. }
  15125. // Then distance to camera
  15126. return RenderingGroup.backToFrontSortCompare(a, b);
  15127. };
  15128. /**
  15129. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15130. * are rendered back to front.
  15131. *
  15132. * @param a The first submesh
  15133. * @param b The second submesh
  15134. * @returns The result of the comparison
  15135. */
  15136. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15137. // Then distance to camera
  15138. if (a._distanceToCamera < b._distanceToCamera) {
  15139. return 1;
  15140. }
  15141. if (a._distanceToCamera > b._distanceToCamera) {
  15142. return -1;
  15143. }
  15144. return 0;
  15145. };
  15146. /**
  15147. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15148. * are rendered front to back (prevent overdraw).
  15149. *
  15150. * @param a The first submesh
  15151. * @param b The second submesh
  15152. * @returns The result of the comparison
  15153. */
  15154. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15155. // Then distance to camera
  15156. if (a._distanceToCamera < b._distanceToCamera) {
  15157. return -1;
  15158. }
  15159. if (a._distanceToCamera > b._distanceToCamera) {
  15160. return 1;
  15161. }
  15162. return 0;
  15163. };
  15164. /**
  15165. * Resets the different lists of submeshes to prepare a new frame.
  15166. */
  15167. RenderingGroup.prototype.prepare = function () {
  15168. this._opaqueSubMeshes.reset();
  15169. this._transparentSubMeshes.reset();
  15170. this._alphaTestSubMeshes.reset();
  15171. this._particleSystems.reset();
  15172. this._spriteManagers.reset();
  15173. this._edgesRenderers.reset();
  15174. };
  15175. RenderingGroup.prototype.dispose = function () {
  15176. this._opaqueSubMeshes.dispose();
  15177. this._transparentSubMeshes.dispose();
  15178. this._alphaTestSubMeshes.dispose();
  15179. this._particleSystems.dispose();
  15180. this._spriteManagers.dispose();
  15181. this._edgesRenderers.dispose();
  15182. };
  15183. /**
  15184. * Inserts the submesh in its correct queue depending on its material.
  15185. * @param subMesh The submesh to dispatch
  15186. */
  15187. RenderingGroup.prototype.dispatch = function (subMesh) {
  15188. var material = subMesh.getMaterial();
  15189. var mesh = subMesh.getMesh();
  15190. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15191. this._transparentSubMeshes.push(subMesh);
  15192. }
  15193. else if (material.needAlphaTesting()) {
  15194. this._alphaTestSubMeshes.push(subMesh);
  15195. }
  15196. else {
  15197. this._opaqueSubMeshes.push(subMesh); // Opaque
  15198. }
  15199. if (mesh._edgesRenderer) {
  15200. this._edgesRenderers.push(mesh._edgesRenderer);
  15201. }
  15202. };
  15203. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15204. this._spriteManagers.push(spriteManager);
  15205. };
  15206. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15207. this._particleSystems.push(particleSystem);
  15208. };
  15209. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15210. if (this._particleSystems.length === 0) {
  15211. return;
  15212. }
  15213. // Particles
  15214. var activeCamera = this._scene.activeCamera;
  15215. this._scene._particlesDuration.beginMonitoring();
  15216. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15217. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15218. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15219. continue;
  15220. }
  15221. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15222. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15223. }
  15224. }
  15225. this._scene._particlesDuration.endMonitoring(false);
  15226. };
  15227. RenderingGroup.prototype._renderSprites = function () {
  15228. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15229. return;
  15230. }
  15231. // Sprites
  15232. var activeCamera = this._scene.activeCamera;
  15233. this._scene._spritesDuration.beginMonitoring();
  15234. for (var id = 0; id < this._spriteManagers.length; id++) {
  15235. var spriteManager = this._spriteManagers.data[id];
  15236. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15237. spriteManager.render();
  15238. }
  15239. }
  15240. this._scene._spritesDuration.endMonitoring(false);
  15241. };
  15242. return RenderingGroup;
  15243. }());
  15244. BABYLON.RenderingGroup = RenderingGroup;
  15245. })(BABYLON || (BABYLON = {}));
  15246. //# sourceMappingURL=babylon.renderingGroup.js.map
  15247. var BABYLON;
  15248. (function (BABYLON) {
  15249. var ClickInfo = (function () {
  15250. function ClickInfo() {
  15251. this._singleClick = false;
  15252. this._doubleClick = false;
  15253. this._hasSwiped = false;
  15254. this._ignore = false;
  15255. }
  15256. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15257. get: function () {
  15258. return this._singleClick;
  15259. },
  15260. set: function (b) {
  15261. this._singleClick = b;
  15262. },
  15263. enumerable: true,
  15264. configurable: true
  15265. });
  15266. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15267. get: function () {
  15268. return this._doubleClick;
  15269. },
  15270. set: function (b) {
  15271. this._doubleClick = b;
  15272. },
  15273. enumerable: true,
  15274. configurable: true
  15275. });
  15276. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15277. get: function () {
  15278. return this._hasSwiped;
  15279. },
  15280. set: function (b) {
  15281. this._hasSwiped = b;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15287. get: function () {
  15288. return this._ignore;
  15289. },
  15290. set: function (b) {
  15291. this._ignore = b;
  15292. },
  15293. enumerable: true,
  15294. configurable: true
  15295. });
  15296. return ClickInfo;
  15297. }());
  15298. var PointerEventTypes = (function () {
  15299. function PointerEventTypes() {
  15300. }
  15301. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15302. get: function () {
  15303. return PointerEventTypes._POINTERDOWN;
  15304. },
  15305. enumerable: true,
  15306. configurable: true
  15307. });
  15308. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15309. get: function () {
  15310. return PointerEventTypes._POINTERUP;
  15311. },
  15312. enumerable: true,
  15313. configurable: true
  15314. });
  15315. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15316. get: function () {
  15317. return PointerEventTypes._POINTERMOVE;
  15318. },
  15319. enumerable: true,
  15320. configurable: true
  15321. });
  15322. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15323. get: function () {
  15324. return PointerEventTypes._POINTERWHEEL;
  15325. },
  15326. enumerable: true,
  15327. configurable: true
  15328. });
  15329. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15330. get: function () {
  15331. return PointerEventTypes._POINTERPICK;
  15332. },
  15333. enumerable: true,
  15334. configurable: true
  15335. });
  15336. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15337. get: function () {
  15338. return PointerEventTypes._POINTERTAP;
  15339. },
  15340. enumerable: true,
  15341. configurable: true
  15342. });
  15343. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15344. get: function () {
  15345. return PointerEventTypes._POINTERDOUBLETAP;
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. return PointerEventTypes;
  15351. }());
  15352. PointerEventTypes._POINTERDOWN = 0x01;
  15353. PointerEventTypes._POINTERUP = 0x02;
  15354. PointerEventTypes._POINTERMOVE = 0x04;
  15355. PointerEventTypes._POINTERWHEEL = 0x08;
  15356. PointerEventTypes._POINTERPICK = 0x10;
  15357. PointerEventTypes._POINTERTAP = 0x20;
  15358. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15359. BABYLON.PointerEventTypes = PointerEventTypes;
  15360. var PointerInfoBase = (function () {
  15361. function PointerInfoBase(type, event) {
  15362. this.type = type;
  15363. this.event = event;
  15364. }
  15365. return PointerInfoBase;
  15366. }());
  15367. BABYLON.PointerInfoBase = PointerInfoBase;
  15368. /**
  15369. * This class is used to store pointer related info for the onPrePointerObservable event.
  15370. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15371. */
  15372. var PointerInfoPre = (function (_super) {
  15373. __extends(PointerInfoPre, _super);
  15374. function PointerInfoPre(type, event, localX, localY) {
  15375. var _this = _super.call(this, type, event) || this;
  15376. _this.skipOnPointerObservable = false;
  15377. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15378. return _this;
  15379. }
  15380. return PointerInfoPre;
  15381. }(PointerInfoBase));
  15382. BABYLON.PointerInfoPre = PointerInfoPre;
  15383. /**
  15384. * This type contains all the data related to a pointer event in Babylon.js.
  15385. * 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.
  15386. */
  15387. var PointerInfo = (function (_super) {
  15388. __extends(PointerInfo, _super);
  15389. function PointerInfo(type, event, pickInfo) {
  15390. var _this = _super.call(this, type, event) || this;
  15391. _this.pickInfo = pickInfo;
  15392. return _this;
  15393. }
  15394. return PointerInfo;
  15395. }(PointerInfoBase));
  15396. BABYLON.PointerInfo = PointerInfo;
  15397. /**
  15398. * This class is used by the onRenderingGroupObservable
  15399. */
  15400. var RenderingGroupInfo = (function () {
  15401. function RenderingGroupInfo() {
  15402. }
  15403. return RenderingGroupInfo;
  15404. }());
  15405. /**
  15406. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15407. * This stage will be fired no matter what
  15408. */
  15409. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15410. /**
  15411. * Called before opaque object are rendered.
  15412. * This stage will be fired only if there's 3D Opaque content to render
  15413. */
  15414. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15415. /**
  15416. * Called after the opaque objects are rendered and before the transparent ones
  15417. * This stage will be fired only if there's 3D transparent content to render
  15418. */
  15419. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15420. /**
  15421. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15422. * This stage will be fired no matter what
  15423. */
  15424. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15425. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15426. /**
  15427. * Represents a scene to be rendered by the engine.
  15428. * @see http://doc.babylonjs.com/page.php?p=21911
  15429. */
  15430. var Scene = (function () {
  15431. /**
  15432. * @constructor
  15433. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15434. */
  15435. function Scene(engine) {
  15436. // Members
  15437. this.autoClear = true;
  15438. this.autoClearDepthAndStencil = true;
  15439. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15440. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15441. this.forceWireframe = false;
  15442. this._forcePointsCloud = false;
  15443. this.forceShowBoundingBoxes = false;
  15444. this.animationsEnabled = true;
  15445. this.constantlyUpdateMeshUnderPointer = false;
  15446. this.hoverCursor = "pointer";
  15447. // Metadata
  15448. this.metadata = null;
  15449. // Events
  15450. /**
  15451. * An event triggered when the scene is disposed.
  15452. * @type {BABYLON.Observable}
  15453. */
  15454. this.onDisposeObservable = new BABYLON.Observable();
  15455. /**
  15456. * An event triggered before rendering the scene
  15457. * @type {BABYLON.Observable}
  15458. */
  15459. this.onBeforeRenderObservable = new BABYLON.Observable();
  15460. /**
  15461. * An event triggered after rendering the scene
  15462. * @type {BABYLON.Observable}
  15463. */
  15464. this.onAfterRenderObservable = new BABYLON.Observable();
  15465. /**
  15466. * An event triggered when the scene is ready
  15467. * @type {BABYLON.Observable}
  15468. */
  15469. this.onReadyObservable = new BABYLON.Observable();
  15470. /**
  15471. * An event triggered before rendering a camera
  15472. * @type {BABYLON.Observable}
  15473. */
  15474. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15475. /**
  15476. * An event triggered after rendering a camera
  15477. * @type {BABYLON.Observable}
  15478. */
  15479. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15480. /**
  15481. * An event triggered when a camera is created
  15482. * @type {BABYLON.Observable}
  15483. */
  15484. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15485. /**
  15486. * An event triggered when a camera is removed
  15487. * @type {BABYLON.Observable}
  15488. */
  15489. this.onCameraRemovedObservable = new BABYLON.Observable();
  15490. /**
  15491. * An event triggered when a light is created
  15492. * @type {BABYLON.Observable}
  15493. */
  15494. this.onNewLightAddedObservable = new BABYLON.Observable();
  15495. /**
  15496. * An event triggered when a light is removed
  15497. * @type {BABYLON.Observable}
  15498. */
  15499. this.onLightRemovedObservable = new BABYLON.Observable();
  15500. /**
  15501. * An event triggered when a geometry is created
  15502. * @type {BABYLON.Observable}
  15503. */
  15504. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15505. /**
  15506. * An event triggered when a geometry is removed
  15507. * @type {BABYLON.Observable}
  15508. */
  15509. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15510. /**
  15511. * An event triggered when a mesh is created
  15512. * @type {BABYLON.Observable}
  15513. */
  15514. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15515. /**
  15516. * An event triggered when a mesh is removed
  15517. * @type {BABYLON.Observable}
  15518. */
  15519. this.onMeshRemovedObservable = new BABYLON.Observable();
  15520. /**
  15521. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15522. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15523. * 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)
  15524. */
  15525. this.onRenderingGroupObservable = new BABYLON.Observable();
  15526. // Animations
  15527. this.animations = [];
  15528. /**
  15529. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  15530. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15531. */
  15532. this.onPrePointerObservable = new BABYLON.Observable();
  15533. /**
  15534. * Observable event triggered each time an input event is received from the rendering canvas
  15535. */
  15536. this.onPointerObservable = new BABYLON.Observable();
  15537. this._meshPickProceed = false;
  15538. this._previousHasSwiped = false;
  15539. this._currentPickResult = null;
  15540. this._previousPickResult = null;
  15541. this._isButtonPressed = false;
  15542. this._doubleClickOccured = false;
  15543. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  15544. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15545. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15546. this._startingPointerTime = 0;
  15547. this._previousStartingPointerTime = 0;
  15548. // Coordinate system
  15549. /**
  15550. * use right-handed coordinate system on this scene.
  15551. * @type {boolean}
  15552. */
  15553. this._useRightHandedSystem = false;
  15554. // Fog
  15555. /**
  15556. * is fog enabled on this scene.
  15557. * @type {boolean}
  15558. */
  15559. this._fogEnabled = true;
  15560. this._fogMode = Scene.FOGMODE_NONE;
  15561. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15562. this.fogDensity = 0.1;
  15563. this.fogStart = 0;
  15564. this.fogEnd = 1000.0;
  15565. // Lights
  15566. /**
  15567. * is shadow enabled on this scene.
  15568. * @type {boolean}
  15569. */
  15570. this._shadowsEnabled = true;
  15571. /**
  15572. * is light enabled on this scene.
  15573. * @type {boolean}
  15574. */
  15575. this._lightsEnabled = true;
  15576. /**
  15577. * All of the lights added to this scene.
  15578. * @see BABYLON.Light
  15579. * @type {BABYLON.Light[]}
  15580. */
  15581. this.lights = new Array();
  15582. // Cameras
  15583. /**
  15584. * All of the cameras added to this scene.
  15585. * @see BABYLON.Camera
  15586. * @type {BABYLON.Camera[]}
  15587. */
  15588. this.cameras = new Array();
  15589. this.activeCameras = new Array();
  15590. // Meshes
  15591. /**
  15592. * All of the (abstract) meshes added to this scene.
  15593. * @see BABYLON.AbstractMesh
  15594. * @type {BABYLON.AbstractMesh[]}
  15595. */
  15596. this.meshes = new Array();
  15597. // Geometries
  15598. this._geometries = new Array();
  15599. this.materials = new Array();
  15600. this.multiMaterials = new Array();
  15601. // Textures
  15602. this._texturesEnabled = true;
  15603. this.textures = new Array();
  15604. // Particles
  15605. this.particlesEnabled = true;
  15606. this.particleSystems = new Array();
  15607. // Sprites
  15608. this.spritesEnabled = true;
  15609. this.spriteManagers = new Array();
  15610. // Layers
  15611. this.layers = new Array();
  15612. this.highlightLayers = new Array();
  15613. // Skeletons
  15614. this._skeletonsEnabled = true;
  15615. this.skeletons = new Array();
  15616. // Morph targets
  15617. this.morphTargetManagers = new Array();
  15618. // Lens flares
  15619. this.lensFlaresEnabled = true;
  15620. this.lensFlareSystems = new Array();
  15621. // Collisions
  15622. this.collisionsEnabled = true;
  15623. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15624. // Postprocesses
  15625. this.postProcessesEnabled = true;
  15626. // Customs render targets
  15627. this.renderTargetsEnabled = true;
  15628. this.dumpNextRenderTargets = false;
  15629. this.customRenderTargets = new Array();
  15630. // Imported meshes
  15631. this.importedMeshesFiles = new Array();
  15632. // Probes
  15633. this.probesEnabled = true;
  15634. this.reflectionProbes = new Array();
  15635. this._actionManagers = new Array();
  15636. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15637. // Procedural textures
  15638. this.proceduralTexturesEnabled = true;
  15639. this._proceduralTextures = new Array();
  15640. this.soundTracks = new Array();
  15641. this._audioEnabled = true;
  15642. this._headphone = false;
  15643. // Performance counters
  15644. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15645. this._totalLightsCounter = new BABYLON.PerfCounter();
  15646. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15647. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15648. this._totalVertices = new BABYLON.PerfCounter();
  15649. this._activeIndices = new BABYLON.PerfCounter();
  15650. this._activeParticles = new BABYLON.PerfCounter();
  15651. this._lastFrameDuration = new BABYLON.PerfCounter();
  15652. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15653. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15654. this._particlesDuration = new BABYLON.PerfCounter();
  15655. this._renderDuration = new BABYLON.PerfCounter();
  15656. this._spritesDuration = new BABYLON.PerfCounter();
  15657. this._activeBones = new BABYLON.PerfCounter();
  15658. this._animationTime = 0;
  15659. this.animationTimeScale = 1;
  15660. this._renderId = 0;
  15661. this._executeWhenReadyTimeoutId = -1;
  15662. this._intermediateRendering = false;
  15663. this._viewUpdateFlag = -1;
  15664. this._projectionUpdateFlag = -1;
  15665. this._toBeDisposed = new BABYLON.SmartArray(256);
  15666. this._pendingData = []; //ANY
  15667. this._activeMeshes = new BABYLON.SmartArray(256);
  15668. this._processedMaterials = new BABYLON.SmartArray(256);
  15669. this._renderTargets = new BABYLON.SmartArray(256);
  15670. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15671. this._activeSkeletons = new BABYLON.SmartArray(32);
  15672. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15673. this._activeAnimatables = new Array();
  15674. this._transformMatrix = BABYLON.Matrix.Zero();
  15675. this.requireLightSorting = false;
  15676. this._uniqueIdCounter = 0;
  15677. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15678. this._engine.scenes.push(this);
  15679. this._uid = null;
  15680. this._renderingManager = new BABYLON.RenderingManager(this);
  15681. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15682. if (BABYLON.OutlineRenderer) {
  15683. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15684. }
  15685. this.attachControl();
  15686. if (BABYLON.SoundTrack) {
  15687. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15688. }
  15689. //simplification queue
  15690. if (BABYLON.SimplificationQueue) {
  15691. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15692. }
  15693. //collision coordinator initialization. For now legacy per default.
  15694. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15695. // Uniform Buffer
  15696. this._createUbo();
  15697. // Default Image processing definition.
  15698. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15699. }
  15700. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15701. get: function () {
  15702. return Scene._FOGMODE_NONE;
  15703. },
  15704. enumerable: true,
  15705. configurable: true
  15706. });
  15707. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15708. get: function () {
  15709. return Scene._FOGMODE_EXP;
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15715. get: function () {
  15716. return Scene._FOGMODE_EXP2;
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15722. get: function () {
  15723. return Scene._FOGMODE_LINEAR;
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15729. /**
  15730. * Texture used in all pbr material as the reflection texture.
  15731. * As in the majority of the scene they are the same (exception for multi room and so on),
  15732. * this is easier to reference from here than from all the materials.
  15733. */
  15734. get: function () {
  15735. return this._environmentTexture;
  15736. },
  15737. /**
  15738. * Texture used in all pbr material as the reflection texture.
  15739. * As in the majority of the scene they are the same (exception for multi room and so on),
  15740. * this is easier to set here than in all the materials.
  15741. */
  15742. set: function (value) {
  15743. this._environmentTexture = value;
  15744. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15745. },
  15746. enumerable: true,
  15747. configurable: true
  15748. });
  15749. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15750. /**
  15751. * Default image processing configuration used either in the rendering
  15752. * Forward main pass or through the imageProcessingPostProcess if present.
  15753. * As in the majority of the scene they are the same (exception for multi camera),
  15754. * this is easier to reference from here than from all the materials and post process.
  15755. *
  15756. * No setter as we it is a shared configuration, you can set the values instead.
  15757. */
  15758. get: function () {
  15759. return this._imageProcessingConfiguration;
  15760. },
  15761. enumerable: true,
  15762. configurable: true
  15763. });
  15764. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15765. get: function () {
  15766. return this._forcePointsCloud;
  15767. },
  15768. set: function (value) {
  15769. if (this._forcePointsCloud === value) {
  15770. return;
  15771. }
  15772. this._forcePointsCloud = value;
  15773. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15774. },
  15775. enumerable: true,
  15776. configurable: true
  15777. });
  15778. Object.defineProperty(Scene.prototype, "onDispose", {
  15779. set: function (callback) {
  15780. if (this._onDisposeObserver) {
  15781. this.onDisposeObservable.remove(this._onDisposeObserver);
  15782. }
  15783. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15784. },
  15785. enumerable: true,
  15786. configurable: true
  15787. });
  15788. Object.defineProperty(Scene.prototype, "beforeRender", {
  15789. set: function (callback) {
  15790. if (this._onBeforeRenderObserver) {
  15791. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15792. }
  15793. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. Object.defineProperty(Scene.prototype, "afterRender", {
  15799. set: function (callback) {
  15800. if (this._onAfterRenderObserver) {
  15801. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15802. }
  15803. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15809. set: function (callback) {
  15810. if (this._onBeforeCameraRenderObserver) {
  15811. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15812. }
  15813. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15814. },
  15815. enumerable: true,
  15816. configurable: true
  15817. });
  15818. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15819. set: function (callback) {
  15820. if (this._onAfterCameraRenderObserver) {
  15821. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15822. }
  15823. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15824. },
  15825. enumerable: true,
  15826. configurable: true
  15827. });
  15828. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15829. get: function () {
  15830. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15836. get: function () {
  15837. return this._useRightHandedSystem;
  15838. },
  15839. set: function (value) {
  15840. if (this._useRightHandedSystem === value) {
  15841. return;
  15842. }
  15843. this._useRightHandedSystem = value;
  15844. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15845. },
  15846. enumerable: true,
  15847. configurable: true
  15848. });
  15849. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15850. get: function () {
  15851. return this._fogEnabled;
  15852. },
  15853. set: function (value) {
  15854. if (this._fogEnabled === value) {
  15855. return;
  15856. }
  15857. this._fogEnabled = value;
  15858. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15859. },
  15860. enumerable: true,
  15861. configurable: true
  15862. });
  15863. Object.defineProperty(Scene.prototype, "fogMode", {
  15864. get: function () {
  15865. return this._fogMode;
  15866. },
  15867. set: function (value) {
  15868. if (this._fogMode === value) {
  15869. return;
  15870. }
  15871. this._fogMode = value;
  15872. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15873. },
  15874. enumerable: true,
  15875. configurable: true
  15876. });
  15877. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15878. get: function () {
  15879. return this._shadowsEnabled;
  15880. },
  15881. set: function (value) {
  15882. if (this._shadowsEnabled === value) {
  15883. return;
  15884. }
  15885. this._shadowsEnabled = value;
  15886. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15887. },
  15888. enumerable: true,
  15889. configurable: true
  15890. });
  15891. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15892. get: function () {
  15893. return this._lightsEnabled;
  15894. },
  15895. set: function (value) {
  15896. if (this._lightsEnabled === value) {
  15897. return;
  15898. }
  15899. this._lightsEnabled = value;
  15900. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15901. },
  15902. enumerable: true,
  15903. configurable: true
  15904. });
  15905. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15906. get: function () {
  15907. if (!this._defaultMaterial) {
  15908. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15909. }
  15910. return this._defaultMaterial;
  15911. },
  15912. set: function (value) {
  15913. this._defaultMaterial = value;
  15914. },
  15915. enumerable: true,
  15916. configurable: true
  15917. });
  15918. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15919. get: function () {
  15920. return this._texturesEnabled;
  15921. },
  15922. set: function (value) {
  15923. if (this._texturesEnabled === value) {
  15924. return;
  15925. }
  15926. this._texturesEnabled = value;
  15927. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15933. get: function () {
  15934. return this._skeletonsEnabled;
  15935. },
  15936. set: function (value) {
  15937. if (this._skeletonsEnabled === value) {
  15938. return;
  15939. }
  15940. this._skeletonsEnabled = value;
  15941. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15942. },
  15943. enumerable: true,
  15944. configurable: true
  15945. });
  15946. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15947. get: function () {
  15948. if (!this._postProcessRenderPipelineManager) {
  15949. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15950. }
  15951. return this._postProcessRenderPipelineManager;
  15952. },
  15953. enumerable: true,
  15954. configurable: true
  15955. });
  15956. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15957. get: function () {
  15958. return this._frustumPlanes;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(Scene.prototype, "debugLayer", {
  15964. // Properties
  15965. get: function () {
  15966. if (!this._debugLayer) {
  15967. this._debugLayer = new BABYLON.DebugLayer(this);
  15968. }
  15969. return this._debugLayer;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15975. get: function () {
  15976. return this._workerCollisions;
  15977. },
  15978. set: function (enabled) {
  15979. if (!BABYLON.CollisionCoordinatorLegacy) {
  15980. return;
  15981. }
  15982. enabled = (enabled && !!Worker);
  15983. this._workerCollisions = enabled;
  15984. if (this.collisionCoordinator) {
  15985. this.collisionCoordinator.destroy();
  15986. }
  15987. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15988. this.collisionCoordinator.init(this);
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15994. get: function () {
  15995. return this._selectionOctree;
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16001. /**
  16002. * The mesh that is currently under the pointer.
  16003. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16004. */
  16005. get: function () {
  16006. return this._pointerOverMesh;
  16007. },
  16008. enumerable: true,
  16009. configurable: true
  16010. });
  16011. Object.defineProperty(Scene.prototype, "pointerX", {
  16012. /**
  16013. * Current on-screen X position of the pointer
  16014. * @return {number} X position of the pointer
  16015. */
  16016. get: function () {
  16017. return this._pointerX;
  16018. },
  16019. enumerable: true,
  16020. configurable: true
  16021. });
  16022. Object.defineProperty(Scene.prototype, "pointerY", {
  16023. /**
  16024. * Current on-screen Y position of the pointer
  16025. * @return {number} Y position of the pointer
  16026. */
  16027. get: function () {
  16028. return this._pointerY;
  16029. },
  16030. enumerable: true,
  16031. configurable: true
  16032. });
  16033. Scene.prototype.getCachedMaterial = function () {
  16034. return this._cachedMaterial;
  16035. };
  16036. Scene.prototype.getCachedEffect = function () {
  16037. return this._cachedEffect;
  16038. };
  16039. Scene.prototype.getCachedVisibility = function () {
  16040. return this._cachedVisibility;
  16041. };
  16042. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16043. if (visibility === void 0) { visibility = 0; }
  16044. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16045. };
  16046. Scene.prototype.getBoundingBoxRenderer = function () {
  16047. if (!this._boundingBoxRenderer) {
  16048. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16049. }
  16050. return this._boundingBoxRenderer;
  16051. };
  16052. Scene.prototype.getOutlineRenderer = function () {
  16053. return this._outlineRenderer;
  16054. };
  16055. Scene.prototype.getEngine = function () {
  16056. return this._engine;
  16057. };
  16058. Scene.prototype.getTotalVertices = function () {
  16059. return this._totalVertices.current;
  16060. };
  16061. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16062. get: function () {
  16063. return this._totalVertices;
  16064. },
  16065. enumerable: true,
  16066. configurable: true
  16067. });
  16068. Scene.prototype.getActiveIndices = function () {
  16069. return this._activeIndices.current;
  16070. };
  16071. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16072. get: function () {
  16073. return this._activeIndices;
  16074. },
  16075. enumerable: true,
  16076. configurable: true
  16077. });
  16078. Scene.prototype.getActiveParticles = function () {
  16079. return this._activeParticles.current;
  16080. };
  16081. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16082. get: function () {
  16083. return this._activeParticles;
  16084. },
  16085. enumerable: true,
  16086. configurable: true
  16087. });
  16088. Scene.prototype.getActiveBones = function () {
  16089. return this._activeBones.current;
  16090. };
  16091. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16092. get: function () {
  16093. return this._activeBones;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. // Stats
  16099. Scene.prototype.getLastFrameDuration = function () {
  16100. return this._lastFrameDuration.current;
  16101. };
  16102. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16103. get: function () {
  16104. return this._lastFrameDuration;
  16105. },
  16106. enumerable: true,
  16107. configurable: true
  16108. });
  16109. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16110. return this._evaluateActiveMeshesDuration.current;
  16111. };
  16112. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16113. get: function () {
  16114. return this._evaluateActiveMeshesDuration;
  16115. },
  16116. enumerable: true,
  16117. configurable: true
  16118. });
  16119. Scene.prototype.getActiveMeshes = function () {
  16120. return this._activeMeshes;
  16121. };
  16122. Scene.prototype.getRenderTargetsDuration = function () {
  16123. return this._renderTargetsDuration.current;
  16124. };
  16125. Scene.prototype.getRenderDuration = function () {
  16126. return this._renderDuration.current;
  16127. };
  16128. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16129. get: function () {
  16130. return this._renderDuration;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Scene.prototype.getParticlesDuration = function () {
  16136. return this._particlesDuration.current;
  16137. };
  16138. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16139. get: function () {
  16140. return this._particlesDuration;
  16141. },
  16142. enumerable: true,
  16143. configurable: true
  16144. });
  16145. Scene.prototype.getSpritesDuration = function () {
  16146. return this._spritesDuration.current;
  16147. };
  16148. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16149. get: function () {
  16150. return this._spritesDuration;
  16151. },
  16152. enumerable: true,
  16153. configurable: true
  16154. });
  16155. Scene.prototype.getAnimationRatio = function () {
  16156. return this._animationRatio;
  16157. };
  16158. Scene.prototype.getRenderId = function () {
  16159. return this._renderId;
  16160. };
  16161. Scene.prototype.incrementRenderId = function () {
  16162. this._renderId++;
  16163. };
  16164. Scene.prototype._updatePointerPosition = function (evt) {
  16165. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16166. this._pointerX = evt.clientX - canvasRect.left;
  16167. this._pointerY = evt.clientY - canvasRect.top;
  16168. this._unTranslatedPointerX = this._pointerX;
  16169. this._unTranslatedPointerY = this._pointerY;
  16170. if (this.cameraToUseForPointers) {
  16171. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16172. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16173. }
  16174. };
  16175. Scene.prototype._createUbo = function () {
  16176. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16177. this._sceneUbo.addUniform("viewProjection", 16);
  16178. this._sceneUbo.addUniform("view", 16);
  16179. };
  16180. // Pointers handling
  16181. /**
  16182. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16183. * @param attachUp defines if you want to attach events to pointerup
  16184. * @param attachDown defines if you want to attach events to pointerdown
  16185. * @param attachMove defines if you want to attach events to pointermove
  16186. */
  16187. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16188. var _this = this;
  16189. if (attachUp === void 0) { attachUp = true; }
  16190. if (attachDown === void 0) { attachDown = true; }
  16191. if (attachMove === void 0) { attachMove = true; }
  16192. this._initActionManager = function (act, clickInfo) {
  16193. if (!_this._meshPickProceed) {
  16194. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16195. _this._currentPickResult = pickResult;
  16196. if (pickResult) {
  16197. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16198. }
  16199. _this._meshPickProceed = true;
  16200. }
  16201. return act;
  16202. };
  16203. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16204. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16205. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16206. btn !== _this._previousButtonPressed) {
  16207. _this._doubleClickOccured = false;
  16208. clickInfo.singleClick = true;
  16209. clickInfo.ignore = false;
  16210. cb(clickInfo, _this._currentPickResult);
  16211. }
  16212. };
  16213. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16214. var clickInfo = new ClickInfo();
  16215. _this._currentPickResult = null;
  16216. var act;
  16217. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16218. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16219. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16220. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16221. act = _this._initActionManager(act, clickInfo);
  16222. if (act)
  16223. checkPicking = act.hasPickTriggers;
  16224. }
  16225. if (checkPicking) {
  16226. var btn = evt.button;
  16227. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16228. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16229. if (!clickInfo.hasSwiped) {
  16230. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16231. if (!checkSingleClickImmediately) {
  16232. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16233. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16234. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16235. act = _this._initActionManager(act, clickInfo);
  16236. if (act)
  16237. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16238. }
  16239. }
  16240. if (checkSingleClickImmediately) {
  16241. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16242. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16243. btn !== _this._previousButtonPressed) {
  16244. clickInfo.singleClick = true;
  16245. cb(clickInfo, _this._currentPickResult);
  16246. }
  16247. }
  16248. else {
  16249. // wait that no double click has been raised during the double click delay
  16250. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16251. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16252. }
  16253. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16254. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16255. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16256. act = _this._initActionManager(act, clickInfo);
  16257. if (act)
  16258. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16259. }
  16260. if (checkDoubleClick) {
  16261. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16262. if (btn === _this._previousButtonPressed &&
  16263. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16264. !_this._doubleClickOccured) {
  16265. // pointer has not moved for 2 clicks, it's a double click
  16266. if (!clickInfo.hasSwiped &&
  16267. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16268. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16269. _this._previousStartingPointerTime = 0;
  16270. _this._doubleClickOccured = true;
  16271. clickInfo.doubleClick = true;
  16272. clickInfo.ignore = false;
  16273. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16274. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16275. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16276. cb(clickInfo, _this._currentPickResult);
  16277. }
  16278. else {
  16279. _this._doubleClickOccured = false;
  16280. _this._previousStartingPointerTime = _this._startingPointerTime;
  16281. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16282. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16283. _this._previousButtonPressed = btn;
  16284. _this._previousHasSwiped = clickInfo.hasSwiped;
  16285. if (Scene.ExclusiveDoubleClickMode) {
  16286. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16287. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16288. }
  16289. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16290. cb(clickInfo, _this._previousPickResult);
  16291. }
  16292. else {
  16293. cb(clickInfo, _this._currentPickResult);
  16294. }
  16295. }
  16296. }
  16297. else {
  16298. _this._doubleClickOccured = false;
  16299. _this._previousStartingPointerTime = _this._startingPointerTime;
  16300. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16301. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16302. _this._previousButtonPressed = btn;
  16303. _this._previousHasSwiped = clickInfo.hasSwiped;
  16304. }
  16305. }
  16306. }
  16307. }
  16308. clickInfo.ignore = true;
  16309. cb(clickInfo, _this._currentPickResult);
  16310. };
  16311. var spritePredicate = function (sprite) {
  16312. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16313. };
  16314. this._onPointerMove = function (evt) {
  16315. _this._updatePointerPosition(evt);
  16316. // PreObservable support
  16317. if (_this.onPrePointerObservable.hasObservers()) {
  16318. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16319. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16320. _this.onPrePointerObservable.notifyObservers(pi, type);
  16321. if (pi.skipOnPointerObservable) {
  16322. return;
  16323. }
  16324. }
  16325. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16326. return;
  16327. }
  16328. var canvas = _this._engine.getRenderingCanvas();
  16329. if (!_this.pointerMovePredicate) {
  16330. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16331. }
  16332. // Meshes
  16333. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16334. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16335. _this.setPointerOverSprite(null);
  16336. _this.setPointerOverMesh(pickResult.pickedMesh);
  16337. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16338. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16339. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16340. }
  16341. else {
  16342. canvas.style.cursor = _this.hoverCursor;
  16343. }
  16344. }
  16345. else {
  16346. canvas.style.cursor = "";
  16347. }
  16348. }
  16349. else {
  16350. _this.setPointerOverMesh(null);
  16351. // Sprites
  16352. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16353. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16354. _this.setPointerOverSprite(pickResult.pickedSprite);
  16355. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16356. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16357. }
  16358. else {
  16359. canvas.style.cursor = _this.hoverCursor;
  16360. }
  16361. }
  16362. else {
  16363. _this.setPointerOverSprite(null);
  16364. // Restore pointer
  16365. canvas.style.cursor = "";
  16366. }
  16367. }
  16368. if (_this.onPointerMove) {
  16369. _this.onPointerMove(evt, pickResult);
  16370. }
  16371. if (_this.onPointerObservable.hasObservers()) {
  16372. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16373. var pi = new PointerInfo(type, evt, pickResult);
  16374. _this.onPointerObservable.notifyObservers(pi, type);
  16375. }
  16376. };
  16377. this._onPointerDown = function (evt) {
  16378. _this._isButtonPressed = true;
  16379. _this._pickedDownMesh = null;
  16380. _this._meshPickProceed = false;
  16381. _this._updatePointerPosition(evt);
  16382. // PreObservable support
  16383. if (_this.onPrePointerObservable.hasObservers()) {
  16384. var type = PointerEventTypes.POINTERDOWN;
  16385. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16386. _this.onPrePointerObservable.notifyObservers(pi, type);
  16387. if (pi.skipOnPointerObservable) {
  16388. return;
  16389. }
  16390. }
  16391. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16392. return;
  16393. }
  16394. _this._startingPointerPosition.x = _this._pointerX;
  16395. _this._startingPointerPosition.y = _this._pointerY;
  16396. _this._startingPointerTime = new Date().getTime();
  16397. if (!_this.pointerDownPredicate) {
  16398. _this.pointerDownPredicate = function (mesh) {
  16399. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16400. };
  16401. }
  16402. // Meshes
  16403. _this._pickedDownMesh = null;
  16404. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16405. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16406. _this._pickedDownMesh = pickResult.pickedMesh;
  16407. var actionManager = pickResult.pickedMesh.actionManager;
  16408. if (actionManager) {
  16409. if (actionManager.hasPickTriggers) {
  16410. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16411. switch (evt.button) {
  16412. case 0:
  16413. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16414. break;
  16415. case 1:
  16416. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16417. break;
  16418. case 2:
  16419. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16420. break;
  16421. }
  16422. }
  16423. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16424. window.setTimeout((function () {
  16425. var _this = this;
  16426. 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);
  16427. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16428. if (this._isButtonPressed &&
  16429. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16430. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16431. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16432. this._startingPointerTime = 0;
  16433. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16434. }
  16435. }
  16436. }).bind(_this), Scene.LongPressDelay);
  16437. }
  16438. }
  16439. }
  16440. if (_this.onPointerDown) {
  16441. _this.onPointerDown(evt, pickResult);
  16442. }
  16443. if (_this.onPointerObservable.hasObservers()) {
  16444. var type = PointerEventTypes.POINTERDOWN;
  16445. var pi = new PointerInfo(type, evt, pickResult);
  16446. _this.onPointerObservable.notifyObservers(pi, type);
  16447. }
  16448. // Sprites
  16449. _this._pickedDownSprite = null;
  16450. if (_this.spriteManagers.length > 0) {
  16451. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16452. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16453. if (pickResult.pickedSprite.actionManager) {
  16454. _this._pickedDownSprite = pickResult.pickedSprite;
  16455. switch (evt.button) {
  16456. case 0:
  16457. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16458. break;
  16459. case 1:
  16460. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16461. break;
  16462. case 2:
  16463. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16464. break;
  16465. }
  16466. if (pickResult.pickedSprite.actionManager) {
  16467. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16468. }
  16469. }
  16470. }
  16471. }
  16472. };
  16473. this._onPointerUp = function (evt) {
  16474. _this._isButtonPressed = false;
  16475. _this._pickedUpMesh = null;
  16476. _this._meshPickProceed = false;
  16477. _this._updatePointerPosition(evt);
  16478. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16479. // PreObservable support
  16480. if (this.onPrePointerObservable.hasObservers()) {
  16481. if (!clickInfo.ignore) {
  16482. if (!clickInfo.hasSwiped) {
  16483. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16484. var type = PointerEventTypes.POINTERTAP;
  16485. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16486. this.onPrePointerObservable.notifyObservers(pi, type);
  16487. if (pi.skipOnPointerObservable) {
  16488. return;
  16489. }
  16490. }
  16491. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16492. var type = PointerEventTypes.POINTERDOUBLETAP;
  16493. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16494. this.onPrePointerObservable.notifyObservers(pi, type);
  16495. if (pi.skipOnPointerObservable) {
  16496. return;
  16497. }
  16498. }
  16499. }
  16500. }
  16501. else {
  16502. var type = PointerEventTypes.POINTERUP;
  16503. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16504. this.onPrePointerObservable.notifyObservers(pi, type);
  16505. if (pi.skipOnPointerObservable) {
  16506. return;
  16507. }
  16508. }
  16509. }
  16510. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16511. return;
  16512. }
  16513. if (!this.pointerUpPredicate) {
  16514. this.pointerUpPredicate = function (mesh) {
  16515. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16516. };
  16517. }
  16518. // Meshes
  16519. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16520. this._initActionManager(null, clickInfo);
  16521. }
  16522. if (!pickResult) {
  16523. pickResult = this._currentPickResult;
  16524. }
  16525. if (pickResult && pickResult && pickResult.pickedMesh) {
  16526. this._pickedUpMesh = pickResult.pickedMesh;
  16527. if (this._pickedDownMesh === this._pickedUpMesh) {
  16528. if (this.onPointerPick) {
  16529. this.onPointerPick(evt, pickResult);
  16530. }
  16531. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16532. var type = PointerEventTypes.POINTERPICK;
  16533. var pi = new PointerInfo(type, evt, pickResult);
  16534. this.onPointerObservable.notifyObservers(pi, type);
  16535. }
  16536. }
  16537. if (pickResult.pickedMesh.actionManager) {
  16538. if (clickInfo.ignore) {
  16539. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16540. }
  16541. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16542. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16543. }
  16544. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16545. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16546. }
  16547. }
  16548. }
  16549. if (this._pickedDownMesh &&
  16550. this._pickedDownMesh.actionManager &&
  16551. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16552. this._pickedDownMesh !== this._pickedUpMesh) {
  16553. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16554. }
  16555. if (this.onPointerUp) {
  16556. this.onPointerUp(evt, pickResult);
  16557. }
  16558. if (this.onPointerObservable.hasObservers()) {
  16559. if (!clickInfo.ignore) {
  16560. if (!clickInfo.hasSwiped) {
  16561. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16562. var type = PointerEventTypes.POINTERTAP;
  16563. var pi = new PointerInfo(type, evt, pickResult);
  16564. this.onPointerObservable.notifyObservers(pi, type);
  16565. }
  16566. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16567. var type = PointerEventTypes.POINTERDOUBLETAP;
  16568. var pi = new PointerInfo(type, evt, pickResult);
  16569. this.onPointerObservable.notifyObservers(pi, type);
  16570. }
  16571. }
  16572. }
  16573. else {
  16574. var type = PointerEventTypes.POINTERUP;
  16575. var pi = new PointerInfo(type, evt, pickResult);
  16576. this.onPointerObservable.notifyObservers(pi, type);
  16577. }
  16578. }
  16579. // Sprites
  16580. if (this.spriteManagers.length > 0) {
  16581. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16582. if (pickResult.hit && pickResult.pickedSprite) {
  16583. if (pickResult.pickedSprite.actionManager) {
  16584. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16585. if (pickResult.pickedSprite.actionManager) {
  16586. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16587. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16588. }
  16589. }
  16590. }
  16591. }
  16592. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16593. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16594. }
  16595. }
  16596. this._previousPickResult = this._currentPickResult;
  16597. }).bind(_this));
  16598. };
  16599. this._onKeyDown = function (evt) {
  16600. if (_this.actionManager) {
  16601. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16602. }
  16603. };
  16604. this._onKeyUp = function (evt) {
  16605. if (_this.actionManager) {
  16606. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16607. }
  16608. };
  16609. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16610. var canvas = this._engine.getRenderingCanvas();
  16611. if (attachMove) {
  16612. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16613. // Wheel
  16614. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16615. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16616. }
  16617. if (attachDown) {
  16618. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16619. }
  16620. if (attachUp) {
  16621. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16622. }
  16623. canvas.tabIndex = 1;
  16624. canvas.addEventListener("keydown", this._onKeyDown, false);
  16625. canvas.addEventListener("keyup", this._onKeyUp, false);
  16626. };
  16627. Scene.prototype.detachControl = function () {
  16628. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16629. var canvas = this._engine.getRenderingCanvas();
  16630. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16631. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16632. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16633. // Wheel
  16634. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16635. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16636. canvas.removeEventListener("keydown", this._onKeyDown);
  16637. canvas.removeEventListener("keyup", this._onKeyUp);
  16638. };
  16639. // Ready
  16640. Scene.prototype.isReady = function () {
  16641. if (this._pendingData.length > 0) {
  16642. return false;
  16643. }
  16644. var index;
  16645. // Geometries
  16646. for (index = 0; index < this._geometries.length; index++) {
  16647. var geometry = this._geometries[index];
  16648. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16649. return false;
  16650. }
  16651. }
  16652. // Meshes
  16653. for (index = 0; index < this.meshes.length; index++) {
  16654. var mesh = this.meshes[index];
  16655. if (!mesh.isEnabled()) {
  16656. continue;
  16657. }
  16658. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16659. continue;
  16660. }
  16661. if (!mesh.isReady()) {
  16662. return false;
  16663. }
  16664. var mat = mesh.material;
  16665. if (mat) {
  16666. if (!mat.isReady(mesh)) {
  16667. return false;
  16668. }
  16669. }
  16670. }
  16671. return true;
  16672. };
  16673. Scene.prototype.resetCachedMaterial = function () {
  16674. this._cachedMaterial = null;
  16675. this._cachedEffect = null;
  16676. this._cachedVisibility = null;
  16677. };
  16678. Scene.prototype.registerBeforeRender = function (func) {
  16679. this.onBeforeRenderObservable.add(func);
  16680. };
  16681. Scene.prototype.unregisterBeforeRender = function (func) {
  16682. this.onBeforeRenderObservable.removeCallback(func);
  16683. };
  16684. Scene.prototype.registerAfterRender = function (func) {
  16685. this.onAfterRenderObservable.add(func);
  16686. };
  16687. Scene.prototype.unregisterAfterRender = function (func) {
  16688. this.onAfterRenderObservable.removeCallback(func);
  16689. };
  16690. Scene.prototype._addPendingData = function (data) {
  16691. this._pendingData.push(data);
  16692. };
  16693. Scene.prototype._removePendingData = function (data) {
  16694. var index = this._pendingData.indexOf(data);
  16695. if (index !== -1) {
  16696. this._pendingData.splice(index, 1);
  16697. }
  16698. };
  16699. Scene.prototype.getWaitingItemsCount = function () {
  16700. return this._pendingData.length;
  16701. };
  16702. /**
  16703. * Registers a function to be executed when the scene is ready.
  16704. * @param {Function} func - the function to be executed.
  16705. */
  16706. Scene.prototype.executeWhenReady = function (func) {
  16707. var _this = this;
  16708. this.onReadyObservable.add(func);
  16709. if (this._executeWhenReadyTimeoutId !== -1) {
  16710. return;
  16711. }
  16712. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16713. _this._checkIsReady();
  16714. }, 150);
  16715. };
  16716. Scene.prototype._checkIsReady = function () {
  16717. var _this = this;
  16718. if (this.isReady()) {
  16719. this.onReadyObservable.notifyObservers(this);
  16720. this.onReadyObservable.clear();
  16721. this._executeWhenReadyTimeoutId = -1;
  16722. return;
  16723. }
  16724. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16725. _this._checkIsReady();
  16726. }, 150);
  16727. };
  16728. // Animations
  16729. /**
  16730. * Will start the animation sequence of a given target
  16731. * @param target - the target
  16732. * @param {number} from - from which frame should animation start
  16733. * @param {number} to - till which frame should animation run.
  16734. * @param {boolean} [loop] - should the animation loop
  16735. * @param {number} [speedRatio] - the speed in which to run the animation
  16736. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16737. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16738. * @return {BABYLON.Animatable} the animatable object created for this animation
  16739. * @see BABYLON.Animatable
  16740. * @see http://doc.babylonjs.com/page.php?p=22081
  16741. */
  16742. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16743. if (speedRatio === void 0) { speedRatio = 1.0; }
  16744. if (from > to && speedRatio > 0) {
  16745. speedRatio *= -1;
  16746. }
  16747. this.stopAnimation(target);
  16748. if (!animatable) {
  16749. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16750. }
  16751. // Local animations
  16752. if (target.animations) {
  16753. animatable.appendAnimations(target, target.animations);
  16754. }
  16755. // Children animations
  16756. if (target.getAnimatables) {
  16757. var animatables = target.getAnimatables();
  16758. for (var index = 0; index < animatables.length; index++) {
  16759. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16760. }
  16761. }
  16762. animatable.reset();
  16763. return animatable;
  16764. };
  16765. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16766. if (speedRatio === undefined) {
  16767. speedRatio = 1.0;
  16768. }
  16769. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16770. return animatable;
  16771. };
  16772. Scene.prototype.getAnimatableByTarget = function (target) {
  16773. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16774. if (this._activeAnimatables[index].target === target) {
  16775. return this._activeAnimatables[index];
  16776. }
  16777. }
  16778. return null;
  16779. };
  16780. Object.defineProperty(Scene.prototype, "Animatables", {
  16781. get: function () {
  16782. return this._activeAnimatables;
  16783. },
  16784. enumerable: true,
  16785. configurable: true
  16786. });
  16787. /**
  16788. * Will stop the animation of the given target
  16789. * @param target - the target
  16790. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16791. * @see beginAnimation
  16792. */
  16793. Scene.prototype.stopAnimation = function (target, animationName) {
  16794. var animatable = this.getAnimatableByTarget(target);
  16795. if (animatable) {
  16796. animatable.stop(animationName);
  16797. }
  16798. };
  16799. Scene.prototype._animate = function () {
  16800. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16801. return;
  16802. }
  16803. // Getting time
  16804. var now = BABYLON.Tools.Now;
  16805. if (!this._animationTimeLast) {
  16806. if (this._pendingData.length > 0) {
  16807. return;
  16808. }
  16809. this._animationTimeLast = now;
  16810. }
  16811. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16812. this._animationTime += deltaTime;
  16813. this._animationTimeLast = now;
  16814. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16815. this._activeAnimatables[index]._animate(this._animationTime);
  16816. }
  16817. };
  16818. // Matrix
  16819. Scene.prototype.getViewMatrix = function () {
  16820. return this._viewMatrix;
  16821. };
  16822. Scene.prototype.getProjectionMatrix = function () {
  16823. return this._projectionMatrix;
  16824. };
  16825. Scene.prototype.getTransformMatrix = function () {
  16826. return this._transformMatrix;
  16827. };
  16828. Scene.prototype.setTransformMatrix = function (view, projection) {
  16829. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16830. return;
  16831. }
  16832. this._viewUpdateFlag = view.updateFlag;
  16833. this._projectionUpdateFlag = projection.updateFlag;
  16834. this._viewMatrix = view;
  16835. this._projectionMatrix = projection;
  16836. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16837. // Update frustum
  16838. if (!this._frustumPlanes) {
  16839. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16840. }
  16841. else {
  16842. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16843. }
  16844. if (this._sceneUbo.useUbo) {
  16845. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16846. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16847. this._sceneUbo.update();
  16848. }
  16849. };
  16850. Scene.prototype.getSceneUniformBuffer = function () {
  16851. return this._sceneUbo;
  16852. };
  16853. // Methods
  16854. Scene.prototype.getUniqueId = function () {
  16855. var result = this._uniqueIdCounter;
  16856. this._uniqueIdCounter++;
  16857. return result;
  16858. };
  16859. Scene.prototype.addMesh = function (newMesh) {
  16860. newMesh.uniqueId = this.getUniqueId();
  16861. var position = this.meshes.push(newMesh);
  16862. //notify the collision coordinator
  16863. if (this.collisionCoordinator) {
  16864. this.collisionCoordinator.onMeshAdded(newMesh);
  16865. }
  16866. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16867. };
  16868. Scene.prototype.removeMesh = function (toRemove) {
  16869. var index = this.meshes.indexOf(toRemove);
  16870. if (index !== -1) {
  16871. // Remove from the scene if mesh found
  16872. this.meshes.splice(index, 1);
  16873. }
  16874. //notify the collision coordinator
  16875. if (this.collisionCoordinator) {
  16876. this.collisionCoordinator.onMeshRemoved(toRemove);
  16877. }
  16878. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16879. return index;
  16880. };
  16881. Scene.prototype.removeSkeleton = function (toRemove) {
  16882. var index = this.skeletons.indexOf(toRemove);
  16883. if (index !== -1) {
  16884. // Remove from the scene if found
  16885. this.skeletons.splice(index, 1);
  16886. }
  16887. return index;
  16888. };
  16889. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16890. var index = this.morphTargetManagers.indexOf(toRemove);
  16891. if (index !== -1) {
  16892. // Remove from the scene if found
  16893. this.morphTargetManagers.splice(index, 1);
  16894. }
  16895. return index;
  16896. };
  16897. Scene.prototype.removeLight = function (toRemove) {
  16898. var index = this.lights.indexOf(toRemove);
  16899. if (index !== -1) {
  16900. // Remove from the scene if mesh found
  16901. this.lights.splice(index, 1);
  16902. this.sortLightsByPriority();
  16903. }
  16904. this.onLightRemovedObservable.notifyObservers(toRemove);
  16905. return index;
  16906. };
  16907. Scene.prototype.removeCamera = function (toRemove) {
  16908. var index = this.cameras.indexOf(toRemove);
  16909. if (index !== -1) {
  16910. // Remove from the scene if mesh found
  16911. this.cameras.splice(index, 1);
  16912. }
  16913. // Remove from activeCameras
  16914. var index2 = this.activeCameras.indexOf(toRemove);
  16915. if (index2 !== -1) {
  16916. // Remove from the scene if mesh found
  16917. this.activeCameras.splice(index2, 1);
  16918. }
  16919. // Reset the activeCamera
  16920. if (this.activeCamera === toRemove) {
  16921. if (this.cameras.length > 0) {
  16922. this.activeCamera = this.cameras[0];
  16923. }
  16924. else {
  16925. this.activeCamera = null;
  16926. }
  16927. }
  16928. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16929. return index;
  16930. };
  16931. Scene.prototype.addLight = function (newLight) {
  16932. newLight.uniqueId = this.getUniqueId();
  16933. this.lights.push(newLight);
  16934. this.sortLightsByPriority();
  16935. this.onNewLightAddedObservable.notifyObservers(newLight);
  16936. };
  16937. Scene.prototype.sortLightsByPriority = function () {
  16938. if (this.requireLightSorting) {
  16939. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16940. }
  16941. };
  16942. Scene.prototype.addCamera = function (newCamera) {
  16943. newCamera.uniqueId = this.getUniqueId();
  16944. var position = this.cameras.push(newCamera);
  16945. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16946. };
  16947. /**
  16948. * Switch active camera
  16949. * @param {Camera} newCamera - new active camera
  16950. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16951. */
  16952. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16953. if (attachControl === void 0) { attachControl = true; }
  16954. var canvas = this._engine.getRenderingCanvas();
  16955. this.activeCamera.detachControl(canvas);
  16956. this.activeCamera = newCamera;
  16957. if (attachControl) {
  16958. newCamera.attachControl(canvas);
  16959. }
  16960. };
  16961. /**
  16962. * sets the active camera of the scene using its ID
  16963. * @param {string} id - the camera's ID
  16964. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16965. * @see activeCamera
  16966. */
  16967. Scene.prototype.setActiveCameraByID = function (id) {
  16968. var camera = this.getCameraByID(id);
  16969. if (camera) {
  16970. this.activeCamera = camera;
  16971. return camera;
  16972. }
  16973. return null;
  16974. };
  16975. /**
  16976. * sets the active camera of the scene using its name
  16977. * @param {string} name - the camera's name
  16978. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16979. * @see activeCamera
  16980. */
  16981. Scene.prototype.setActiveCameraByName = function (name) {
  16982. var camera = this.getCameraByName(name);
  16983. if (camera) {
  16984. this.activeCamera = camera;
  16985. return camera;
  16986. }
  16987. return null;
  16988. };
  16989. /**
  16990. * get a material using its id
  16991. * @param {string} the material's ID
  16992. * @return {BABYLON.Material|null} the material or null if none found.
  16993. */
  16994. Scene.prototype.getMaterialByID = function (id) {
  16995. for (var index = 0; index < this.materials.length; index++) {
  16996. if (this.materials[index].id === id) {
  16997. return this.materials[index];
  16998. }
  16999. }
  17000. return null;
  17001. };
  17002. /**
  17003. * get a material using its name
  17004. * @param {string} the material's name
  17005. * @return {BABYLON.Material|null} the material or null if none found.
  17006. */
  17007. Scene.prototype.getMaterialByName = function (name) {
  17008. for (var index = 0; index < this.materials.length; index++) {
  17009. if (this.materials[index].name === name) {
  17010. return this.materials[index];
  17011. }
  17012. }
  17013. return null;
  17014. };
  17015. Scene.prototype.getLensFlareSystemByName = function (name) {
  17016. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17017. if (this.lensFlareSystems[index].name === name) {
  17018. return this.lensFlareSystems[index];
  17019. }
  17020. }
  17021. return null;
  17022. };
  17023. Scene.prototype.getLensFlareSystemByID = function (id) {
  17024. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17025. if (this.lensFlareSystems[index].id === id) {
  17026. return this.lensFlareSystems[index];
  17027. }
  17028. }
  17029. return null;
  17030. };
  17031. Scene.prototype.getCameraByID = function (id) {
  17032. for (var index = 0; index < this.cameras.length; index++) {
  17033. if (this.cameras[index].id === id) {
  17034. return this.cameras[index];
  17035. }
  17036. }
  17037. return null;
  17038. };
  17039. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17040. for (var index = 0; index < this.cameras.length; index++) {
  17041. if (this.cameras[index].uniqueId === uniqueId) {
  17042. return this.cameras[index];
  17043. }
  17044. }
  17045. return null;
  17046. };
  17047. /**
  17048. * get a camera using its name
  17049. * @param {string} the camera's name
  17050. * @return {BABYLON.Camera|null} the camera or null if none found.
  17051. */
  17052. Scene.prototype.getCameraByName = function (name) {
  17053. for (var index = 0; index < this.cameras.length; index++) {
  17054. if (this.cameras[index].name === name) {
  17055. return this.cameras[index];
  17056. }
  17057. }
  17058. return null;
  17059. };
  17060. /**
  17061. * get a bone using its id
  17062. * @param {string} the bone's id
  17063. * @return {BABYLON.Bone|null} the bone or null if not found
  17064. */
  17065. Scene.prototype.getBoneByID = function (id) {
  17066. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17067. var skeleton = this.skeletons[skeletonIndex];
  17068. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17069. if (skeleton.bones[boneIndex].id === id) {
  17070. return skeleton.bones[boneIndex];
  17071. }
  17072. }
  17073. }
  17074. return null;
  17075. };
  17076. /**
  17077. * get a bone using its id
  17078. * @param {string} the bone's name
  17079. * @return {BABYLON.Bone|null} the bone or null if not found
  17080. */
  17081. Scene.prototype.getBoneByName = function (name) {
  17082. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17083. var skeleton = this.skeletons[skeletonIndex];
  17084. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17085. if (skeleton.bones[boneIndex].name === name) {
  17086. return skeleton.bones[boneIndex];
  17087. }
  17088. }
  17089. }
  17090. return null;
  17091. };
  17092. /**
  17093. * get a light node using its name
  17094. * @param {string} the light's name
  17095. * @return {BABYLON.Light|null} the light or null if none found.
  17096. */
  17097. Scene.prototype.getLightByName = function (name) {
  17098. for (var index = 0; index < this.lights.length; index++) {
  17099. if (this.lights[index].name === name) {
  17100. return this.lights[index];
  17101. }
  17102. }
  17103. return null;
  17104. };
  17105. /**
  17106. * get a light node using its ID
  17107. * @param {string} the light's id
  17108. * @return {BABYLON.Light|null} the light or null if none found.
  17109. */
  17110. Scene.prototype.getLightByID = function (id) {
  17111. for (var index = 0; index < this.lights.length; index++) {
  17112. if (this.lights[index].id === id) {
  17113. return this.lights[index];
  17114. }
  17115. }
  17116. return null;
  17117. };
  17118. /**
  17119. * get a light node using its scene-generated unique ID
  17120. * @param {number} the light's unique id
  17121. * @return {BABYLON.Light|null} the light or null if none found.
  17122. */
  17123. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17124. for (var index = 0; index < this.lights.length; index++) {
  17125. if (this.lights[index].uniqueId === uniqueId) {
  17126. return this.lights[index];
  17127. }
  17128. }
  17129. return null;
  17130. };
  17131. /**
  17132. * get a particle system by id
  17133. * @param id {number} the particle system id
  17134. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17135. */
  17136. Scene.prototype.getParticleSystemByID = function (id) {
  17137. for (var index = 0; index < this.particleSystems.length; index++) {
  17138. if (this.particleSystems[index].id === id) {
  17139. return this.particleSystems[index];
  17140. }
  17141. }
  17142. return null;
  17143. };
  17144. /**
  17145. * get a geometry using its ID
  17146. * @param {string} the geometry's id
  17147. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17148. */
  17149. Scene.prototype.getGeometryByID = function (id) {
  17150. for (var index = 0; index < this._geometries.length; index++) {
  17151. if (this._geometries[index].id === id) {
  17152. return this._geometries[index];
  17153. }
  17154. }
  17155. return null;
  17156. };
  17157. /**
  17158. * add a new geometry to this scene.
  17159. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17160. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17161. * @return {boolean} was the geometry added or not
  17162. */
  17163. Scene.prototype.pushGeometry = function (geometry, force) {
  17164. if (!force && this.getGeometryByID(geometry.id)) {
  17165. return false;
  17166. }
  17167. this._geometries.push(geometry);
  17168. //notify the collision coordinator
  17169. if (this.collisionCoordinator) {
  17170. this.collisionCoordinator.onGeometryAdded(geometry);
  17171. }
  17172. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17173. return true;
  17174. };
  17175. /**
  17176. * Removes an existing geometry
  17177. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17178. * @return {boolean} was the geometry removed or not
  17179. */
  17180. Scene.prototype.removeGeometry = function (geometry) {
  17181. var index = this._geometries.indexOf(geometry);
  17182. if (index > -1) {
  17183. this._geometries.splice(index, 1);
  17184. //notify the collision coordinator
  17185. if (this.collisionCoordinator) {
  17186. this.collisionCoordinator.onGeometryDeleted(geometry);
  17187. }
  17188. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17189. return true;
  17190. }
  17191. return false;
  17192. };
  17193. Scene.prototype.getGeometries = function () {
  17194. return this._geometries;
  17195. };
  17196. /**
  17197. * Get the first added mesh found of a given ID
  17198. * @param {string} id - the id to search for
  17199. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17200. */
  17201. Scene.prototype.getMeshByID = function (id) {
  17202. for (var index = 0; index < this.meshes.length; index++) {
  17203. if (this.meshes[index].id === id) {
  17204. return this.meshes[index];
  17205. }
  17206. }
  17207. return null;
  17208. };
  17209. Scene.prototype.getMeshesByID = function (id) {
  17210. return this.meshes.filter(function (m) {
  17211. return m.id === id;
  17212. });
  17213. };
  17214. /**
  17215. * Get a mesh with its auto-generated unique id
  17216. * @param {number} uniqueId - the unique id to search for
  17217. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17218. */
  17219. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17220. for (var index = 0; index < this.meshes.length; index++) {
  17221. if (this.meshes[index].uniqueId === uniqueId) {
  17222. return this.meshes[index];
  17223. }
  17224. }
  17225. return null;
  17226. };
  17227. /**
  17228. * Get a the last added mesh found of a given ID
  17229. * @param {string} id - the id to search for
  17230. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17231. */
  17232. Scene.prototype.getLastMeshByID = function (id) {
  17233. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17234. if (this.meshes[index].id === id) {
  17235. return this.meshes[index];
  17236. }
  17237. }
  17238. return null;
  17239. };
  17240. /**
  17241. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17242. * @param {string} id - the id to search for
  17243. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17244. */
  17245. Scene.prototype.getLastEntryByID = function (id) {
  17246. var index;
  17247. for (index = this.meshes.length - 1; index >= 0; index--) {
  17248. if (this.meshes[index].id === id) {
  17249. return this.meshes[index];
  17250. }
  17251. }
  17252. for (index = this.cameras.length - 1; index >= 0; index--) {
  17253. if (this.cameras[index].id === id) {
  17254. return this.cameras[index];
  17255. }
  17256. }
  17257. for (index = this.lights.length - 1; index >= 0; index--) {
  17258. if (this.lights[index].id === id) {
  17259. return this.lights[index];
  17260. }
  17261. }
  17262. return null;
  17263. };
  17264. Scene.prototype.getNodeByID = function (id) {
  17265. var mesh = this.getMeshByID(id);
  17266. if (mesh) {
  17267. return mesh;
  17268. }
  17269. var light = this.getLightByID(id);
  17270. if (light) {
  17271. return light;
  17272. }
  17273. var camera = this.getCameraByID(id);
  17274. if (camera) {
  17275. return camera;
  17276. }
  17277. var bone = this.getBoneByID(id);
  17278. return bone;
  17279. };
  17280. Scene.prototype.getNodeByName = function (name) {
  17281. var mesh = this.getMeshByName(name);
  17282. if (mesh) {
  17283. return mesh;
  17284. }
  17285. var light = this.getLightByName(name);
  17286. if (light) {
  17287. return light;
  17288. }
  17289. var camera = this.getCameraByName(name);
  17290. if (camera) {
  17291. return camera;
  17292. }
  17293. var bone = this.getBoneByName(name);
  17294. return bone;
  17295. };
  17296. Scene.prototype.getMeshByName = function (name) {
  17297. for (var index = 0; index < this.meshes.length; index++) {
  17298. if (this.meshes[index].name === name) {
  17299. return this.meshes[index];
  17300. }
  17301. }
  17302. return null;
  17303. };
  17304. Scene.prototype.getSoundByName = function (name) {
  17305. var index;
  17306. if (BABYLON.AudioEngine) {
  17307. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17308. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17309. return this.mainSoundTrack.soundCollection[index];
  17310. }
  17311. }
  17312. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17313. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17314. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17315. return this.soundTracks[sdIndex].soundCollection[index];
  17316. }
  17317. }
  17318. }
  17319. }
  17320. return null;
  17321. };
  17322. Scene.prototype.getLastSkeletonByID = function (id) {
  17323. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17324. if (this.skeletons[index].id === id) {
  17325. return this.skeletons[index];
  17326. }
  17327. }
  17328. return null;
  17329. };
  17330. Scene.prototype.getSkeletonById = function (id) {
  17331. for (var index = 0; index < this.skeletons.length; index++) {
  17332. if (this.skeletons[index].id === id) {
  17333. return this.skeletons[index];
  17334. }
  17335. }
  17336. return null;
  17337. };
  17338. Scene.prototype.getSkeletonByName = function (name) {
  17339. for (var index = 0; index < this.skeletons.length; index++) {
  17340. if (this.skeletons[index].name === name) {
  17341. return this.skeletons[index];
  17342. }
  17343. }
  17344. return null;
  17345. };
  17346. Scene.prototype.getMorphTargetManagerById = function (id) {
  17347. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17348. if (this.morphTargetManagers[index].uniqueId === id) {
  17349. return this.morphTargetManagers[index];
  17350. }
  17351. }
  17352. return null;
  17353. };
  17354. Scene.prototype.isActiveMesh = function (mesh) {
  17355. return (this._activeMeshes.indexOf(mesh) !== -1);
  17356. };
  17357. /**
  17358. * Return a the first highlight layer of the scene with a given name.
  17359. * @param name The name of the highlight layer to look for.
  17360. * @return The highlight layer if found otherwise null.
  17361. */
  17362. Scene.prototype.getHighlightLayerByName = function (name) {
  17363. for (var index = 0; index < this.highlightLayers.length; index++) {
  17364. if (this.highlightLayers[index].name === name) {
  17365. return this.highlightLayers[index];
  17366. }
  17367. }
  17368. return null;
  17369. };
  17370. Object.defineProperty(Scene.prototype, "uid", {
  17371. /**
  17372. * Return a unique id as a string which can serve as an identifier for the scene
  17373. */
  17374. get: function () {
  17375. if (!this._uid) {
  17376. this._uid = BABYLON.Tools.RandomId();
  17377. }
  17378. return this._uid;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. /**
  17384. * Add an externaly attached data from its key.
  17385. * This method call will fail and return false, if such key already exists.
  17386. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17387. * @param key the unique key that identifies the data
  17388. * @param data the data object to associate to the key for this Engine instance
  17389. * @return true if no such key were already present and the data was added successfully, false otherwise
  17390. */
  17391. Scene.prototype.addExternalData = function (key, data) {
  17392. if (!this._externalData) {
  17393. this._externalData = new BABYLON.StringDictionary();
  17394. }
  17395. return this._externalData.add(key, data);
  17396. };
  17397. /**
  17398. * Get an externaly attached data from its key
  17399. * @param key the unique key that identifies the data
  17400. * @return the associated data, if present (can be null), or undefined if not present
  17401. */
  17402. Scene.prototype.getExternalData = function (key) {
  17403. if (!this._externalData) {
  17404. return null;
  17405. }
  17406. return this._externalData.get(key);
  17407. };
  17408. /**
  17409. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17410. * @param key the unique key that identifies the data
  17411. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17412. * @return the associated data, can be null if the factory returned null.
  17413. */
  17414. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17415. if (!this._externalData) {
  17416. this._externalData = new BABYLON.StringDictionary();
  17417. }
  17418. return this._externalData.getOrAddWithFactory(key, factory);
  17419. };
  17420. /**
  17421. * Remove an externaly attached data from the Engine instance
  17422. * @param key the unique key that identifies the data
  17423. * @return true if the data was successfully removed, false if it doesn't exist
  17424. */
  17425. Scene.prototype.removeExternalData = function (key) {
  17426. return this._externalData.remove(key);
  17427. };
  17428. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17429. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17430. var material = subMesh.getMaterial();
  17431. if (mesh.showSubMeshesBoundingBox) {
  17432. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17433. }
  17434. if (material) {
  17435. // Render targets
  17436. if (material.getRenderTargetTextures) {
  17437. if (this._processedMaterials.indexOf(material) === -1) {
  17438. this._processedMaterials.push(material);
  17439. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17440. }
  17441. }
  17442. // Dispatch
  17443. this._activeIndices.addCount(subMesh.indexCount, false);
  17444. this._renderingManager.dispatch(subMesh);
  17445. }
  17446. }
  17447. };
  17448. Scene.prototype._isInIntermediateRendering = function () {
  17449. return this._intermediateRendering;
  17450. };
  17451. Scene.prototype._evaluateActiveMeshes = function () {
  17452. this.activeCamera._activeMeshes.reset();
  17453. this._activeMeshes.reset();
  17454. this._renderingManager.reset();
  17455. this._processedMaterials.reset();
  17456. this._activeParticleSystems.reset();
  17457. this._activeSkeletons.reset();
  17458. this._softwareSkinnedMeshes.reset();
  17459. if (this._boundingBoxRenderer) {
  17460. this._boundingBoxRenderer.reset();
  17461. }
  17462. // Meshes
  17463. var meshes;
  17464. var len;
  17465. if (this._selectionOctree) {
  17466. var selection = this._selectionOctree.select(this._frustumPlanes);
  17467. meshes = selection.data;
  17468. len = selection.length;
  17469. }
  17470. else {
  17471. len = this.meshes.length;
  17472. meshes = this.meshes;
  17473. }
  17474. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17475. var mesh = meshes[meshIndex];
  17476. if (mesh.isBlocked) {
  17477. continue;
  17478. }
  17479. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17480. if (!mesh.isReady() || !mesh.isEnabled()) {
  17481. continue;
  17482. }
  17483. mesh.computeWorldMatrix();
  17484. // Intersections
  17485. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17486. this._meshesForIntersections.pushNoDuplicate(mesh);
  17487. }
  17488. // Switch to current LOD
  17489. var meshLOD = mesh.getLOD(this.activeCamera);
  17490. if (!meshLOD) {
  17491. continue;
  17492. }
  17493. mesh._preActivate();
  17494. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17495. this._activeMeshes.push(mesh);
  17496. this.activeCamera._activeMeshes.push(mesh);
  17497. mesh._activate(this._renderId);
  17498. this._activeMesh(mesh, meshLOD);
  17499. }
  17500. }
  17501. // Particle systems
  17502. this._particlesDuration.beginMonitoring();
  17503. var beforeParticlesDate = BABYLON.Tools.Now;
  17504. if (this.particlesEnabled) {
  17505. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17506. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17507. var particleSystem = this.particleSystems[particleIndex];
  17508. if (!particleSystem.isStarted()) {
  17509. continue;
  17510. }
  17511. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17512. this._activeParticleSystems.push(particleSystem);
  17513. particleSystem.animate();
  17514. this._renderingManager.dispatchParticles(particleSystem);
  17515. }
  17516. }
  17517. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17518. }
  17519. this._particlesDuration.endMonitoring(false);
  17520. };
  17521. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17522. if (mesh.skeleton && this.skeletonsEnabled) {
  17523. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17524. mesh.skeleton.prepare();
  17525. }
  17526. if (!mesh.computeBonesUsingShaders) {
  17527. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17528. }
  17529. }
  17530. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17531. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17532. }
  17533. if (mesh && mesh.subMeshes) {
  17534. // Submeshes Octrees
  17535. var len;
  17536. var subMeshes;
  17537. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17538. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17539. len = intersections.length;
  17540. subMeshes = intersections.data;
  17541. }
  17542. else {
  17543. subMeshes = mesh.subMeshes;
  17544. len = subMeshes.length;
  17545. }
  17546. for (var subIndex = 0; subIndex < len; subIndex++) {
  17547. var subMesh = subMeshes[subIndex];
  17548. this._evaluateSubMesh(subMesh, mesh);
  17549. }
  17550. }
  17551. };
  17552. Scene.prototype.updateTransformMatrix = function (force) {
  17553. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17554. };
  17555. Scene.prototype._renderForCamera = function (camera) {
  17556. var engine = this._engine;
  17557. var startTime = BABYLON.Tools.Now;
  17558. this.activeCamera = camera;
  17559. if (!this.activeCamera)
  17560. throw new Error("Active camera not set");
  17561. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17562. // Viewport
  17563. engine.setViewport(this.activeCamera.viewport);
  17564. // Camera
  17565. this.resetCachedMaterial();
  17566. this._renderId++;
  17567. this.updateTransformMatrix();
  17568. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17569. // Meshes
  17570. this._evaluateActiveMeshesDuration.beginMonitoring();
  17571. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17572. this._evaluateActiveMeshes();
  17573. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17574. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17575. // Software skinning
  17576. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17577. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17578. mesh.applySkeleton(mesh.skeleton);
  17579. }
  17580. // Render targets
  17581. this._renderTargetsDuration.beginMonitoring();
  17582. var needsRestoreFrameBuffer = false;
  17583. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17584. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17585. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17586. }
  17587. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17588. this._intermediateRendering = true;
  17589. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17590. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17591. var renderTarget = this._renderTargets.data[renderIndex];
  17592. if (renderTarget._shouldRender()) {
  17593. this._renderId++;
  17594. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17595. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17596. }
  17597. }
  17598. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17599. this._intermediateRendering = false;
  17600. this._renderId++;
  17601. needsRestoreFrameBuffer = true; // Restore back buffer
  17602. }
  17603. // Render HighlightLayer Texture
  17604. var stencilState = this._engine.getStencilBuffer();
  17605. var renderhighlights = false;
  17606. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17607. this._intermediateRendering = true;
  17608. for (var i = 0; i < this.highlightLayers.length; i++) {
  17609. var highlightLayer = this.highlightLayers[i];
  17610. if (highlightLayer.shouldRender() &&
  17611. (!highlightLayer.camera ||
  17612. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17613. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17614. renderhighlights = true;
  17615. var renderTarget = highlightLayer._mainTexture;
  17616. if (renderTarget._shouldRender()) {
  17617. this._renderId++;
  17618. renderTarget.render(false, false);
  17619. needsRestoreFrameBuffer = true;
  17620. }
  17621. }
  17622. }
  17623. this._intermediateRendering = false;
  17624. this._renderId++;
  17625. }
  17626. if (needsRestoreFrameBuffer) {
  17627. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17628. }
  17629. this._renderTargetsDuration.endMonitoring(false);
  17630. // Prepare Frame
  17631. this.postProcessManager._prepareFrame();
  17632. this._renderDuration.beginMonitoring();
  17633. // Backgrounds
  17634. var layerIndex;
  17635. var layer;
  17636. if (this.layers.length) {
  17637. engine.setDepthBuffer(false);
  17638. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17639. layer = this.layers[layerIndex];
  17640. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17641. layer.render();
  17642. }
  17643. }
  17644. engine.setDepthBuffer(true);
  17645. }
  17646. // Render
  17647. BABYLON.Tools.StartPerformanceCounter("Main render");
  17648. // Activate HighlightLayer stencil
  17649. if (renderhighlights) {
  17650. this._engine.setStencilBuffer(true);
  17651. }
  17652. this._renderingManager.render(null, null, true, true);
  17653. // Restore HighlightLayer stencil
  17654. if (renderhighlights) {
  17655. this._engine.setStencilBuffer(stencilState);
  17656. }
  17657. BABYLON.Tools.EndPerformanceCounter("Main render");
  17658. // Bounding boxes
  17659. if (this._boundingBoxRenderer) {
  17660. this._boundingBoxRenderer.render();
  17661. }
  17662. // Lens flares
  17663. if (this.lensFlaresEnabled) {
  17664. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17665. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17666. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17667. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17668. lensFlareSystem.render();
  17669. }
  17670. }
  17671. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17672. }
  17673. // Foregrounds
  17674. if (this.layers.length) {
  17675. engine.setDepthBuffer(false);
  17676. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17677. layer = this.layers[layerIndex];
  17678. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17679. layer.render();
  17680. }
  17681. }
  17682. engine.setDepthBuffer(true);
  17683. }
  17684. // Highlight Layer
  17685. if (renderhighlights) {
  17686. engine.setDepthBuffer(false);
  17687. for (var i = 0; i < this.highlightLayers.length; i++) {
  17688. if (this.highlightLayers[i].shouldRender()) {
  17689. this.highlightLayers[i].render();
  17690. }
  17691. }
  17692. engine.setDepthBuffer(true);
  17693. }
  17694. this._renderDuration.endMonitoring(false);
  17695. // Finalize frame
  17696. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17697. // Update camera
  17698. this.activeCamera._updateFromScene();
  17699. // Reset some special arrays
  17700. this._renderTargets.reset();
  17701. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17702. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17703. };
  17704. Scene.prototype._processSubCameras = function (camera) {
  17705. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17706. this._renderForCamera(camera);
  17707. return;
  17708. }
  17709. // rig cameras
  17710. for (var index = 0; index < camera._rigCameras.length; index++) {
  17711. this._renderForCamera(camera._rigCameras[index]);
  17712. }
  17713. this.activeCamera = camera;
  17714. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17715. // Update camera
  17716. this.activeCamera._updateFromScene();
  17717. };
  17718. Scene.prototype._checkIntersections = function () {
  17719. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17720. var sourceMesh = this._meshesForIntersections.data[index];
  17721. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17722. var action = sourceMesh.actionManager.actions[actionIndex];
  17723. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17724. var parameters = action.getTriggerParameter();
  17725. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17726. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17727. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17728. if (areIntersecting && currentIntersectionInProgress === -1) {
  17729. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17730. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17731. sourceMesh._intersectionsInProgress.push(otherMesh);
  17732. }
  17733. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17734. sourceMesh._intersectionsInProgress.push(otherMesh);
  17735. }
  17736. }
  17737. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17738. //They intersected, and now they don't.
  17739. //is this trigger an exit trigger? execute an event.
  17740. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17741. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17742. }
  17743. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17744. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17745. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17746. }
  17747. }
  17748. }
  17749. }
  17750. }
  17751. };
  17752. Scene.prototype.render = function () {
  17753. if (this.isDisposed) {
  17754. return;
  17755. }
  17756. this._lastFrameDuration.beginMonitoring();
  17757. this._particlesDuration.fetchNewFrame();
  17758. this._spritesDuration.fetchNewFrame();
  17759. this._activeParticles.fetchNewFrame();
  17760. this._renderDuration.fetchNewFrame();
  17761. this._renderTargetsDuration.fetchNewFrame();
  17762. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17763. this._totalVertices.fetchNewFrame();
  17764. this._activeIndices.fetchNewFrame();
  17765. this._activeBones.fetchNewFrame();
  17766. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17767. this._meshesForIntersections.reset();
  17768. this.resetCachedMaterial();
  17769. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17770. // Actions
  17771. if (this.actionManager) {
  17772. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17773. }
  17774. //Simplification Queue
  17775. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17776. this.simplificationQueue.executeNext();
  17777. }
  17778. // Animations
  17779. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17780. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17781. this._animate();
  17782. // Physics
  17783. if (this._physicsEngine) {
  17784. BABYLON.Tools.StartPerformanceCounter("Physics");
  17785. this._physicsEngine._step(deltaTime / 1000.0);
  17786. BABYLON.Tools.EndPerformanceCounter("Physics");
  17787. }
  17788. // Before render
  17789. this.onBeforeRenderObservable.notifyObservers(this);
  17790. // Customs render targets
  17791. this._renderTargetsDuration.beginMonitoring();
  17792. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17793. var engine = this.getEngine();
  17794. var currentActiveCamera = this.activeCamera;
  17795. if (this.renderTargetsEnabled) {
  17796. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17797. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17798. var renderTarget = this.customRenderTargets[customIndex];
  17799. if (renderTarget._shouldRender()) {
  17800. this._renderId++;
  17801. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17802. if (!this.activeCamera)
  17803. throw new Error("Active camera not set");
  17804. // Viewport
  17805. engine.setViewport(this.activeCamera.viewport);
  17806. // Camera
  17807. this.updateTransformMatrix();
  17808. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17809. }
  17810. }
  17811. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17812. this._renderId++;
  17813. }
  17814. // Restore back buffer
  17815. if (this.customRenderTargets.length > 0) {
  17816. engine.restoreDefaultFramebuffer();
  17817. }
  17818. this._renderTargetsDuration.endMonitoring();
  17819. this.activeCamera = currentActiveCamera;
  17820. // Procedural textures
  17821. if (this.proceduralTexturesEnabled) {
  17822. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17823. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17824. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17825. if (proceduralTexture._shouldRender()) {
  17826. proceduralTexture.render();
  17827. }
  17828. }
  17829. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17830. }
  17831. // Clear
  17832. if (this.autoClearDepthAndStencil || this.autoClear) {
  17833. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17834. }
  17835. // Shadows
  17836. if (this.shadowsEnabled) {
  17837. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17838. var light = this.lights[lightIndex];
  17839. var shadowGenerator = light.getShadowGenerator();
  17840. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17841. var shadowMap = shadowGenerator.getShadowMap();
  17842. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17843. this._renderTargets.push(shadowMap);
  17844. }
  17845. }
  17846. }
  17847. }
  17848. // Depth renderer
  17849. if (this._depthRenderer) {
  17850. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17851. }
  17852. // Geometry renderer
  17853. if (this._geometryBufferRenderer) {
  17854. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17855. }
  17856. // RenderPipeline
  17857. if (this._postProcessRenderPipelineManager) {
  17858. this._postProcessRenderPipelineManager.update();
  17859. }
  17860. // Multi-cameras?
  17861. if (this.activeCameras.length > 0) {
  17862. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17863. if (cameraIndex > 0) {
  17864. this._engine.clear(null, false, true, true);
  17865. }
  17866. this._processSubCameras(this.activeCameras[cameraIndex]);
  17867. }
  17868. }
  17869. else {
  17870. if (!this.activeCamera) {
  17871. throw new Error("No camera defined");
  17872. }
  17873. this._processSubCameras(this.activeCamera);
  17874. }
  17875. // Intersection checks
  17876. this._checkIntersections();
  17877. // Update the audio listener attached to the camera
  17878. if (BABYLON.AudioEngine) {
  17879. this._updateAudioParameters();
  17880. }
  17881. // After render
  17882. if (this.afterRender) {
  17883. this.afterRender();
  17884. }
  17885. this.onAfterRenderObservable.notifyObservers(this);
  17886. // Cleaning
  17887. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17888. this._toBeDisposed.data[index].dispose();
  17889. this._toBeDisposed[index] = null;
  17890. }
  17891. this._toBeDisposed.reset();
  17892. if (this.dumpNextRenderTargets) {
  17893. this.dumpNextRenderTargets = false;
  17894. }
  17895. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17896. this._lastFrameDuration.endMonitoring();
  17897. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17898. this._totalLightsCounter.addCount(this.lights.length, true);
  17899. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17900. this._totalTexturesCounter.addCount(this.textures.length, true);
  17901. this._activeBones.addCount(0, true);
  17902. this._activeIndices.addCount(0, true);
  17903. this._activeParticles.addCount(0, true);
  17904. };
  17905. Scene.prototype._updateAudioParameters = function () {
  17906. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17907. return;
  17908. }
  17909. var listeningCamera;
  17910. var audioEngine = BABYLON.Engine.audioEngine;
  17911. if (this.activeCameras.length > 0) {
  17912. listeningCamera = this.activeCameras[0];
  17913. }
  17914. else {
  17915. listeningCamera = this.activeCamera;
  17916. }
  17917. if (listeningCamera && audioEngine.canUseWebAudio) {
  17918. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17919. // for VR cameras
  17920. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17921. listeningCamera = listeningCamera.rigCameras[0];
  17922. }
  17923. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17924. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17925. cameraDirection.normalize();
  17926. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17927. var i;
  17928. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17929. var sound = this.mainSoundTrack.soundCollection[i];
  17930. if (sound.useCustomAttenuation) {
  17931. sound.updateDistanceFromListener();
  17932. }
  17933. }
  17934. for (i = 0; i < this.soundTracks.length; i++) {
  17935. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17936. sound = this.soundTracks[i].soundCollection[j];
  17937. if (sound.useCustomAttenuation) {
  17938. sound.updateDistanceFromListener();
  17939. }
  17940. }
  17941. }
  17942. }
  17943. };
  17944. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17945. // Audio
  17946. get: function () {
  17947. return this._audioEnabled;
  17948. },
  17949. set: function (value) {
  17950. this._audioEnabled = value;
  17951. if (BABYLON.AudioEngine) {
  17952. if (this._audioEnabled) {
  17953. this._enableAudio();
  17954. }
  17955. else {
  17956. this._disableAudio();
  17957. }
  17958. }
  17959. },
  17960. enumerable: true,
  17961. configurable: true
  17962. });
  17963. Scene.prototype._disableAudio = function () {
  17964. var i;
  17965. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17966. this.mainSoundTrack.soundCollection[i].pause();
  17967. }
  17968. for (i = 0; i < this.soundTracks.length; i++) {
  17969. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17970. this.soundTracks[i].soundCollection[j].pause();
  17971. }
  17972. }
  17973. };
  17974. Scene.prototype._enableAudio = function () {
  17975. var i;
  17976. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17977. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17978. this.mainSoundTrack.soundCollection[i].play();
  17979. }
  17980. }
  17981. for (i = 0; i < this.soundTracks.length; i++) {
  17982. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17983. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17984. this.soundTracks[i].soundCollection[j].play();
  17985. }
  17986. }
  17987. }
  17988. };
  17989. Object.defineProperty(Scene.prototype, "headphone", {
  17990. get: function () {
  17991. return this._headphone;
  17992. },
  17993. set: function (value) {
  17994. this._headphone = value;
  17995. if (BABYLON.AudioEngine) {
  17996. if (this._headphone) {
  17997. this._switchAudioModeForHeadphones();
  17998. }
  17999. else {
  18000. this._switchAudioModeForNormalSpeakers();
  18001. }
  18002. }
  18003. },
  18004. enumerable: true,
  18005. configurable: true
  18006. });
  18007. Scene.prototype._switchAudioModeForHeadphones = function () {
  18008. this.mainSoundTrack.switchPanningModelToHRTF();
  18009. for (var i = 0; i < this.soundTracks.length; i++) {
  18010. this.soundTracks[i].switchPanningModelToHRTF();
  18011. }
  18012. };
  18013. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18014. this.mainSoundTrack.switchPanningModelToEqualPower();
  18015. for (var i = 0; i < this.soundTracks.length; i++) {
  18016. this.soundTracks[i].switchPanningModelToEqualPower();
  18017. }
  18018. };
  18019. Scene.prototype.enableDepthRenderer = function () {
  18020. if (this._depthRenderer) {
  18021. return this._depthRenderer;
  18022. }
  18023. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18024. return this._depthRenderer;
  18025. };
  18026. Scene.prototype.disableDepthRenderer = function () {
  18027. if (!this._depthRenderer) {
  18028. return;
  18029. }
  18030. this._depthRenderer.dispose();
  18031. this._depthRenderer = null;
  18032. };
  18033. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18034. if (ratio === void 0) { ratio = 1; }
  18035. if (this._geometryBufferRenderer) {
  18036. return this._geometryBufferRenderer;
  18037. }
  18038. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18039. if (!this._geometryBufferRenderer.isSupported) {
  18040. this._geometryBufferRenderer = null;
  18041. }
  18042. return this._geometryBufferRenderer;
  18043. };
  18044. Scene.prototype.disableGeometryBufferRenderer = function () {
  18045. if (!this._geometryBufferRenderer) {
  18046. return;
  18047. }
  18048. this._geometryBufferRenderer.dispose();
  18049. this._geometryBufferRenderer = null;
  18050. };
  18051. Scene.prototype.freezeMaterials = function () {
  18052. for (var i = 0; i < this.materials.length; i++) {
  18053. this.materials[i].freeze();
  18054. }
  18055. };
  18056. Scene.prototype.unfreezeMaterials = function () {
  18057. for (var i = 0; i < this.materials.length; i++) {
  18058. this.materials[i].unfreeze();
  18059. }
  18060. };
  18061. Scene.prototype.dispose = function () {
  18062. this.beforeRender = null;
  18063. this.afterRender = null;
  18064. this.skeletons = [];
  18065. this.morphTargetManagers = [];
  18066. this.importedMeshesFiles = new Array();
  18067. if (this._depthRenderer) {
  18068. this._depthRenderer.dispose();
  18069. }
  18070. // Smart arrays
  18071. if (this.activeCamera) {
  18072. this.activeCamera._activeMeshes.dispose();
  18073. this.activeCamera = null;
  18074. }
  18075. this._activeMeshes.dispose();
  18076. this._renderingManager.dispose();
  18077. this._processedMaterials.dispose();
  18078. this._activeParticleSystems.dispose();
  18079. this._activeSkeletons.dispose();
  18080. this._softwareSkinnedMeshes.dispose();
  18081. if (this._boundingBoxRenderer) {
  18082. this._boundingBoxRenderer.dispose();
  18083. }
  18084. this._meshesForIntersections.dispose();
  18085. this._toBeDisposed.dispose();
  18086. // Debug layer
  18087. if (this._debugLayer) {
  18088. this._debugLayer.hide();
  18089. }
  18090. // Events
  18091. this.onDisposeObservable.notifyObservers(this);
  18092. this.onDisposeObservable.clear();
  18093. this.onBeforeRenderObservable.clear();
  18094. this.onAfterRenderObservable.clear();
  18095. this.detachControl();
  18096. // Release sounds & sounds tracks
  18097. if (BABYLON.AudioEngine) {
  18098. this.disposeSounds();
  18099. }
  18100. // Detach cameras
  18101. var canvas = this._engine.getRenderingCanvas();
  18102. var index;
  18103. for (index = 0; index < this.cameras.length; index++) {
  18104. this.cameras[index].detachControl(canvas);
  18105. }
  18106. // Release lights
  18107. while (this.lights.length) {
  18108. this.lights[0].dispose();
  18109. }
  18110. // Release meshes
  18111. while (this.meshes.length) {
  18112. this.meshes[0].dispose(true);
  18113. }
  18114. // Release cameras
  18115. while (this.cameras.length) {
  18116. this.cameras[0].dispose();
  18117. }
  18118. // Release materials
  18119. while (this.materials.length) {
  18120. this.materials[0].dispose();
  18121. }
  18122. // Release particles
  18123. while (this.particleSystems.length) {
  18124. this.particleSystems[0].dispose();
  18125. }
  18126. // Release sprites
  18127. while (this.spriteManagers.length) {
  18128. this.spriteManagers[0].dispose();
  18129. }
  18130. // Release layers
  18131. while (this.layers.length) {
  18132. this.layers[0].dispose();
  18133. }
  18134. while (this.highlightLayers.length) {
  18135. this.highlightLayers[0].dispose();
  18136. }
  18137. // Release textures
  18138. while (this.textures.length) {
  18139. this.textures[0].dispose();
  18140. }
  18141. // Release UBO
  18142. this._sceneUbo.dispose();
  18143. // Post-processes
  18144. this.postProcessManager.dispose();
  18145. // Physics
  18146. if (this._physicsEngine) {
  18147. this.disablePhysicsEngine();
  18148. }
  18149. // Remove from engine
  18150. index = this._engine.scenes.indexOf(this);
  18151. if (index > -1) {
  18152. this._engine.scenes.splice(index, 1);
  18153. }
  18154. this._engine.wipeCaches();
  18155. this._engine = null;
  18156. };
  18157. Object.defineProperty(Scene.prototype, "isDisposed", {
  18158. get: function () {
  18159. return !this._engine;
  18160. },
  18161. enumerable: true,
  18162. configurable: true
  18163. });
  18164. // Release sounds & sounds tracks
  18165. Scene.prototype.disposeSounds = function () {
  18166. this.mainSoundTrack.dispose();
  18167. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18168. this.soundTracks[scIndex].dispose();
  18169. }
  18170. };
  18171. // Octrees
  18172. Scene.prototype.getWorldExtends = function () {
  18173. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18174. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18175. for (var index = 0; index < this.meshes.length; index++) {
  18176. var mesh = this.meshes[index];
  18177. mesh.computeWorldMatrix(true);
  18178. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18179. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18180. BABYLON.Tools.CheckExtends(minBox, min, max);
  18181. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18182. }
  18183. return {
  18184. min: min,
  18185. max: max
  18186. };
  18187. };
  18188. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18189. if (maxCapacity === void 0) { maxCapacity = 64; }
  18190. if (maxDepth === void 0) { maxDepth = 2; }
  18191. if (!this._selectionOctree) {
  18192. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18193. }
  18194. var worldExtends = this.getWorldExtends();
  18195. // Update octree
  18196. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18197. return this._selectionOctree;
  18198. };
  18199. // Picking
  18200. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18201. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18202. var engine = this._engine;
  18203. if (!camera) {
  18204. if (!this.activeCamera)
  18205. throw new Error("Active camera not set");
  18206. camera = this.activeCamera;
  18207. }
  18208. var cameraViewport = camera.viewport;
  18209. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18210. // Moving coordinates to local viewport world
  18211. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18212. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18213. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18214. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18215. };
  18216. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18217. if (!BABYLON.PickingInfo) {
  18218. return null;
  18219. }
  18220. var engine = this._engine;
  18221. if (!camera) {
  18222. if (!this.activeCamera)
  18223. throw new Error("Active camera not set");
  18224. camera = this.activeCamera;
  18225. }
  18226. var cameraViewport = camera.viewport;
  18227. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18228. var identity = BABYLON.Matrix.Identity();
  18229. // Moving coordinates to local viewport world
  18230. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18231. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18232. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18233. };
  18234. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18235. if (!BABYLON.PickingInfo) {
  18236. return null;
  18237. }
  18238. var pickingInfo = null;
  18239. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18240. var mesh = this.meshes[meshIndex];
  18241. if (predicate) {
  18242. if (!predicate(mesh)) {
  18243. continue;
  18244. }
  18245. }
  18246. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18247. continue;
  18248. }
  18249. var world = mesh.getWorldMatrix();
  18250. var ray = rayFunction(world);
  18251. var result = mesh.intersects(ray, fastCheck);
  18252. if (!result || !result.hit)
  18253. continue;
  18254. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18255. continue;
  18256. pickingInfo = result;
  18257. if (fastCheck) {
  18258. break;
  18259. }
  18260. }
  18261. return pickingInfo || new BABYLON.PickingInfo();
  18262. };
  18263. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18264. if (!BABYLON.PickingInfo) {
  18265. return null;
  18266. }
  18267. var pickingInfos = new Array();
  18268. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18269. var mesh = this.meshes[meshIndex];
  18270. if (predicate) {
  18271. if (!predicate(mesh)) {
  18272. continue;
  18273. }
  18274. }
  18275. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18276. continue;
  18277. }
  18278. var world = mesh.getWorldMatrix();
  18279. var ray = rayFunction(world);
  18280. var result = mesh.intersects(ray, false);
  18281. if (!result || !result.hit)
  18282. continue;
  18283. pickingInfos.push(result);
  18284. }
  18285. return pickingInfos;
  18286. };
  18287. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18288. if (!BABYLON.PickingInfo) {
  18289. return null;
  18290. }
  18291. var pickingInfo = null;
  18292. camera = camera || this.activeCamera;
  18293. if (this.spriteManagers.length > 0) {
  18294. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18295. var spriteManager = this.spriteManagers[spriteIndex];
  18296. if (!spriteManager.isPickable) {
  18297. continue;
  18298. }
  18299. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18300. if (!result || !result.hit)
  18301. continue;
  18302. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18303. continue;
  18304. pickingInfo = result;
  18305. if (fastCheck) {
  18306. break;
  18307. }
  18308. }
  18309. }
  18310. return pickingInfo || new BABYLON.PickingInfo();
  18311. };
  18312. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18313. /// <param name="x">X position on screen</param>
  18314. /// <param name="y">Y position on screen</param>
  18315. /// <param name="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</param>
  18316. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18317. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18318. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18319. var _this = this;
  18320. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18321. };
  18322. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18323. /// <param name="x">X position on screen</param>
  18324. /// <param name="y">Y position on screen</param>
  18325. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  18326. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18327. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18328. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18329. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18330. };
  18331. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18332. var _this = this;
  18333. return this._internalPick(function (world) {
  18334. if (!_this._pickWithRayInverseMatrix) {
  18335. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18336. }
  18337. world.invertToRef(_this._pickWithRayInverseMatrix);
  18338. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18339. }, predicate, fastCheck);
  18340. };
  18341. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18342. /// <param name="x">X position on screen</param>
  18343. /// <param name="y">Y position on screen</param>
  18344. /// <param name="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</param>
  18345. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18346. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18347. var _this = this;
  18348. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18349. };
  18350. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18351. /// <param name="ray">Ray to use</param>
  18352. /// <param name="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</param>
  18353. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18354. var _this = this;
  18355. return this._internalMultiPick(function (world) {
  18356. if (!_this._pickWithRayInverseMatrix) {
  18357. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18358. }
  18359. world.invertToRef(_this._pickWithRayInverseMatrix);
  18360. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18361. }, predicate);
  18362. };
  18363. Scene.prototype.setPointerOverMesh = function (mesh) {
  18364. if (this._pointerOverMesh === mesh) {
  18365. return;
  18366. }
  18367. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18368. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18369. }
  18370. this._pointerOverMesh = mesh;
  18371. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18372. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18373. }
  18374. };
  18375. Scene.prototype.getPointerOverMesh = function () {
  18376. return this._pointerOverMesh;
  18377. };
  18378. Scene.prototype.setPointerOverSprite = function (sprite) {
  18379. if (this._pointerOverSprite === sprite) {
  18380. return;
  18381. }
  18382. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18383. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18384. }
  18385. this._pointerOverSprite = sprite;
  18386. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18387. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18388. }
  18389. };
  18390. Scene.prototype.getPointerOverSprite = function () {
  18391. return this._pointerOverSprite;
  18392. };
  18393. // Physics
  18394. Scene.prototype.getPhysicsEngine = function () {
  18395. return this._physicsEngine;
  18396. };
  18397. /**
  18398. * Enables physics to the current scene
  18399. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18400. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18401. * @return {boolean} was the physics engine initialized
  18402. */
  18403. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18404. if (this._physicsEngine) {
  18405. return true;
  18406. }
  18407. try {
  18408. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18409. return true;
  18410. }
  18411. catch (e) {
  18412. BABYLON.Tools.Error(e.message);
  18413. return false;
  18414. }
  18415. };
  18416. Scene.prototype.disablePhysicsEngine = function () {
  18417. if (!this._physicsEngine) {
  18418. return;
  18419. }
  18420. this._physicsEngine.dispose();
  18421. this._physicsEngine = undefined;
  18422. };
  18423. Scene.prototype.isPhysicsEnabled = function () {
  18424. return this._physicsEngine !== undefined;
  18425. };
  18426. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18427. var mesh = compound.parts[0].mesh;
  18428. mesh.physicsImpostor.dispose();
  18429. mesh.physicsImpostor = null;
  18430. };
  18431. // Misc.
  18432. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  18433. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18434. if (replace === void 0) { replace = false; }
  18435. if (attachCameraControls === void 0) { attachCameraControls = false; }
  18436. // Dispose existing camera or light in replace mode.
  18437. if (replace) {
  18438. if (this.activeCamera) {
  18439. this.activeCamera.dispose();
  18440. this.activeCamera = null;
  18441. }
  18442. if (this.lights) {
  18443. for (var i = 0; i < this.lights.length; i++) {
  18444. this.lights[i].dispose();
  18445. }
  18446. }
  18447. }
  18448. // Light
  18449. if (this.lights.length === 0) {
  18450. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18451. }
  18452. // Camera
  18453. if (!this.activeCamera) {
  18454. var worldExtends = this.getWorldExtends();
  18455. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18456. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18457. var camera;
  18458. var radius = worldSize.length() * 1.5;
  18459. if (createArcRotateCamera) {
  18460. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18461. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18462. arcRotateCamera.wheelPrecision = 100 / radius;
  18463. camera = arcRotateCamera;
  18464. }
  18465. else {
  18466. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18467. freeCamera.setTarget(worldCenter);
  18468. camera = freeCamera;
  18469. }
  18470. camera.minZ = radius * 0.01;
  18471. camera.maxZ = radius * 100;
  18472. camera.speed = radius * 0.2;
  18473. this.activeCamera = camera;
  18474. if (attachCameraControls) {
  18475. camera.attachControl(this.getEngine().getRenderingCanvas());
  18476. }
  18477. }
  18478. };
  18479. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  18480. if (pbr === void 0) { pbr = false; }
  18481. if (scale === void 0) { scale = 1000; }
  18482. if (blur === void 0) { blur = 0; }
  18483. if (environmentTexture) {
  18484. this.environmentTexture = environmentTexture;
  18485. }
  18486. if (!this.environmentTexture) {
  18487. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18488. return;
  18489. }
  18490. // Skybox
  18491. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  18492. if (pbr) {
  18493. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18494. hdrSkyboxMaterial.backFaceCulling = false;
  18495. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18496. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18497. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  18498. hdrSkyboxMaterial.disableLighting = true;
  18499. hdrSkyboxMaterial.twoSidedLighting = true;
  18500. hdrSkybox.infiniteDistance = true;
  18501. hdrSkybox.material = hdrSkyboxMaterial;
  18502. }
  18503. else {
  18504. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18505. skyboxMaterial.backFaceCulling = false;
  18506. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18507. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18508. skyboxMaterial.disableLighting = true;
  18509. hdrSkybox.infiniteDistance = true;
  18510. hdrSkybox.material = skyboxMaterial;
  18511. }
  18512. return hdrSkybox;
  18513. };
  18514. // Tags
  18515. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18516. if (tagsQuery === undefined) {
  18517. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18518. return list;
  18519. }
  18520. var listByTags = [];
  18521. forEach = forEach || (function (item) { return; });
  18522. for (var i in list) {
  18523. var item = list[i];
  18524. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18525. listByTags.push(item);
  18526. forEach(item);
  18527. }
  18528. }
  18529. return listByTags;
  18530. };
  18531. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18532. return this._getByTags(this.meshes, tagsQuery, forEach);
  18533. };
  18534. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18535. return this._getByTags(this.cameras, tagsQuery, forEach);
  18536. };
  18537. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18538. return this._getByTags(this.lights, tagsQuery, forEach);
  18539. };
  18540. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18541. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18542. };
  18543. /**
  18544. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18545. * This allowed control for front to back rendering or reversly depending of the special needs.
  18546. *
  18547. * @param renderingGroupId The rendering group id corresponding to its index
  18548. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18549. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18550. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18551. */
  18552. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18553. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18554. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18555. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18556. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18557. };
  18558. /**
  18559. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18560. *
  18561. * @param renderingGroupId The rendering group id corresponding to its index
  18562. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18563. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18564. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18565. */
  18566. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18567. if (depth === void 0) { depth = true; }
  18568. if (stencil === void 0) { stencil = true; }
  18569. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18570. };
  18571. /**
  18572. * Will flag all materials as dirty to trigger new shader compilation
  18573. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18574. */
  18575. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18576. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18577. var material = _a[_i];
  18578. if (predicate && !predicate(material)) {
  18579. continue;
  18580. }
  18581. material.markAsDirty(flag);
  18582. }
  18583. };
  18584. return Scene;
  18585. }());
  18586. // Statics
  18587. Scene._FOGMODE_NONE = 0;
  18588. Scene._FOGMODE_EXP = 1;
  18589. Scene._FOGMODE_EXP2 = 2;
  18590. Scene._FOGMODE_LINEAR = 3;
  18591. Scene.MinDeltaTime = 1.0;
  18592. Scene.MaxDeltaTime = 1000.0;
  18593. Scene.DragMovementThreshold = 10; // in pixels
  18594. Scene.LongPressDelay = 500; // in milliseconds
  18595. Scene.DoubleClickDelay = 300; // in milliseconds
  18596. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18597. BABYLON.Scene = Scene;
  18598. })(BABYLON || (BABYLON = {}));
  18599. //# sourceMappingURL=babylon.scene.js.map
  18600. var BABYLON;
  18601. (function (BABYLON) {
  18602. var Buffer = (function () {
  18603. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18604. if (engine instanceof BABYLON.Mesh) {
  18605. this._engine = engine.getScene().getEngine();
  18606. }
  18607. else {
  18608. this._engine = engine;
  18609. }
  18610. this._updatable = updatable;
  18611. this._data = data;
  18612. this._strideSize = stride;
  18613. if (!postponeInternalCreation) {
  18614. this.create();
  18615. }
  18616. this._instanced = instanced;
  18617. this._instanceDivisor = instanced ? 1 : 0;
  18618. }
  18619. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18620. // a lot of these parameters are ignored as they are overriden by the buffer
  18621. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18622. };
  18623. // Properties
  18624. Buffer.prototype.isUpdatable = function () {
  18625. return this._updatable;
  18626. };
  18627. Buffer.prototype.getData = function () {
  18628. return this._data;
  18629. };
  18630. Buffer.prototype.getBuffer = function () {
  18631. return this._buffer;
  18632. };
  18633. Buffer.prototype.getStrideSize = function () {
  18634. return this._strideSize;
  18635. };
  18636. Buffer.prototype.getIsInstanced = function () {
  18637. return this._instanced;
  18638. };
  18639. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18640. get: function () {
  18641. return this._instanceDivisor;
  18642. },
  18643. set: function (value) {
  18644. this._instanceDivisor = value;
  18645. if (value == 0) {
  18646. this._instanced = false;
  18647. }
  18648. else {
  18649. this._instanced = true;
  18650. }
  18651. },
  18652. enumerable: true,
  18653. configurable: true
  18654. });
  18655. // Methods
  18656. Buffer.prototype.create = function (data) {
  18657. if (!data && this._buffer) {
  18658. return; // nothing to do
  18659. }
  18660. data = data || this._data;
  18661. if (!this._buffer) {
  18662. if (this._updatable) {
  18663. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18664. this._data = data;
  18665. }
  18666. else {
  18667. this._buffer = this._engine.createVertexBuffer(data);
  18668. }
  18669. }
  18670. else if (this._updatable) {
  18671. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18672. this._data = data;
  18673. }
  18674. };
  18675. Buffer.prototype.update = function (data) {
  18676. this.create(data);
  18677. };
  18678. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18679. if (!this._buffer) {
  18680. return;
  18681. }
  18682. if (this._updatable) {
  18683. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18684. this._data = null;
  18685. }
  18686. };
  18687. Buffer.prototype.dispose = function () {
  18688. if (!this._buffer) {
  18689. return;
  18690. }
  18691. if (this._engine._releaseBuffer(this._buffer)) {
  18692. this._buffer = null;
  18693. }
  18694. };
  18695. return Buffer;
  18696. }());
  18697. BABYLON.Buffer = Buffer;
  18698. })(BABYLON || (BABYLON = {}));
  18699. //# sourceMappingURL=babylon.buffer.js.map
  18700. var BABYLON;
  18701. (function (BABYLON) {
  18702. var VertexBuffer = (function () {
  18703. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18704. if (!stride) {
  18705. // Deduce stride from kind
  18706. switch (kind) {
  18707. case VertexBuffer.PositionKind:
  18708. stride = 3;
  18709. break;
  18710. case VertexBuffer.NormalKind:
  18711. stride = 3;
  18712. break;
  18713. case VertexBuffer.UVKind:
  18714. case VertexBuffer.UV2Kind:
  18715. case VertexBuffer.UV3Kind:
  18716. case VertexBuffer.UV4Kind:
  18717. case VertexBuffer.UV5Kind:
  18718. case VertexBuffer.UV6Kind:
  18719. stride = 2;
  18720. break;
  18721. case VertexBuffer.TangentKind:
  18722. case VertexBuffer.ColorKind:
  18723. stride = 4;
  18724. break;
  18725. case VertexBuffer.MatricesIndicesKind:
  18726. case VertexBuffer.MatricesIndicesExtraKind:
  18727. stride = 4;
  18728. break;
  18729. case VertexBuffer.MatricesWeightsKind:
  18730. case VertexBuffer.MatricesWeightsExtraKind:
  18731. stride = 4;
  18732. break;
  18733. }
  18734. }
  18735. if (data instanceof BABYLON.Buffer) {
  18736. if (!stride) {
  18737. stride = data.getStrideSize();
  18738. }
  18739. this._buffer = data;
  18740. this._ownsBuffer = false;
  18741. }
  18742. else {
  18743. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18744. this._ownsBuffer = true;
  18745. }
  18746. this._stride = stride;
  18747. this._offset = offset ? offset : 0;
  18748. this._size = size ? size : stride;
  18749. this._kind = kind;
  18750. }
  18751. /**
  18752. * Returns the kind of the VertexBuffer (string).
  18753. */
  18754. VertexBuffer.prototype.getKind = function () {
  18755. return this._kind;
  18756. };
  18757. // Properties
  18758. /**
  18759. * Boolean : is the VertexBuffer updatable ?
  18760. */
  18761. VertexBuffer.prototype.isUpdatable = function () {
  18762. return this._buffer.isUpdatable();
  18763. };
  18764. /**
  18765. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18766. */
  18767. VertexBuffer.prototype.getData = function () {
  18768. return this._buffer.getData();
  18769. };
  18770. /**
  18771. * Returns the WebGLBuffer associated to the VertexBuffer.
  18772. */
  18773. VertexBuffer.prototype.getBuffer = function () {
  18774. return this._buffer.getBuffer();
  18775. };
  18776. /**
  18777. * Returns the stride of the VertexBuffer (integer).
  18778. */
  18779. VertexBuffer.prototype.getStrideSize = function () {
  18780. return this._stride;
  18781. };
  18782. /**
  18783. * Returns the offset (integer).
  18784. */
  18785. VertexBuffer.prototype.getOffset = function () {
  18786. return this._offset;
  18787. };
  18788. /**
  18789. * Returns the VertexBuffer total size (integer).
  18790. */
  18791. VertexBuffer.prototype.getSize = function () {
  18792. return this._size;
  18793. };
  18794. /**
  18795. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18796. */
  18797. VertexBuffer.prototype.getIsInstanced = function () {
  18798. return this._buffer.getIsInstanced();
  18799. };
  18800. /**
  18801. * Returns the instancing divisor, zero for non-instanced (integer).
  18802. */
  18803. VertexBuffer.prototype.getInstanceDivisor = function () {
  18804. return this._buffer.instanceDivisor;
  18805. };
  18806. // Methods
  18807. /**
  18808. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18809. * Returns the created WebGLBuffer.
  18810. */
  18811. VertexBuffer.prototype.create = function (data) {
  18812. return this._buffer.create(data);
  18813. };
  18814. /**
  18815. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18816. * Returns the updated WebGLBuffer.
  18817. */
  18818. VertexBuffer.prototype.update = function (data) {
  18819. return this._buffer.update(data);
  18820. };
  18821. /**
  18822. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18823. * Returns the directly updated WebGLBuffer.
  18824. */
  18825. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18826. return this._buffer.updateDirectly(data, offset);
  18827. };
  18828. /**
  18829. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18830. */
  18831. VertexBuffer.prototype.dispose = function () {
  18832. if (this._ownsBuffer) {
  18833. this._buffer.dispose();
  18834. }
  18835. };
  18836. Object.defineProperty(VertexBuffer, "PositionKind", {
  18837. get: function () {
  18838. return VertexBuffer._PositionKind;
  18839. },
  18840. enumerable: true,
  18841. configurable: true
  18842. });
  18843. Object.defineProperty(VertexBuffer, "NormalKind", {
  18844. get: function () {
  18845. return VertexBuffer._NormalKind;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. Object.defineProperty(VertexBuffer, "TangentKind", {
  18851. get: function () {
  18852. return VertexBuffer._TangentKind;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. Object.defineProperty(VertexBuffer, "UVKind", {
  18858. get: function () {
  18859. return VertexBuffer._UVKind;
  18860. },
  18861. enumerable: true,
  18862. configurable: true
  18863. });
  18864. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18865. get: function () {
  18866. return VertexBuffer._UV2Kind;
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18872. get: function () {
  18873. return VertexBuffer._UV3Kind;
  18874. },
  18875. enumerable: true,
  18876. configurable: true
  18877. });
  18878. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18879. get: function () {
  18880. return VertexBuffer._UV4Kind;
  18881. },
  18882. enumerable: true,
  18883. configurable: true
  18884. });
  18885. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18886. get: function () {
  18887. return VertexBuffer._UV5Kind;
  18888. },
  18889. enumerable: true,
  18890. configurable: true
  18891. });
  18892. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18893. get: function () {
  18894. return VertexBuffer._UV6Kind;
  18895. },
  18896. enumerable: true,
  18897. configurable: true
  18898. });
  18899. Object.defineProperty(VertexBuffer, "ColorKind", {
  18900. get: function () {
  18901. return VertexBuffer._ColorKind;
  18902. },
  18903. enumerable: true,
  18904. configurable: true
  18905. });
  18906. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18907. get: function () {
  18908. return VertexBuffer._MatricesIndicesKind;
  18909. },
  18910. enumerable: true,
  18911. configurable: true
  18912. });
  18913. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18914. get: function () {
  18915. return VertexBuffer._MatricesWeightsKind;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18921. get: function () {
  18922. return VertexBuffer._MatricesIndicesExtraKind;
  18923. },
  18924. enumerable: true,
  18925. configurable: true
  18926. });
  18927. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18928. get: function () {
  18929. return VertexBuffer._MatricesWeightsExtraKind;
  18930. },
  18931. enumerable: true,
  18932. configurable: true
  18933. });
  18934. return VertexBuffer;
  18935. }());
  18936. // Enums
  18937. VertexBuffer._PositionKind = "position";
  18938. VertexBuffer._NormalKind = "normal";
  18939. VertexBuffer._TangentKind = "tangent";
  18940. VertexBuffer._UVKind = "uv";
  18941. VertexBuffer._UV2Kind = "uv2";
  18942. VertexBuffer._UV3Kind = "uv3";
  18943. VertexBuffer._UV4Kind = "uv4";
  18944. VertexBuffer._UV5Kind = "uv5";
  18945. VertexBuffer._UV6Kind = "uv6";
  18946. VertexBuffer._ColorKind = "color";
  18947. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18948. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18949. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18950. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18951. BABYLON.VertexBuffer = VertexBuffer;
  18952. })(BABYLON || (BABYLON = {}));
  18953. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18954. var BABYLON;
  18955. (function (BABYLON) {
  18956. var BaseTexture = (function () {
  18957. function BaseTexture(scene) {
  18958. this._hasAlpha = false;
  18959. this.getAlphaFromRGB = false;
  18960. this.level = 1;
  18961. this.coordinatesIndex = 0;
  18962. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18963. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18964. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18965. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18966. this.isCube = false;
  18967. this.gammaSpace = true;
  18968. this.invertZ = false;
  18969. this.lodLevelInAlpha = false;
  18970. this.lodGenerationOffset = 0.0;
  18971. this.lodGenerationScale = 0.8;
  18972. this.isRenderTarget = false;
  18973. this.animations = new Array();
  18974. /**
  18975. * An event triggered when the texture is disposed.
  18976. * @type {BABYLON.Observable}
  18977. */
  18978. this.onDisposeObservable = new BABYLON.Observable();
  18979. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18980. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18981. this._scene.textures.push(this);
  18982. this._uid = null;
  18983. }
  18984. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18985. get: function () {
  18986. return this._hasAlpha;
  18987. },
  18988. set: function (value) {
  18989. if (this._hasAlpha === value) {
  18990. return;
  18991. }
  18992. this._hasAlpha = value;
  18993. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18994. },
  18995. enumerable: true,
  18996. configurable: true
  18997. });
  18998. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18999. get: function () {
  19000. return this._coordinatesMode;
  19001. },
  19002. set: function (value) {
  19003. if (this._coordinatesMode === value) {
  19004. return;
  19005. }
  19006. this._coordinatesMode = value;
  19007. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19008. },
  19009. enumerable: true,
  19010. configurable: true
  19011. });
  19012. Object.defineProperty(BaseTexture.prototype, "uid", {
  19013. get: function () {
  19014. if (!this._uid) {
  19015. this._uid = BABYLON.Tools.RandomId();
  19016. }
  19017. return this._uid;
  19018. },
  19019. enumerable: true,
  19020. configurable: true
  19021. });
  19022. BaseTexture.prototype.toString = function () {
  19023. return this.name;
  19024. };
  19025. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  19026. set: function (callback) {
  19027. if (this._onDisposeObserver) {
  19028. this.onDisposeObservable.remove(this._onDisposeObserver);
  19029. }
  19030. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  19036. get: function () {
  19037. return true;
  19038. },
  19039. enumerable: true,
  19040. configurable: true
  19041. });
  19042. BaseTexture.prototype.getScene = function () {
  19043. return this._scene;
  19044. };
  19045. BaseTexture.prototype.getTextureMatrix = function () {
  19046. return null;
  19047. };
  19048. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  19049. return null;
  19050. };
  19051. BaseTexture.prototype.getInternalTexture = function () {
  19052. return this._texture;
  19053. };
  19054. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  19055. return !this.isBlocking || this.isReady();
  19056. };
  19057. BaseTexture.prototype.isReady = function () {
  19058. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19059. this.delayLoad();
  19060. return false;
  19061. }
  19062. if (this._texture) {
  19063. return this._texture.isReady;
  19064. }
  19065. return false;
  19066. };
  19067. BaseTexture.prototype.getSize = function () {
  19068. if (this._texture._width) {
  19069. return new BABYLON.Size(this._texture._width, this._texture._height);
  19070. }
  19071. if (this._texture._size) {
  19072. return new BABYLON.Size(this._texture._size, this._texture._size);
  19073. }
  19074. return BABYLON.Size.Zero();
  19075. };
  19076. BaseTexture.prototype.getBaseSize = function () {
  19077. if (!this.isReady() || !this._texture)
  19078. return BABYLON.Size.Zero();
  19079. if (this._texture._size) {
  19080. return new BABYLON.Size(this._texture._size, this._texture._size);
  19081. }
  19082. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19083. };
  19084. BaseTexture.prototype.scale = function (ratio) {
  19085. };
  19086. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19087. get: function () {
  19088. return false;
  19089. },
  19090. enumerable: true,
  19091. configurable: true
  19092. });
  19093. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19094. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19095. for (var index = 0; index < texturesCache.length; index++) {
  19096. var texturesCacheEntry = texturesCache[index];
  19097. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19098. texturesCache.splice(index, 1);
  19099. return;
  19100. }
  19101. }
  19102. };
  19103. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19104. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19105. for (var index = 0; index < texturesCache.length; index++) {
  19106. var texturesCacheEntry = texturesCache[index];
  19107. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  19108. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19109. texturesCacheEntry.references++;
  19110. return texturesCacheEntry;
  19111. }
  19112. }
  19113. }
  19114. return null;
  19115. };
  19116. BaseTexture.prototype.delayLoad = function () {
  19117. };
  19118. BaseTexture.prototype.clone = function () {
  19119. return null;
  19120. };
  19121. Object.defineProperty(BaseTexture.prototype, "textureType", {
  19122. get: function () {
  19123. if (!this._texture) {
  19124. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19125. }
  19126. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  19127. },
  19128. enumerable: true,
  19129. configurable: true
  19130. });
  19131. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  19132. get: function () {
  19133. if (!this._texture) {
  19134. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19135. }
  19136. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  19137. },
  19138. enumerable: true,
  19139. configurable: true
  19140. });
  19141. BaseTexture.prototype.readPixels = function (faceIndex) {
  19142. if (faceIndex === void 0) { faceIndex = 0; }
  19143. if (!this._texture) {
  19144. return null;
  19145. }
  19146. var size = this.getSize();
  19147. var engine = this.getScene().getEngine();
  19148. if (this._texture.isCube) {
  19149. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19150. }
  19151. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  19152. };
  19153. BaseTexture.prototype.releaseInternalTexture = function () {
  19154. if (this._texture) {
  19155. this._scene.getEngine().releaseInternalTexture(this._texture);
  19156. delete this._texture;
  19157. }
  19158. };
  19159. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  19160. get: function () {
  19161. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  19162. return null;
  19163. }
  19164. if (!this._texture._sphericalPolynomial) {
  19165. this._texture._sphericalPolynomial =
  19166. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  19167. }
  19168. return this._texture._sphericalPolynomial;
  19169. },
  19170. set: function (value) {
  19171. if (this._texture) {
  19172. this._texture._sphericalPolynomial = value;
  19173. }
  19174. },
  19175. enumerable: true,
  19176. configurable: true
  19177. });
  19178. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  19179. get: function () {
  19180. if (this._texture) {
  19181. return this._texture._lodTextureHigh;
  19182. }
  19183. return null;
  19184. },
  19185. enumerable: true,
  19186. configurable: true
  19187. });
  19188. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  19189. get: function () {
  19190. if (this._texture) {
  19191. return this._texture._lodTextureMid;
  19192. }
  19193. return null;
  19194. },
  19195. enumerable: true,
  19196. configurable: true
  19197. });
  19198. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  19199. get: function () {
  19200. if (this._texture) {
  19201. return this._texture._lodTextureLow;
  19202. }
  19203. return null;
  19204. },
  19205. enumerable: true,
  19206. configurable: true
  19207. });
  19208. BaseTexture.prototype.dispose = function () {
  19209. // Animations
  19210. this.getScene().stopAnimation(this);
  19211. // Remove from scene
  19212. this._scene._removePendingData(this);
  19213. var index = this._scene.textures.indexOf(this);
  19214. if (index >= 0) {
  19215. this._scene.textures.splice(index, 1);
  19216. }
  19217. if (this._texture === undefined) {
  19218. return;
  19219. }
  19220. // Release
  19221. this.releaseInternalTexture();
  19222. // Callback
  19223. this.onDisposeObservable.notifyObservers(this);
  19224. this.onDisposeObservable.clear();
  19225. };
  19226. BaseTexture.prototype.serialize = function () {
  19227. if (!this.name) {
  19228. return null;
  19229. }
  19230. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19231. // Animations
  19232. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19233. return serializationObject;
  19234. };
  19235. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19236. var numReady = 0;
  19237. var _loop_1 = function () {
  19238. texture = textures[i];
  19239. if (texture.isReady()) {
  19240. if (++numReady === textures.length) {
  19241. onLoad();
  19242. }
  19243. }
  19244. else {
  19245. observable = texture.onLoadObservable;
  19246. var callback_1 = function () {
  19247. observable.removeCallback(callback_1);
  19248. if (++numReady === textures.length) {
  19249. onLoad();
  19250. }
  19251. };
  19252. observable.add(callback_1);
  19253. }
  19254. };
  19255. var texture, observable;
  19256. for (var i = 0; i < textures.length; i++) {
  19257. _loop_1();
  19258. }
  19259. };
  19260. return BaseTexture;
  19261. }());
  19262. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19263. __decorate([
  19264. BABYLON.serialize()
  19265. ], BaseTexture.prototype, "name", void 0);
  19266. __decorate([
  19267. BABYLON.serialize("hasAlpha")
  19268. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19269. __decorate([
  19270. BABYLON.serialize()
  19271. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19272. __decorate([
  19273. BABYLON.serialize()
  19274. ], BaseTexture.prototype, "level", void 0);
  19275. __decorate([
  19276. BABYLON.serialize()
  19277. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19278. __decorate([
  19279. BABYLON.serialize("coordinatesMode")
  19280. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19281. __decorate([
  19282. BABYLON.serialize()
  19283. ], BaseTexture.prototype, "wrapU", void 0);
  19284. __decorate([
  19285. BABYLON.serialize()
  19286. ], BaseTexture.prototype, "wrapV", void 0);
  19287. __decorate([
  19288. BABYLON.serialize()
  19289. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19290. __decorate([
  19291. BABYLON.serialize()
  19292. ], BaseTexture.prototype, "isCube", void 0);
  19293. __decorate([
  19294. BABYLON.serialize()
  19295. ], BaseTexture.prototype, "gammaSpace", void 0);
  19296. __decorate([
  19297. BABYLON.serialize()
  19298. ], BaseTexture.prototype, "invertZ", void 0);
  19299. __decorate([
  19300. BABYLON.serialize()
  19301. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  19302. __decorate([
  19303. BABYLON.serialize()
  19304. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19311. BABYLON.BaseTexture = BaseTexture;
  19312. })(BABYLON || (BABYLON = {}));
  19313. //# sourceMappingURL=babylon.baseTexture.js.map
  19314. var BABYLON;
  19315. (function (BABYLON) {
  19316. var Texture = (function (_super) {
  19317. __extends(Texture, _super);
  19318. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19319. if (noMipmap === void 0) { noMipmap = false; }
  19320. if (invertY === void 0) { invertY = true; }
  19321. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19322. if (onLoad === void 0) { onLoad = null; }
  19323. if (onError === void 0) { onError = null; }
  19324. if (buffer === void 0) { buffer = null; }
  19325. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19326. var _this = _super.call(this, scene) || this;
  19327. _this.uOffset = 0;
  19328. _this.vOffset = 0;
  19329. _this.uScale = 1.0;
  19330. _this.vScale = 1.0;
  19331. _this.uAng = 0;
  19332. _this.vAng = 0;
  19333. _this.wAng = 0;
  19334. _this._isBlocking = true;
  19335. _this.name = url;
  19336. _this.url = url;
  19337. _this._noMipmap = noMipmap;
  19338. _this._invertY = invertY;
  19339. _this._samplingMode = samplingMode;
  19340. _this._buffer = buffer;
  19341. _this._deleteBuffer = deleteBuffer;
  19342. _this._format = format;
  19343. scene = _this.getScene();
  19344. var load = function () {
  19345. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19346. _this.onLoadObservable.notifyObservers(_this);
  19347. }
  19348. if (onLoad) {
  19349. onLoad();
  19350. }
  19351. if (!_this.isBlocking) {
  19352. scene.resetCachedMaterial();
  19353. }
  19354. };
  19355. if (!url) {
  19356. _this._delayedOnLoad = load;
  19357. _this._delayedOnError = onError;
  19358. return _this;
  19359. }
  19360. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19361. if (!_this._texture) {
  19362. if (!scene.useDelayedTextureLoading) {
  19363. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19364. if (deleteBuffer) {
  19365. delete _this._buffer;
  19366. }
  19367. }
  19368. else {
  19369. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19370. _this._delayedOnLoad = load;
  19371. _this._delayedOnError = onError;
  19372. }
  19373. }
  19374. else {
  19375. if (_this._texture.isReady) {
  19376. BABYLON.Tools.SetImmediate(function () { return load(); });
  19377. }
  19378. else {
  19379. _this._texture.onLoadedCallbacks.push(load);
  19380. }
  19381. }
  19382. return _this;
  19383. }
  19384. Object.defineProperty(Texture.prototype, "noMipmap", {
  19385. get: function () {
  19386. return this._noMipmap;
  19387. },
  19388. enumerable: true,
  19389. configurable: true
  19390. });
  19391. Object.defineProperty(Texture.prototype, "isBlocking", {
  19392. get: function () {
  19393. return this._isBlocking;
  19394. },
  19395. set: function (value) {
  19396. this._isBlocking = value;
  19397. },
  19398. enumerable: true,
  19399. configurable: true
  19400. });
  19401. Texture.prototype.updateURL = function (url) {
  19402. this.url = url;
  19403. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19404. this.delayLoad();
  19405. };
  19406. Texture.prototype.delayLoad = function () {
  19407. var _this = this;
  19408. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19409. return;
  19410. }
  19411. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19412. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19413. if (!this._texture) {
  19414. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  19415. if (this._deleteBuffer) {
  19416. delete this._buffer;
  19417. }
  19418. }
  19419. else {
  19420. if (this._texture.isReady) {
  19421. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19422. }
  19423. else {
  19424. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19425. }
  19426. }
  19427. };
  19428. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19429. if (!this._texture) {
  19430. return;
  19431. }
  19432. this._samplingMode = samplingMode;
  19433. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19434. };
  19435. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19436. x *= this.uScale;
  19437. y *= this.vScale;
  19438. x -= 0.5 * this.uScale;
  19439. y -= 0.5 * this.vScale;
  19440. z -= 0.5;
  19441. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19442. t.x += 0.5 * this.uScale + this.uOffset;
  19443. t.y += 0.5 * this.vScale + this.vOffset;
  19444. t.z += 0.5;
  19445. };
  19446. Texture.prototype.getTextureMatrix = function () {
  19447. var _this = this;
  19448. if (this.uOffset === this._cachedUOffset &&
  19449. this.vOffset === this._cachedVOffset &&
  19450. this.uScale === this._cachedUScale &&
  19451. this.vScale === this._cachedVScale &&
  19452. this.uAng === this._cachedUAng &&
  19453. this.vAng === this._cachedVAng &&
  19454. this.wAng === this._cachedWAng) {
  19455. return this._cachedTextureMatrix;
  19456. }
  19457. this._cachedUOffset = this.uOffset;
  19458. this._cachedVOffset = this.vOffset;
  19459. this._cachedUScale = this.uScale;
  19460. this._cachedVScale = this.vScale;
  19461. this._cachedUAng = this.uAng;
  19462. this._cachedVAng = this.vAng;
  19463. this._cachedWAng = this.wAng;
  19464. if (!this._cachedTextureMatrix) {
  19465. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19466. this._rowGenerationMatrix = new BABYLON.Matrix();
  19467. this._t0 = BABYLON.Vector3.Zero();
  19468. this._t1 = BABYLON.Vector3.Zero();
  19469. this._t2 = BABYLON.Vector3.Zero();
  19470. }
  19471. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19472. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19473. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19474. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19475. this._t1.subtractInPlace(this._t0);
  19476. this._t2.subtractInPlace(this._t0);
  19477. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19478. this._cachedTextureMatrix.m[0] = this._t1.x;
  19479. this._cachedTextureMatrix.m[1] = this._t1.y;
  19480. this._cachedTextureMatrix.m[2] = this._t1.z;
  19481. this._cachedTextureMatrix.m[4] = this._t2.x;
  19482. this._cachedTextureMatrix.m[5] = this._t2.y;
  19483. this._cachedTextureMatrix.m[6] = this._t2.z;
  19484. this._cachedTextureMatrix.m[8] = this._t0.x;
  19485. this._cachedTextureMatrix.m[9] = this._t0.y;
  19486. this._cachedTextureMatrix.m[10] = this._t0.z;
  19487. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19488. return mat.hasTexture(_this);
  19489. });
  19490. return this._cachedTextureMatrix;
  19491. };
  19492. Texture.prototype.getReflectionTextureMatrix = function () {
  19493. var _this = this;
  19494. if (this.uOffset === this._cachedUOffset &&
  19495. this.vOffset === this._cachedVOffset &&
  19496. this.uScale === this._cachedUScale &&
  19497. this.vScale === this._cachedVScale &&
  19498. this.coordinatesMode === this._cachedCoordinatesMode) {
  19499. return this._cachedTextureMatrix;
  19500. }
  19501. if (!this._cachedTextureMatrix) {
  19502. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19503. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19504. }
  19505. this._cachedCoordinatesMode = this.coordinatesMode;
  19506. switch (this.coordinatesMode) {
  19507. case Texture.PLANAR_MODE:
  19508. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19509. this._cachedTextureMatrix[0] = this.uScale;
  19510. this._cachedTextureMatrix[5] = this.vScale;
  19511. this._cachedTextureMatrix[12] = this.uOffset;
  19512. this._cachedTextureMatrix[13] = this.vOffset;
  19513. break;
  19514. case Texture.PROJECTION_MODE:
  19515. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19516. this._projectionModeMatrix.m[0] = 0.5;
  19517. this._projectionModeMatrix.m[5] = -0.5;
  19518. this._projectionModeMatrix.m[10] = 0.0;
  19519. this._projectionModeMatrix.m[12] = 0.5;
  19520. this._projectionModeMatrix.m[13] = 0.5;
  19521. this._projectionModeMatrix.m[14] = 1.0;
  19522. this._projectionModeMatrix.m[15] = 1.0;
  19523. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19524. break;
  19525. default:
  19526. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19527. break;
  19528. }
  19529. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  19530. return (mat.getActiveTextures().indexOf(_this) !== -1);
  19531. });
  19532. return this._cachedTextureMatrix;
  19533. };
  19534. Texture.prototype.clone = function () {
  19535. var _this = this;
  19536. return BABYLON.SerializationHelper.Clone(function () {
  19537. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19538. }, this);
  19539. };
  19540. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19541. get: function () {
  19542. if (!this._onLoadObservable) {
  19543. this._onLoadObservable = new BABYLON.Observable();
  19544. }
  19545. return this._onLoadObservable;
  19546. },
  19547. enumerable: true,
  19548. configurable: true
  19549. });
  19550. // Statics
  19551. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19552. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19553. if (onLoad === void 0) { onLoad = null; }
  19554. if (onError === void 0) { onError = null; }
  19555. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19556. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19557. };
  19558. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19559. if (parsedTexture.customType) {
  19560. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19561. // Update Sampling Mode
  19562. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19563. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19564. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19565. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19566. }
  19567. }
  19568. return parsedCustomTexture;
  19569. }
  19570. if (parsedTexture.isCube) {
  19571. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19572. }
  19573. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19574. return null;
  19575. }
  19576. var texture = BABYLON.SerializationHelper.Parse(function () {
  19577. if (parsedTexture.mirrorPlane) {
  19578. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19579. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19580. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19581. return mirrorTexture;
  19582. }
  19583. else if (parsedTexture.isRenderTarget) {
  19584. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19585. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19586. return renderTargetTexture;
  19587. }
  19588. else {
  19589. var texture;
  19590. if (parsedTexture.base64String) {
  19591. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19592. }
  19593. else {
  19594. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19595. }
  19596. return texture;
  19597. }
  19598. }, parsedTexture, scene);
  19599. // Update Sampling Mode
  19600. if (parsedTexture.samplingMode) {
  19601. var sampling = parsedTexture.samplingMode;
  19602. if (texture._samplingMode !== sampling) {
  19603. texture.updateSamplingMode(sampling);
  19604. }
  19605. }
  19606. // Animations
  19607. if (parsedTexture.animations) {
  19608. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19609. var parsedAnimation = parsedTexture.animations[animationIndex];
  19610. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19611. }
  19612. }
  19613. return texture;
  19614. };
  19615. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19616. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19617. if (noMipmap === void 0) { noMipmap = false; }
  19618. if (invertY === void 0) { invertY = true; }
  19619. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19620. if (onLoad === void 0) { onLoad = null; }
  19621. if (onError === void 0) { onError = null; }
  19622. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19623. if (name.substr(0, 5) !== "data:") {
  19624. name = "data:" + name;
  19625. }
  19626. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19627. };
  19628. return Texture;
  19629. }(BABYLON.BaseTexture));
  19630. // Constants
  19631. Texture.NEAREST_SAMPLINGMODE = 1;
  19632. Texture.BILINEAR_SAMPLINGMODE = 2;
  19633. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19634. Texture.EXPLICIT_MODE = 0;
  19635. Texture.SPHERICAL_MODE = 1;
  19636. Texture.PLANAR_MODE = 2;
  19637. Texture.CUBIC_MODE = 3;
  19638. Texture.PROJECTION_MODE = 4;
  19639. Texture.SKYBOX_MODE = 5;
  19640. Texture.INVCUBIC_MODE = 6;
  19641. Texture.EQUIRECTANGULAR_MODE = 7;
  19642. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19643. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19644. Texture.CLAMP_ADDRESSMODE = 0;
  19645. Texture.WRAP_ADDRESSMODE = 1;
  19646. Texture.MIRROR_ADDRESSMODE = 2;
  19647. __decorate([
  19648. BABYLON.serialize()
  19649. ], Texture.prototype, "url", void 0);
  19650. __decorate([
  19651. BABYLON.serialize()
  19652. ], Texture.prototype, "uOffset", void 0);
  19653. __decorate([
  19654. BABYLON.serialize()
  19655. ], Texture.prototype, "vOffset", void 0);
  19656. __decorate([
  19657. BABYLON.serialize()
  19658. ], Texture.prototype, "uScale", void 0);
  19659. __decorate([
  19660. BABYLON.serialize()
  19661. ], Texture.prototype, "vScale", void 0);
  19662. __decorate([
  19663. BABYLON.serialize()
  19664. ], Texture.prototype, "uAng", void 0);
  19665. __decorate([
  19666. BABYLON.serialize()
  19667. ], Texture.prototype, "vAng", void 0);
  19668. __decorate([
  19669. BABYLON.serialize()
  19670. ], Texture.prototype, "wAng", void 0);
  19671. __decorate([
  19672. BABYLON.serialize()
  19673. ], Texture.prototype, "isBlocking", null);
  19674. BABYLON.Texture = Texture;
  19675. })(BABYLON || (BABYLON = {}));
  19676. //# sourceMappingURL=babylon.texture.js.map
  19677. var BABYLON;
  19678. (function (BABYLON) {
  19679. var _InstancesBatch = (function () {
  19680. function _InstancesBatch() {
  19681. this.mustReturn = false;
  19682. this.visibleInstances = new Array();
  19683. this.renderSelf = new Array();
  19684. }
  19685. return _InstancesBatch;
  19686. }());
  19687. BABYLON._InstancesBatch = _InstancesBatch;
  19688. var Mesh = (function (_super) {
  19689. __extends(Mesh, _super);
  19690. /**
  19691. * @constructor
  19692. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19693. * @param {Scene} scene The scene to add this mesh to.
  19694. * @param {Node} parent The parent of this mesh, if it has one
  19695. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19696. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19697. * When false, achieved by calling a clone(), also passing False.
  19698. * This will make creation of children, recursive.
  19699. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19700. */
  19701. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19702. if (parent === void 0) { parent = null; }
  19703. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19704. var _this = _super.call(this, name, scene) || this;
  19705. // Events
  19706. /**
  19707. * An event triggered before rendering the mesh
  19708. * @type {BABYLON.Observable}
  19709. */
  19710. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19711. /**
  19712. * An event triggered after rendering the mesh
  19713. * @type {BABYLON.Observable}
  19714. */
  19715. _this.onAfterRenderObservable = new BABYLON.Observable();
  19716. /**
  19717. * An event triggered before drawing the mesh
  19718. * @type {BABYLON.Observable}
  19719. */
  19720. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19721. // Members
  19722. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19723. _this.instances = new Array();
  19724. _this._LODLevels = new Array();
  19725. _this._visibleInstances = {};
  19726. _this._renderIdForInstances = new Array();
  19727. _this._batchCache = new _InstancesBatch();
  19728. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19729. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19730. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19731. // Will be used to save a source mesh reference, If any
  19732. _this._source = null;
  19733. if (source) {
  19734. // Source mesh
  19735. _this._source = source;
  19736. // Geometry
  19737. if (source._geometry) {
  19738. source._geometry.applyToMesh(_this);
  19739. }
  19740. // Deep copy
  19741. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19742. // Parent
  19743. _this.parent = source.parent;
  19744. // Pivot
  19745. _this.setPivotMatrix(source.getPivotMatrix());
  19746. _this.id = name + "." + source.id;
  19747. // Material
  19748. _this.material = source.material;
  19749. var index;
  19750. if (!doNotCloneChildren) {
  19751. // Children
  19752. for (index = 0; index < scene.meshes.length; index++) {
  19753. var mesh = scene.meshes[index];
  19754. if (mesh.parent === source) {
  19755. // doNotCloneChildren is always going to be False
  19756. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19757. }
  19758. }
  19759. }
  19760. // Physics clone
  19761. var physicsEngine = _this.getScene().getPhysicsEngine();
  19762. if (clonePhysicsImpostor && physicsEngine) {
  19763. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19764. if (impostor) {
  19765. _this.physicsImpostor = impostor.clone(_this);
  19766. }
  19767. }
  19768. // Particles
  19769. for (index = 0; index < scene.particleSystems.length; index++) {
  19770. var system = scene.particleSystems[index];
  19771. if (system.emitter === source) {
  19772. system.clone(system.name, _this);
  19773. }
  19774. }
  19775. _this.computeWorldMatrix(true);
  19776. }
  19777. // Parent
  19778. if (parent !== null) {
  19779. _this.parent = parent;
  19780. }
  19781. return _this;
  19782. }
  19783. Object.defineProperty(Mesh, "FRONTSIDE", {
  19784. /**
  19785. * Mesh side orientation : usually the external or front surface
  19786. */
  19787. get: function () {
  19788. return Mesh._FRONTSIDE;
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Mesh, "BACKSIDE", {
  19794. /**
  19795. * Mesh side orientation : usually the internal or back surface
  19796. */
  19797. get: function () {
  19798. return Mesh._BACKSIDE;
  19799. },
  19800. enumerable: true,
  19801. configurable: true
  19802. });
  19803. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19804. /**
  19805. * Mesh side orientation : both internal and external or front and back surfaces
  19806. */
  19807. get: function () {
  19808. return Mesh._DOUBLESIDE;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19814. /**
  19815. * Mesh side orientation : by default, `FRONTSIDE`
  19816. */
  19817. get: function () {
  19818. return Mesh._DEFAULTSIDE;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(Mesh, "NO_CAP", {
  19824. /**
  19825. * Mesh cap setting : no cap
  19826. */
  19827. get: function () {
  19828. return Mesh._NO_CAP;
  19829. },
  19830. enumerable: true,
  19831. configurable: true
  19832. });
  19833. Object.defineProperty(Mesh, "CAP_START", {
  19834. /**
  19835. * Mesh cap setting : one cap at the beginning of the mesh
  19836. */
  19837. get: function () {
  19838. return Mesh._CAP_START;
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(Mesh, "CAP_END", {
  19844. /**
  19845. * Mesh cap setting : one cap at the end of the mesh
  19846. */
  19847. get: function () {
  19848. return Mesh._CAP_END;
  19849. },
  19850. enumerable: true,
  19851. configurable: true
  19852. });
  19853. Object.defineProperty(Mesh, "CAP_ALL", {
  19854. /**
  19855. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19856. */
  19857. get: function () {
  19858. return Mesh._CAP_ALL;
  19859. },
  19860. enumerable: true,
  19861. configurable: true
  19862. });
  19863. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19864. set: function (callback) {
  19865. if (this._onBeforeDrawObserver) {
  19866. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19867. }
  19868. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19869. },
  19870. enumerable: true,
  19871. configurable: true
  19872. });
  19873. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19874. get: function () {
  19875. return this._morphTargetManager;
  19876. },
  19877. set: function (value) {
  19878. if (this._morphTargetManager === value) {
  19879. return;
  19880. }
  19881. this._morphTargetManager = value;
  19882. this._syncGeometryWithMorphTargetManager();
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(Mesh.prototype, "source", {
  19888. get: function () {
  19889. return this._source;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. // Methods
  19895. /**
  19896. * Returns the string "Mesh".
  19897. */
  19898. Mesh.prototype.getClassName = function () {
  19899. return "Mesh";
  19900. };
  19901. /**
  19902. * Returns a string.
  19903. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19904. */
  19905. Mesh.prototype.toString = function (fullDetails) {
  19906. var ret = _super.prototype.toString.call(this, fullDetails);
  19907. ret += ", n vertices: " + this.getTotalVertices();
  19908. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19909. if (this.animations) {
  19910. for (var i = 0; i < this.animations.length; i++) {
  19911. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19912. }
  19913. }
  19914. if (fullDetails) {
  19915. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19916. }
  19917. return ret;
  19918. };
  19919. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19920. /**
  19921. * True if the mesh has some Levels Of Details (LOD).
  19922. * Returns a boolean.
  19923. */
  19924. get: function () {
  19925. return this._LODLevels.length > 0;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Mesh.prototype._sortLODLevels = function () {
  19931. this._LODLevels.sort(function (a, b) {
  19932. if (a.distance < b.distance) {
  19933. return 1;
  19934. }
  19935. if (a.distance > b.distance) {
  19936. return -1;
  19937. }
  19938. return 0;
  19939. });
  19940. };
  19941. /**
  19942. * Add a mesh as LOD level triggered at the given distance.
  19943. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19944. * @param {number} distance The distance from the center of the object to show this level
  19945. * @param {Mesh} mesh The mesh to be added as LOD level
  19946. * @return {Mesh} This mesh (for chaining)
  19947. */
  19948. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19949. if (mesh && mesh._masterMesh) {
  19950. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19951. return this;
  19952. }
  19953. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19954. this._LODLevels.push(level);
  19955. if (mesh) {
  19956. mesh._masterMesh = this;
  19957. }
  19958. this._sortLODLevels();
  19959. return this;
  19960. };
  19961. /**
  19962. * Returns the LOD level mesh at the passed distance or null if not found.
  19963. * It is related to the method `addLODLevel(distance, mesh)`.
  19964. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19965. * Returns an object Mesh or `null`.
  19966. */
  19967. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19968. for (var index = 0; index < this._LODLevels.length; index++) {
  19969. var level = this._LODLevels[index];
  19970. if (level.distance === distance) {
  19971. return level.mesh;
  19972. }
  19973. }
  19974. return null;
  19975. };
  19976. /**
  19977. * Remove a mesh from the LOD array
  19978. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19979. * @param {Mesh} mesh The mesh to be removed.
  19980. * @return {Mesh} This mesh (for chaining)
  19981. */
  19982. Mesh.prototype.removeLODLevel = function (mesh) {
  19983. for (var index = 0; index < this._LODLevels.length; index++) {
  19984. if (this._LODLevels[index].mesh === mesh) {
  19985. this._LODLevels.splice(index, 1);
  19986. if (mesh) {
  19987. mesh._masterMesh = null;
  19988. }
  19989. }
  19990. }
  19991. this._sortLODLevels();
  19992. return this;
  19993. };
  19994. /**
  19995. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19996. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19997. */
  19998. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19999. if (!this._LODLevels || this._LODLevels.length === 0) {
  20000. return this;
  20001. }
  20002. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20003. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20004. if (this.onLODLevelSelection) {
  20005. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20006. }
  20007. return this;
  20008. }
  20009. for (var index = 0; index < this._LODLevels.length; index++) {
  20010. var level = this._LODLevels[index];
  20011. if (level.distance < distanceToCamera) {
  20012. if (level.mesh) {
  20013. level.mesh._preActivate();
  20014. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20015. }
  20016. if (this.onLODLevelSelection) {
  20017. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20018. }
  20019. return level.mesh;
  20020. }
  20021. }
  20022. if (this.onLODLevelSelection) {
  20023. this.onLODLevelSelection(distanceToCamera, this, this);
  20024. }
  20025. return this;
  20026. };
  20027. Object.defineProperty(Mesh.prototype, "geometry", {
  20028. /**
  20029. * Returns the mesh internal Geometry object.
  20030. */
  20031. get: function () {
  20032. return this._geometry;
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. /**
  20038. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20039. */
  20040. Mesh.prototype.getTotalVertices = function () {
  20041. if (!this._geometry) {
  20042. return 0;
  20043. }
  20044. return this._geometry.getTotalVertices();
  20045. };
  20046. /**
  20047. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20048. * 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.
  20049. * You can force the copy with forceCopy === true
  20050. * Returns null if the mesh has no geometry or no vertex buffer.
  20051. * Possible `kind` values :
  20052. * - BABYLON.VertexBuffer.PositionKind
  20053. * - BABYLON.VertexBuffer.UVKind
  20054. * - BABYLON.VertexBuffer.UV2Kind
  20055. * - BABYLON.VertexBuffer.UV3Kind
  20056. * - BABYLON.VertexBuffer.UV4Kind
  20057. * - BABYLON.VertexBuffer.UV5Kind
  20058. * - BABYLON.VertexBuffer.UV6Kind
  20059. * - BABYLON.VertexBuffer.ColorKind
  20060. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20061. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20062. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20063. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20064. */
  20065. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  20066. if (!this._geometry) {
  20067. return null;
  20068. }
  20069. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  20070. };
  20071. /**
  20072. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20073. * Returns `undefined` if the mesh has no geometry.
  20074. * Possible `kind` values :
  20075. * - BABYLON.VertexBuffer.PositionKind
  20076. * - BABYLON.VertexBuffer.UVKind
  20077. * - BABYLON.VertexBuffer.UV2Kind
  20078. * - BABYLON.VertexBuffer.UV3Kind
  20079. * - BABYLON.VertexBuffer.UV4Kind
  20080. * - BABYLON.VertexBuffer.UV5Kind
  20081. * - BABYLON.VertexBuffer.UV6Kind
  20082. * - BABYLON.VertexBuffer.ColorKind
  20083. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20084. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20085. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20086. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20087. */
  20088. Mesh.prototype.getVertexBuffer = function (kind) {
  20089. if (!this._geometry) {
  20090. return undefined;
  20091. }
  20092. return this._geometry.getVertexBuffer(kind);
  20093. };
  20094. /**
  20095. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20096. * Possible `kind` values :
  20097. * - BABYLON.VertexBuffer.PositionKind
  20098. * - BABYLON.VertexBuffer.UVKind
  20099. * - BABYLON.VertexBuffer.UV2Kind
  20100. * - BABYLON.VertexBuffer.UV3Kind
  20101. * - BABYLON.VertexBuffer.UV4Kind
  20102. * - BABYLON.VertexBuffer.UV5Kind
  20103. * - BABYLON.VertexBuffer.UV6Kind
  20104. * - BABYLON.VertexBuffer.ColorKind
  20105. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20106. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20107. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20108. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20109. */
  20110. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20111. if (!this._geometry) {
  20112. if (this._delayInfo) {
  20113. return this._delayInfo.indexOf(kind) !== -1;
  20114. }
  20115. return false;
  20116. }
  20117. return this._geometry.isVerticesDataPresent(kind);
  20118. };
  20119. /**
  20120. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20121. * Possible `kind` values :
  20122. * - BABYLON.VertexBuffer.PositionKind
  20123. * - BABYLON.VertexBuffer.UVKind
  20124. * - BABYLON.VertexBuffer.UV2Kind
  20125. * - BABYLON.VertexBuffer.UV3Kind
  20126. * - BABYLON.VertexBuffer.UV4Kind
  20127. * - BABYLON.VertexBuffer.UV5Kind
  20128. * - BABYLON.VertexBuffer.UV6Kind
  20129. * - BABYLON.VertexBuffer.ColorKind
  20130. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20131. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20132. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20133. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20134. */
  20135. Mesh.prototype.getVerticesDataKinds = function () {
  20136. if (!this._geometry) {
  20137. var result = [];
  20138. if (this._delayInfo) {
  20139. this._delayInfo.forEach(function (kind, index, array) {
  20140. result.push(kind);
  20141. });
  20142. }
  20143. return result;
  20144. }
  20145. return this._geometry.getVerticesDataKinds();
  20146. };
  20147. /**
  20148. * Returns a positive integer : the total number of indices in this mesh geometry.
  20149. * Returns zero if the mesh has no geometry.
  20150. */
  20151. Mesh.prototype.getTotalIndices = function () {
  20152. if (!this._geometry) {
  20153. return 0;
  20154. }
  20155. return this._geometry.getTotalIndices();
  20156. };
  20157. /**
  20158. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20159. * 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.
  20160. * Returns an empty array if the mesh has no geometry.
  20161. */
  20162. Mesh.prototype.getIndices = function (copyWhenShared) {
  20163. if (!this._geometry) {
  20164. return [];
  20165. }
  20166. return this._geometry.getIndices(copyWhenShared);
  20167. };
  20168. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20169. get: function () {
  20170. return this._masterMesh !== null && this._masterMesh !== undefined;
  20171. },
  20172. enumerable: true,
  20173. configurable: true
  20174. });
  20175. /**
  20176. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20177. */
  20178. Mesh.prototype.isReady = function () {
  20179. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20180. return false;
  20181. }
  20182. return _super.prototype.isReady.call(this);
  20183. };
  20184. /**
  20185. * Boolean : true if the mesh has been disposed.
  20186. */
  20187. Mesh.prototype.isDisposed = function () {
  20188. return this._isDisposed;
  20189. };
  20190. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20191. get: function () {
  20192. return this._sideOrientation;
  20193. },
  20194. /**
  20195. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20196. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20197. */
  20198. set: function (sideO) {
  20199. this._sideOrientation = sideO;
  20200. },
  20201. enumerable: true,
  20202. configurable: true
  20203. });
  20204. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20205. /**
  20206. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20207. * This property is pertinent only for updatable parametric shapes.
  20208. */
  20209. get: function () {
  20210. return this._areNormalsFrozen;
  20211. },
  20212. enumerable: true,
  20213. configurable: true
  20214. });
  20215. /**
  20216. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20217. * It has no effect at all on other shapes.
  20218. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20219. * Returns the Mesh.
  20220. */
  20221. Mesh.prototype.freezeNormals = function () {
  20222. this._areNormalsFrozen = true;
  20223. return this;
  20224. };
  20225. /**
  20226. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20227. * It has no effect at all on other shapes.
  20228. * It reactivates the mesh normals computation if it was previously frozen.
  20229. * Returns the Mesh.
  20230. */
  20231. Mesh.prototype.unfreezeNormals = function () {
  20232. this._areNormalsFrozen = false;
  20233. return this;
  20234. };
  20235. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20236. /**
  20237. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20238. */
  20239. set: function (count) {
  20240. this._overridenInstanceCount = count;
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. // Methods
  20246. Mesh.prototype._preActivate = function () {
  20247. var sceneRenderId = this.getScene().getRenderId();
  20248. if (this._preActivateId === sceneRenderId) {
  20249. return this;
  20250. }
  20251. this._preActivateId = sceneRenderId;
  20252. this._visibleInstances = null;
  20253. return this;
  20254. };
  20255. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20256. if (this._visibleInstances) {
  20257. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20258. }
  20259. return this;
  20260. };
  20261. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20262. if (!this._visibleInstances) {
  20263. this._visibleInstances = {};
  20264. this._visibleInstances.defaultRenderId = renderId;
  20265. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20266. }
  20267. if (!this._visibleInstances[renderId]) {
  20268. this._visibleInstances[renderId] = new Array();
  20269. }
  20270. this._visibleInstances[renderId].push(instance);
  20271. return this;
  20272. };
  20273. /**
  20274. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20275. * This means the mesh underlying bounding box and sphere are recomputed.
  20276. * Returns the Mesh.
  20277. */
  20278. Mesh.prototype.refreshBoundingInfo = function () {
  20279. if (this._boundingInfo.isLocked) {
  20280. return;
  20281. }
  20282. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20283. if (data) {
  20284. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20285. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20286. }
  20287. if (this.subMeshes) {
  20288. for (var index = 0; index < this.subMeshes.length; index++) {
  20289. this.subMeshes[index].refreshBoundingInfo();
  20290. }
  20291. }
  20292. this._updateBoundingInfo();
  20293. return this;
  20294. };
  20295. Mesh.prototype._createGlobalSubMesh = function () {
  20296. var totalVertices = this.getTotalVertices();
  20297. if (!totalVertices || !this.getIndices()) {
  20298. return null;
  20299. }
  20300. // Check if we need to recreate the submeshes
  20301. if (this.subMeshes && this.subMeshes.length > 0) {
  20302. var totalIndices = this.getIndices().length;
  20303. var needToRecreate = false;
  20304. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20305. var submesh = _a[_i];
  20306. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  20307. needToRecreate = true;
  20308. break;
  20309. }
  20310. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  20311. needToRecreate = true;
  20312. break;
  20313. }
  20314. }
  20315. if (!needToRecreate) {
  20316. return;
  20317. }
  20318. }
  20319. this.releaseSubMeshes();
  20320. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20321. };
  20322. Mesh.prototype.subdivide = function (count) {
  20323. if (count < 1) {
  20324. return;
  20325. }
  20326. var totalIndices = this.getTotalIndices();
  20327. var subdivisionSize = (totalIndices / count) | 0;
  20328. var offset = 0;
  20329. // Ensure that subdivisionSize is a multiple of 3
  20330. while (subdivisionSize % 3 !== 0) {
  20331. subdivisionSize++;
  20332. }
  20333. this.releaseSubMeshes();
  20334. for (var index = 0; index < count; index++) {
  20335. if (offset >= totalIndices) {
  20336. break;
  20337. }
  20338. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20339. offset += subdivisionSize;
  20340. }
  20341. this.synchronizeInstances();
  20342. };
  20343. /**
  20344. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20345. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20346. * The `data` are either a numeric array either a Float32Array.
  20347. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20348. * 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).
  20349. * Note that a new underlying VertexBuffer object is created each call.
  20350. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20351. *
  20352. * Possible `kind` values :
  20353. * - BABYLON.VertexBuffer.PositionKind
  20354. * - BABYLON.VertexBuffer.UVKind
  20355. * - BABYLON.VertexBuffer.UV2Kind
  20356. * - BABYLON.VertexBuffer.UV3Kind
  20357. * - BABYLON.VertexBuffer.UV4Kind
  20358. * - BABYLON.VertexBuffer.UV5Kind
  20359. * - BABYLON.VertexBuffer.UV6Kind
  20360. * - BABYLON.VertexBuffer.ColorKind
  20361. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20362. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20363. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20364. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20365. *
  20366. * Returns the Mesh.
  20367. */
  20368. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20369. if (!this._geometry) {
  20370. var vertexData = new BABYLON.VertexData();
  20371. vertexData.set(data, kind);
  20372. var scene = this.getScene();
  20373. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20374. }
  20375. else {
  20376. this._geometry.setVerticesData(kind, data, updatable, stride);
  20377. }
  20378. return this;
  20379. };
  20380. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20381. if (updatable === void 0) { updatable = true; }
  20382. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20383. return;
  20384. }
  20385. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20386. };
  20387. /**
  20388. * Sets the mesh VertexBuffer.
  20389. * Returns the Mesh.
  20390. */
  20391. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20392. if (!this._geometry) {
  20393. var scene = this.getScene();
  20394. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20395. }
  20396. this._geometry.setVerticesBuffer(buffer);
  20397. return this;
  20398. };
  20399. /**
  20400. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20401. * If the mesh has no geometry, it is simply returned as it is.
  20402. * The `data` are either a numeric array either a Float32Array.
  20403. * No new underlying VertexBuffer object is created.
  20404. * 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.
  20405. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20406. *
  20407. * Possible `kind` values :
  20408. * - BABYLON.VertexBuffer.PositionKind
  20409. * - BABYLON.VertexBuffer.UVKind
  20410. * - BABYLON.VertexBuffer.UV2Kind
  20411. * - BABYLON.VertexBuffer.UV3Kind
  20412. * - BABYLON.VertexBuffer.UV4Kind
  20413. * - BABYLON.VertexBuffer.UV5Kind
  20414. * - BABYLON.VertexBuffer.UV6Kind
  20415. * - BABYLON.VertexBuffer.ColorKind
  20416. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20417. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20418. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20419. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20420. *
  20421. * Returns the Mesh.
  20422. */
  20423. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20424. if (!this._geometry) {
  20425. return;
  20426. }
  20427. if (!makeItUnique) {
  20428. this._geometry.updateVerticesData(kind, data, updateExtends);
  20429. }
  20430. else {
  20431. this.makeGeometryUnique();
  20432. this.updateVerticesData(kind, data, updateExtends, false);
  20433. }
  20434. return this;
  20435. };
  20436. /**
  20437. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20438. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20439. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20440. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20441. * Returns the Mesh.
  20442. */
  20443. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20444. if (computeNormals === void 0) { computeNormals = true; }
  20445. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20446. positionFunction(positions);
  20447. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20448. if (computeNormals) {
  20449. var indices = this.getIndices();
  20450. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20451. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20452. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20453. }
  20454. return this;
  20455. };
  20456. /**
  20457. * Creates a un-shared specific occurence of the geometry for the mesh.
  20458. * Returns the Mesh.
  20459. */
  20460. Mesh.prototype.makeGeometryUnique = function () {
  20461. if (!this._geometry) {
  20462. return;
  20463. }
  20464. var oldGeometry = this._geometry;
  20465. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20466. oldGeometry.releaseForMesh(this, true);
  20467. geometry.applyToMesh(this);
  20468. return this;
  20469. };
  20470. /**
  20471. * Sets the mesh indices.
  20472. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20473. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20474. * This method creates a new index buffer each call.
  20475. * Returns the Mesh.
  20476. */
  20477. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20478. if (!this._geometry) {
  20479. var vertexData = new BABYLON.VertexData();
  20480. vertexData.indices = indices;
  20481. var scene = this.getScene();
  20482. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20483. }
  20484. else {
  20485. this._geometry.setIndices(indices, totalVertices);
  20486. }
  20487. return this;
  20488. };
  20489. /**
  20490. * Invert the geometry to move from a right handed system to a left handed one.
  20491. * Returns the Mesh.
  20492. */
  20493. Mesh.prototype.toLeftHanded = function () {
  20494. if (!this._geometry) {
  20495. return;
  20496. }
  20497. this._geometry.toLeftHanded();
  20498. return this;
  20499. };
  20500. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20501. var engine = this.getScene().getEngine();
  20502. // Wireframe
  20503. var indexToBind;
  20504. if (this._unIndexed) {
  20505. indexToBind = null;
  20506. }
  20507. else {
  20508. switch (fillMode) {
  20509. case BABYLON.Material.PointFillMode:
  20510. indexToBind = null;
  20511. break;
  20512. case BABYLON.Material.WireFrameFillMode:
  20513. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20514. break;
  20515. default:
  20516. case BABYLON.Material.TriangleFillMode:
  20517. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20518. break;
  20519. }
  20520. }
  20521. // VBOs
  20522. this._geometry._bind(effect, indexToBind);
  20523. return this;
  20524. };
  20525. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20526. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20527. return this;
  20528. }
  20529. this.onBeforeDrawObservable.notifyObservers(this);
  20530. var engine = this.getScene().getEngine();
  20531. // Draw order
  20532. switch (fillMode) {
  20533. case BABYLON.Material.PointFillMode:
  20534. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20535. break;
  20536. case BABYLON.Material.WireFrameFillMode:
  20537. if (this._unIndexed) {
  20538. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20539. }
  20540. else {
  20541. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20542. }
  20543. break;
  20544. default:
  20545. if (this._unIndexed) {
  20546. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20547. }
  20548. else {
  20549. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20550. }
  20551. }
  20552. return this;
  20553. };
  20554. /**
  20555. * Registers for this mesh a javascript function called just before the rendering process.
  20556. * This function is passed the current mesh.
  20557. * Return the Mesh.
  20558. */
  20559. Mesh.prototype.registerBeforeRender = function (func) {
  20560. this.onBeforeRenderObservable.add(func);
  20561. return this;
  20562. };
  20563. /**
  20564. * Disposes a previously registered javascript function called before the rendering.
  20565. * This function is passed the current mesh.
  20566. * Returns the Mesh.
  20567. */
  20568. Mesh.prototype.unregisterBeforeRender = function (func) {
  20569. this.onBeforeRenderObservable.removeCallback(func);
  20570. return this;
  20571. };
  20572. /**
  20573. * Registers for this mesh a javascript function called just after the rendering is complete.
  20574. * This function is passed the current mesh.
  20575. * Returns the Mesh.
  20576. */
  20577. Mesh.prototype.registerAfterRender = function (func) {
  20578. this.onAfterRenderObservable.add(func);
  20579. return this;
  20580. };
  20581. /**
  20582. * Disposes a previously registered javascript function called after the rendering.
  20583. * This function is passed the current mesh.
  20584. * Return the Mesh.
  20585. */
  20586. Mesh.prototype.unregisterAfterRender = function (func) {
  20587. this.onAfterRenderObservable.removeCallback(func);
  20588. return this;
  20589. };
  20590. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20591. var scene = this.getScene();
  20592. this._batchCache.mustReturn = false;
  20593. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20594. this._batchCache.visibleInstances[subMeshId] = null;
  20595. if (this._visibleInstances) {
  20596. var currentRenderId = scene.getRenderId();
  20597. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20598. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20599. var selfRenderId = this._renderId;
  20600. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20601. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20602. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20603. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20604. }
  20605. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20606. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20607. this._batchCache.mustReturn = true;
  20608. return this._batchCache;
  20609. }
  20610. if (currentRenderId !== selfRenderId) {
  20611. this._batchCache.renderSelf[subMeshId] = false;
  20612. }
  20613. }
  20614. this._renderIdForInstances[subMeshId] = currentRenderId;
  20615. }
  20616. return this._batchCache;
  20617. };
  20618. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20619. var visibleInstances = batch.visibleInstances[subMesh._id];
  20620. var matricesCount = visibleInstances.length + 1;
  20621. var bufferSize = matricesCount * 16 * 4;
  20622. var currentInstancesBufferSize = this._instancesBufferSize;
  20623. var instancesBuffer = this._instancesBuffer;
  20624. while (this._instancesBufferSize < bufferSize) {
  20625. this._instancesBufferSize *= 2;
  20626. }
  20627. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20628. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20629. }
  20630. var offset = 0;
  20631. var instancesCount = 0;
  20632. var world = this.getWorldMatrix();
  20633. if (batch.renderSelf[subMesh._id]) {
  20634. world.copyToArray(this._instancesData, offset);
  20635. offset += 16;
  20636. instancesCount++;
  20637. }
  20638. if (visibleInstances) {
  20639. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20640. var instance = visibleInstances[instanceIndex];
  20641. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20642. offset += 16;
  20643. instancesCount++;
  20644. }
  20645. }
  20646. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20647. if (instancesBuffer) {
  20648. instancesBuffer.dispose();
  20649. }
  20650. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20651. this._instancesBuffer = instancesBuffer;
  20652. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20653. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20654. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20655. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20656. }
  20657. else {
  20658. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20659. }
  20660. this.geometry._bind(effect);
  20661. this._draw(subMesh, fillMode, instancesCount);
  20662. engine.unbindInstanceAttributes();
  20663. return this;
  20664. };
  20665. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20666. var scene = this.getScene();
  20667. var engine = scene.getEngine();
  20668. if (hardwareInstancedRendering) {
  20669. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20670. }
  20671. else {
  20672. if (batch.renderSelf[subMesh._id]) {
  20673. // Draw
  20674. if (onBeforeDraw) {
  20675. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20676. }
  20677. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20678. }
  20679. if (batch.visibleInstances[subMesh._id]) {
  20680. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20681. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20682. // World
  20683. var world = instance.getWorldMatrix();
  20684. if (onBeforeDraw) {
  20685. onBeforeDraw(true, world, effectiveMaterial);
  20686. }
  20687. // Draw
  20688. this._draw(subMesh, fillMode);
  20689. }
  20690. }
  20691. }
  20692. return this;
  20693. };
  20694. /**
  20695. * Triggers the draw call for the mesh.
  20696. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20697. * Returns the Mesh.
  20698. */
  20699. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20700. var scene = this.getScene();
  20701. // Managing instances
  20702. var batch = this._getInstancesRenderList(subMesh._id);
  20703. if (batch.mustReturn) {
  20704. return this;
  20705. }
  20706. // Checking geometry state
  20707. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20708. return this;
  20709. }
  20710. var callbackIndex;
  20711. this.onBeforeRenderObservable.notifyObservers(this);
  20712. var engine = scene.getEngine();
  20713. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20714. // Material
  20715. var effectiveMaterial = subMesh.getMaterial();
  20716. if (!effectiveMaterial) {
  20717. return this;
  20718. }
  20719. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20720. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20721. return this;
  20722. }
  20723. }
  20724. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20725. return this;
  20726. }
  20727. // Alpha mode
  20728. if (enableAlphaMode) {
  20729. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20730. }
  20731. // Outline - step 1
  20732. var savedDepthWrite = engine.getDepthWrite();
  20733. if (this.renderOutline) {
  20734. engine.setDepthWrite(false);
  20735. scene.getOutlineRenderer().render(subMesh, batch);
  20736. engine.setDepthWrite(savedDepthWrite);
  20737. }
  20738. var effect;
  20739. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20740. effect = subMesh.effect;
  20741. }
  20742. else {
  20743. effect = effectiveMaterial.getEffect();
  20744. }
  20745. effectiveMaterial._preBind(effect);
  20746. // Bind
  20747. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20748. this._bind(subMesh, effect, fillMode);
  20749. var world = this.getWorldMatrix();
  20750. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20751. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20752. }
  20753. else {
  20754. effectiveMaterial.bind(world, this);
  20755. }
  20756. // Draw
  20757. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20758. // Unbind
  20759. effectiveMaterial.unbind();
  20760. // Outline - step 2
  20761. if (this.renderOutline && savedDepthWrite) {
  20762. engine.setDepthWrite(true);
  20763. engine.setColorWrite(false);
  20764. scene.getOutlineRenderer().render(subMesh, batch);
  20765. engine.setColorWrite(true);
  20766. }
  20767. // Overlay
  20768. if (this.renderOverlay) {
  20769. var currentMode = engine.getAlphaMode();
  20770. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20771. scene.getOutlineRenderer().render(subMesh, batch, true);
  20772. engine.setAlphaMode(currentMode);
  20773. }
  20774. this.onAfterRenderObservable.notifyObservers(this);
  20775. return this;
  20776. };
  20777. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20778. if (isInstance) {
  20779. effectiveMaterial.bindOnlyWorldMatrix(world);
  20780. }
  20781. return this;
  20782. };
  20783. /**
  20784. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20785. */
  20786. Mesh.prototype.getEmittedParticleSystems = function () {
  20787. var results = new Array();
  20788. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20789. var particleSystem = this.getScene().particleSystems[index];
  20790. if (particleSystem.emitter === this) {
  20791. results.push(particleSystem);
  20792. }
  20793. }
  20794. return results;
  20795. };
  20796. /**
  20797. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20798. */
  20799. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20800. var results = new Array();
  20801. var descendants = this.getDescendants();
  20802. descendants.push(this);
  20803. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20804. var particleSystem = this.getScene().particleSystems[index];
  20805. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20806. results.push(particleSystem);
  20807. }
  20808. }
  20809. return results;
  20810. };
  20811. Mesh.prototype._checkDelayState = function () {
  20812. var scene = this.getScene();
  20813. if (this._geometry) {
  20814. this._geometry.load(scene);
  20815. }
  20816. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20817. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20818. this._queueLoad(this, scene);
  20819. }
  20820. return this;
  20821. };
  20822. Mesh.prototype._queueLoad = function (mesh, scene) {
  20823. var _this = this;
  20824. scene._addPendingData(mesh);
  20825. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20826. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20827. if (data instanceof ArrayBuffer) {
  20828. _this._delayLoadingFunction(data, _this);
  20829. }
  20830. else {
  20831. _this._delayLoadingFunction(JSON.parse(data), _this);
  20832. }
  20833. _this.instances.forEach(function (instance) {
  20834. instance._syncSubMeshes();
  20835. });
  20836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20837. scene._removePendingData(_this);
  20838. }, function () { }, scene.database, getBinaryData);
  20839. return this;
  20840. };
  20841. /**
  20842. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20843. */
  20844. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20845. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20846. return false;
  20847. }
  20848. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20849. return false;
  20850. }
  20851. this._checkDelayState();
  20852. return true;
  20853. };
  20854. /**
  20855. * Sets the mesh material by the material or multiMaterial `id` property.
  20856. * The material `id` is a string identifying the material or the multiMaterial.
  20857. * This method returns the Mesh.
  20858. */
  20859. Mesh.prototype.setMaterialByID = function (id) {
  20860. var materials = this.getScene().materials;
  20861. var index;
  20862. for (index = materials.length - 1; index > -1; index--) {
  20863. if (materials[index].id === id) {
  20864. this.material = materials[index];
  20865. return this;
  20866. }
  20867. }
  20868. // Multi
  20869. var multiMaterials = this.getScene().multiMaterials;
  20870. for (index = multiMaterials.length - 1; index > -1; index--) {
  20871. if (multiMaterials[index].id === id) {
  20872. this.material = multiMaterials[index];
  20873. return this;
  20874. }
  20875. }
  20876. return this;
  20877. };
  20878. /**
  20879. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20880. */
  20881. Mesh.prototype.getAnimatables = function () {
  20882. var results = [];
  20883. if (this.material) {
  20884. results.push(this.material);
  20885. }
  20886. if (this.skeleton) {
  20887. results.push(this.skeleton);
  20888. }
  20889. return results;
  20890. };
  20891. /**
  20892. * Modifies the mesh geometry according to the passed transformation matrix.
  20893. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20894. * The mesh normals are modified accordingly the same transformation.
  20895. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20896. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20897. * Returns the Mesh.
  20898. */
  20899. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20900. // Position
  20901. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20902. return this;
  20903. }
  20904. var submeshes = this.subMeshes.splice(0);
  20905. this._resetPointsArrayCache();
  20906. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20907. var temp = [];
  20908. var index;
  20909. for (index = 0; index < data.length; index += 3) {
  20910. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20911. }
  20912. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20913. // Normals
  20914. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20915. return this;
  20916. }
  20917. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20918. temp = [];
  20919. for (index = 0; index < data.length; index += 3) {
  20920. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20921. }
  20922. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20923. // flip faces?
  20924. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20925. this.flipFaces();
  20926. }
  20927. // Restore submeshes
  20928. this.releaseSubMeshes();
  20929. this.subMeshes = submeshes;
  20930. return this;
  20931. };
  20932. /**
  20933. * Modifies the mesh geometry according to its own current World Matrix.
  20934. * The mesh World Matrix is then reset.
  20935. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20936. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20937. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20938. * Returns the Mesh.
  20939. */
  20940. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20941. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20942. this.scaling.copyFromFloats(1, 1, 1);
  20943. this.position.copyFromFloats(0, 0, 0);
  20944. this.rotation.copyFromFloats(0, 0, 0);
  20945. //only if quaternion is already set
  20946. if (this.rotationQuaternion) {
  20947. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20948. }
  20949. this._worldMatrix = BABYLON.Matrix.Identity();
  20950. return this;
  20951. };
  20952. Object.defineProperty(Mesh.prototype, "_positions", {
  20953. // Cache
  20954. get: function () {
  20955. if (this._geometry) {
  20956. return this._geometry._positions;
  20957. }
  20958. return null;
  20959. },
  20960. enumerable: true,
  20961. configurable: true
  20962. });
  20963. Mesh.prototype._resetPointsArrayCache = function () {
  20964. if (this._geometry) {
  20965. this._geometry._resetPointsArrayCache();
  20966. }
  20967. return this;
  20968. };
  20969. Mesh.prototype._generatePointsArray = function () {
  20970. if (this._geometry) {
  20971. return this._geometry._generatePointsArray();
  20972. }
  20973. return false;
  20974. };
  20975. /**
  20976. * Returns a new Mesh object generated from the current mesh properties.
  20977. * This method must not get confused with createInstance().
  20978. * The parameter `name` is a string, the name given to the new mesh.
  20979. * The optional parameter `newParent` can be any Node object (default `null`).
  20980. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20981. * 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.
  20982. */
  20983. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20984. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20985. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20986. };
  20987. /**
  20988. * Disposes the mesh.
  20989. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20990. */
  20991. Mesh.prototype.dispose = function (doNotRecurse) {
  20992. var _this = this;
  20993. this.morphTargetManager = undefined;
  20994. if (this._geometry) {
  20995. this._geometry.releaseForMesh(this, true);
  20996. }
  20997. // Sources
  20998. var meshes = this.getScene().meshes;
  20999. meshes.forEach(function (mesh) {
  21000. if (mesh._source && mesh._source === _this) {
  21001. mesh._source = null;
  21002. }
  21003. });
  21004. this._source = null;
  21005. // Instances
  21006. if (this._instancesBuffer) {
  21007. this._instancesBuffer.dispose();
  21008. this._instancesBuffer = null;
  21009. }
  21010. while (this.instances.length) {
  21011. this.instances[0].dispose();
  21012. }
  21013. // Highlight layers.
  21014. var highlightLayers = this.getScene().highlightLayers;
  21015. for (var i = 0; i < highlightLayers.length; i++) {
  21016. var highlightLayer = highlightLayers[i];
  21017. if (highlightLayer) {
  21018. highlightLayer.removeMesh(this);
  21019. highlightLayer.removeExcludedMesh(this);
  21020. }
  21021. }
  21022. _super.prototype.dispose.call(this, doNotRecurse);
  21023. };
  21024. /**
  21025. * Modifies the mesh geometry according to a displacement map.
  21026. * 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.
  21027. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21028. * This method returns nothing.
  21029. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21030. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21031. * 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.
  21032. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21033. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21034. *
  21035. * Returns the Mesh.
  21036. */
  21037. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21038. var _this = this;
  21039. var scene = this.getScene();
  21040. var onload = function (img) {
  21041. // Getting height map data
  21042. var canvas = document.createElement("canvas");
  21043. var context = canvas.getContext("2d");
  21044. var heightMapWidth = img.width;
  21045. var heightMapHeight = img.height;
  21046. canvas.width = heightMapWidth;
  21047. canvas.height = heightMapHeight;
  21048. context.drawImage(img, 0, 0);
  21049. // Create VertexData from map data
  21050. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21051. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21052. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21053. //execute success callback, if set
  21054. if (onSuccess) {
  21055. onSuccess(_this);
  21056. }
  21057. };
  21058. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21059. return this;
  21060. };
  21061. /**
  21062. * Modifies the mesh geometry according to a displacementMap buffer.
  21063. * 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.
  21064. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21065. * This method returns nothing.
  21066. * 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.
  21067. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21068. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21069. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21070. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21071. *
  21072. * Returns the Mesh.
  21073. */
  21074. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21075. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21076. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21077. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21078. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21079. return this;
  21080. }
  21081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21083. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21084. var position = BABYLON.Vector3.Zero();
  21085. var normal = BABYLON.Vector3.Zero();
  21086. var uv = BABYLON.Vector2.Zero();
  21087. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21088. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21089. for (var index = 0; index < positions.length; index += 3) {
  21090. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21091. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21092. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21093. // Compute height
  21094. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21095. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21096. var pos = (u + v * heightMapWidth) * 4;
  21097. var r = buffer[pos] / 255.0;
  21098. var g = buffer[pos + 1] / 255.0;
  21099. var b = buffer[pos + 2] / 255.0;
  21100. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21101. normal.normalize();
  21102. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21103. position = position.add(normal);
  21104. position.toArray(positions, index);
  21105. }
  21106. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21107. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21108. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21109. return this;
  21110. };
  21111. /**
  21112. * Modify the mesh to get a flat shading rendering.
  21113. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21114. * This method returns the Mesh.
  21115. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21116. */
  21117. Mesh.prototype.convertToFlatShadedMesh = function () {
  21118. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21119. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21120. var kinds = this.getVerticesDataKinds();
  21121. var vbs = [];
  21122. var data = [];
  21123. var newdata = [];
  21124. var updatableNormals = false;
  21125. var kindIndex;
  21126. var kind;
  21127. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21128. kind = kinds[kindIndex];
  21129. var vertexBuffer = this.getVertexBuffer(kind);
  21130. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21131. updatableNormals = vertexBuffer.isUpdatable();
  21132. kinds.splice(kindIndex, 1);
  21133. kindIndex--;
  21134. continue;
  21135. }
  21136. vbs[kind] = vertexBuffer;
  21137. data[kind] = vbs[kind].getData();
  21138. newdata[kind] = [];
  21139. }
  21140. // Save previous submeshes
  21141. var previousSubmeshes = this.subMeshes.slice(0);
  21142. var indices = this.getIndices();
  21143. var totalIndices = this.getTotalIndices();
  21144. // Generating unique vertices per face
  21145. var index;
  21146. for (index = 0; index < totalIndices; index++) {
  21147. var vertexIndex = indices[index];
  21148. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21149. kind = kinds[kindIndex];
  21150. var stride = vbs[kind].getStrideSize();
  21151. for (var offset = 0; offset < stride; offset++) {
  21152. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21153. }
  21154. }
  21155. }
  21156. // Updating faces & normal
  21157. var normals = [];
  21158. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21159. for (index = 0; index < totalIndices; index += 3) {
  21160. indices[index] = index;
  21161. indices[index + 1] = index + 1;
  21162. indices[index + 2] = index + 2;
  21163. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21164. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21165. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21166. var p1p2 = p1.subtract(p2);
  21167. var p3p2 = p3.subtract(p2);
  21168. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21169. // Store same normals for every vertex
  21170. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21171. normals.push(normal.x);
  21172. normals.push(normal.y);
  21173. normals.push(normal.z);
  21174. }
  21175. }
  21176. this.setIndices(indices);
  21177. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21178. // Updating vertex buffers
  21179. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21180. kind = kinds[kindIndex];
  21181. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21182. }
  21183. // Updating submeshes
  21184. this.releaseSubMeshes();
  21185. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21186. var previousOne = previousSubmeshes[submeshIndex];
  21187. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21188. }
  21189. this.synchronizeInstances();
  21190. return this;
  21191. };
  21192. /**
  21193. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21194. * In other words, more vertices, no more indices and a single bigger VBO.
  21195. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21196. * Returns the Mesh.
  21197. */
  21198. Mesh.prototype.convertToUnIndexedMesh = function () {
  21199. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21200. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21201. var kinds = this.getVerticesDataKinds();
  21202. var vbs = [];
  21203. var data = [];
  21204. var newdata = [];
  21205. var updatableNormals = false;
  21206. var kindIndex;
  21207. var kind;
  21208. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21209. kind = kinds[kindIndex];
  21210. var vertexBuffer = this.getVertexBuffer(kind);
  21211. vbs[kind] = vertexBuffer;
  21212. data[kind] = vbs[kind].getData();
  21213. newdata[kind] = [];
  21214. }
  21215. // Save previous submeshes
  21216. var previousSubmeshes = this.subMeshes.slice(0);
  21217. var indices = this.getIndices();
  21218. var totalIndices = this.getTotalIndices();
  21219. // Generating unique vertices per face
  21220. var index;
  21221. for (index = 0; index < totalIndices; index++) {
  21222. var vertexIndex = indices[index];
  21223. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21224. kind = kinds[kindIndex];
  21225. var stride = vbs[kind].getStrideSize();
  21226. for (var offset = 0; offset < stride; offset++) {
  21227. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21228. }
  21229. }
  21230. }
  21231. // Updating indices
  21232. for (index = 0; index < totalIndices; index += 3) {
  21233. indices[index] = index;
  21234. indices[index + 1] = index + 1;
  21235. indices[index + 2] = index + 2;
  21236. }
  21237. this.setIndices(indices);
  21238. // Updating vertex buffers
  21239. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21240. kind = kinds[kindIndex];
  21241. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21242. }
  21243. // Updating submeshes
  21244. this.releaseSubMeshes();
  21245. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21246. var previousOne = previousSubmeshes[submeshIndex];
  21247. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21248. }
  21249. this._unIndexed = true;
  21250. this.synchronizeInstances();
  21251. return this;
  21252. };
  21253. /**
  21254. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21255. * This method returns the Mesh.
  21256. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21257. */
  21258. Mesh.prototype.flipFaces = function (flipNormals) {
  21259. if (flipNormals === void 0) { flipNormals = false; }
  21260. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21261. var i;
  21262. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21263. for (i = 0; i < vertex_data.normals.length; i++) {
  21264. vertex_data.normals[i] *= -1;
  21265. }
  21266. }
  21267. var temp;
  21268. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21269. // reassign indices
  21270. temp = vertex_data.indices[i + 1];
  21271. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21272. vertex_data.indices[i + 2] = temp;
  21273. }
  21274. vertex_data.applyToMesh(this);
  21275. return this;
  21276. };
  21277. // Instances
  21278. /**
  21279. * Creates a new InstancedMesh object from the mesh model.
  21280. * An instance shares the same properties and the same material than its model.
  21281. * Only these properties of each instance can then be set individually :
  21282. * - position
  21283. * - rotation
  21284. * - rotationQuaternion
  21285. * - setPivotMatrix
  21286. * - scaling
  21287. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21288. * Warning : this method is not supported for Line mesh and LineSystem
  21289. */
  21290. Mesh.prototype.createInstance = function (name) {
  21291. return new BABYLON.InstancedMesh(name, this);
  21292. };
  21293. /**
  21294. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21295. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21296. * This method returns the Mesh.
  21297. */
  21298. Mesh.prototype.synchronizeInstances = function () {
  21299. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21300. var instance = this.instances[instanceIndex];
  21301. instance._syncSubMeshes();
  21302. }
  21303. return this;
  21304. };
  21305. /**
  21306. * Simplify the mesh according to the given array of settings.
  21307. * Function will return immediately and will simplify async. It returns the Mesh.
  21308. * @param settings a collection of simplification settings.
  21309. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21310. * @param type the type of simplification to run.
  21311. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21312. */
  21313. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21314. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21315. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21316. this.getScene().simplificationQueue.addTask({
  21317. settings: settings,
  21318. parallelProcessing: parallelProcessing,
  21319. mesh: this,
  21320. simplificationType: simplificationType,
  21321. successCallback: successCallback
  21322. });
  21323. return this;
  21324. };
  21325. /**
  21326. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21327. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21328. * This should be used together with the simplification to avoid disappearing triangles.
  21329. * Returns the Mesh.
  21330. * @param successCallback an optional success callback to be called after the optimization finished.
  21331. */
  21332. Mesh.prototype.optimizeIndices = function (successCallback) {
  21333. var _this = this;
  21334. var indices = this.getIndices();
  21335. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21336. var vectorPositions = [];
  21337. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21338. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21339. }
  21340. var dupes = [];
  21341. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21342. var realPos = vectorPositions.length - 1 - iteration;
  21343. var testedPosition = vectorPositions[realPos];
  21344. for (var j = 0; j < realPos; ++j) {
  21345. var againstPosition = vectorPositions[j];
  21346. if (testedPosition.equals(againstPosition)) {
  21347. dupes[realPos] = j;
  21348. break;
  21349. }
  21350. }
  21351. }, function () {
  21352. for (var i = 0; i < indices.length; ++i) {
  21353. indices[i] = dupes[indices[i]] || indices[i];
  21354. }
  21355. //indices are now reordered
  21356. var originalSubMeshes = _this.subMeshes.slice(0);
  21357. _this.setIndices(indices);
  21358. _this.subMeshes = originalSubMeshes;
  21359. if (successCallback) {
  21360. successCallback(_this);
  21361. }
  21362. });
  21363. return this;
  21364. };
  21365. Mesh.prototype.serialize = function (serializationObject) {
  21366. serializationObject.name = this.name;
  21367. serializationObject.id = this.id;
  21368. serializationObject.type = this.getClassName();
  21369. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21370. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21371. }
  21372. serializationObject.position = this.position.asArray();
  21373. if (this.rotationQuaternion) {
  21374. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21375. }
  21376. else if (this.rotation) {
  21377. serializationObject.rotation = this.rotation.asArray();
  21378. }
  21379. serializationObject.scaling = this.scaling.asArray();
  21380. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21381. serializationObject.isEnabled = this.isEnabled();
  21382. serializationObject.isVisible = this.isVisible;
  21383. serializationObject.infiniteDistance = this.infiniteDistance;
  21384. serializationObject.pickable = this.isPickable;
  21385. serializationObject.receiveShadows = this.receiveShadows;
  21386. serializationObject.billboardMode = this.billboardMode;
  21387. serializationObject.visibility = this.visibility;
  21388. serializationObject.checkCollisions = this.checkCollisions;
  21389. serializationObject.isBlocker = this.isBlocker;
  21390. // Parent
  21391. if (this.parent) {
  21392. serializationObject.parentId = this.parent.id;
  21393. }
  21394. // Geometry
  21395. var geometry = this._geometry;
  21396. if (geometry) {
  21397. var geometryId = geometry.id;
  21398. serializationObject.geometryId = geometryId;
  21399. // SubMeshes
  21400. serializationObject.subMeshes = [];
  21401. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21402. var subMesh = this.subMeshes[subIndex];
  21403. serializationObject.subMeshes.push({
  21404. materialIndex: subMesh.materialIndex,
  21405. verticesStart: subMesh.verticesStart,
  21406. verticesCount: subMesh.verticesCount,
  21407. indexStart: subMesh.indexStart,
  21408. indexCount: subMesh.indexCount
  21409. });
  21410. }
  21411. }
  21412. // Material
  21413. if (this.material) {
  21414. serializationObject.materialId = this.material.id;
  21415. }
  21416. else {
  21417. this.material = null;
  21418. }
  21419. // Morph targets
  21420. if (this.morphTargetManager) {
  21421. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21422. }
  21423. // Skeleton
  21424. if (this.skeleton) {
  21425. serializationObject.skeletonId = this.skeleton.id;
  21426. }
  21427. // Physics
  21428. //TODO implement correct serialization for physics impostors.
  21429. if (this.getPhysicsImpostor()) {
  21430. var impostor = this.getPhysicsImpostor();
  21431. serializationObject.physicsMass = impostor.getParam("mass");
  21432. serializationObject.physicsFriction = impostor.getParam("friction");
  21433. serializationObject.physicsRestitution = impostor.getParam("mass");
  21434. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21435. }
  21436. // Metadata
  21437. if (this.metadata) {
  21438. serializationObject.metadata = this.metadata;
  21439. }
  21440. // Instances
  21441. serializationObject.instances = [];
  21442. for (var index = 0; index < this.instances.length; index++) {
  21443. var instance = this.instances[index];
  21444. var serializationInstance = {
  21445. name: instance.name,
  21446. position: instance.position.asArray(),
  21447. scaling: instance.scaling.asArray()
  21448. };
  21449. if (instance.rotationQuaternion) {
  21450. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21451. }
  21452. else if (instance.rotation) {
  21453. serializationInstance.rotation = instance.rotation.asArray();
  21454. }
  21455. serializationObject.instances.push(serializationInstance);
  21456. // Animations
  21457. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21458. serializationInstance.ranges = instance.serializeAnimationRanges();
  21459. }
  21460. //
  21461. // Animations
  21462. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21463. serializationObject.ranges = this.serializeAnimationRanges();
  21464. // Layer mask
  21465. serializationObject.layerMask = this.layerMask;
  21466. // Alpha
  21467. serializationObject.alphaIndex = this.alphaIndex;
  21468. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21469. // Overlay
  21470. serializationObject.overlayAlpha = this.overlayAlpha;
  21471. serializationObject.overlayColor = this.overlayColor.asArray();
  21472. serializationObject.renderOverlay = this.renderOverlay;
  21473. // Fog
  21474. serializationObject.applyFog = this.applyFog;
  21475. // Action Manager
  21476. if (this.actionManager) {
  21477. serializationObject.actions = this.actionManager.serialize(this.name);
  21478. }
  21479. };
  21480. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21481. if (!this.geometry) {
  21482. return;
  21483. }
  21484. this._markSubMeshesAsAttributesDirty();
  21485. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21486. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21487. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21488. this.morphTargetManager = undefined;
  21489. return;
  21490. }
  21491. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21492. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21493. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21494. if (morphTarget.hasNormals) {
  21495. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21496. }
  21497. if (morphTarget.hasTangents) {
  21498. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21499. }
  21500. }
  21501. }
  21502. else {
  21503. var index = 0;
  21504. // Positions
  21505. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21506. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21507. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21508. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21509. }
  21510. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21511. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21512. }
  21513. index++;
  21514. }
  21515. }
  21516. };
  21517. // Statics
  21518. /**
  21519. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21520. * The parameter `parsedMesh` is the mesh to be copied.
  21521. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21522. */
  21523. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21524. var mesh;
  21525. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21526. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21527. }
  21528. else {
  21529. mesh = new Mesh(parsedMesh.name, scene);
  21530. }
  21531. mesh.id = parsedMesh.id;
  21532. if (BABYLON.Tags) {
  21533. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21534. }
  21535. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21536. if (parsedMesh.metadata !== undefined) {
  21537. mesh.metadata = parsedMesh.metadata;
  21538. }
  21539. if (parsedMesh.rotationQuaternion) {
  21540. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21541. }
  21542. else if (parsedMesh.rotation) {
  21543. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21544. }
  21545. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21546. if (parsedMesh.localMatrix) {
  21547. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21548. }
  21549. else if (parsedMesh.pivotMatrix) {
  21550. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21551. }
  21552. mesh.setEnabled(parsedMesh.isEnabled);
  21553. mesh.isVisible = parsedMesh.isVisible;
  21554. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21555. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21556. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21557. if (parsedMesh.applyFog !== undefined) {
  21558. mesh.applyFog = parsedMesh.applyFog;
  21559. }
  21560. if (parsedMesh.pickable !== undefined) {
  21561. mesh.isPickable = parsedMesh.pickable;
  21562. }
  21563. if (parsedMesh.alphaIndex !== undefined) {
  21564. mesh.alphaIndex = parsedMesh.alphaIndex;
  21565. }
  21566. mesh.receiveShadows = parsedMesh.receiveShadows;
  21567. mesh.billboardMode = parsedMesh.billboardMode;
  21568. if (parsedMesh.visibility !== undefined) {
  21569. mesh.visibility = parsedMesh.visibility;
  21570. }
  21571. mesh.checkCollisions = parsedMesh.checkCollisions;
  21572. if (parsedMesh.isBlocker !== undefined) {
  21573. mesh.isBlocker = parsedMesh.isBlocker;
  21574. }
  21575. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21576. // freezeWorldMatrix
  21577. if (parsedMesh.freezeWorldMatrix) {
  21578. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21579. }
  21580. // Parent
  21581. if (parsedMesh.parentId) {
  21582. mesh._waitingParentId = parsedMesh.parentId;
  21583. }
  21584. // Actions
  21585. if (parsedMesh.actions !== undefined) {
  21586. mesh._waitingActions = parsedMesh.actions;
  21587. }
  21588. // Overlay
  21589. if (parsedMesh.overlayAlpha !== undefined) {
  21590. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21591. }
  21592. if (parsedMesh.overlayColor !== undefined) {
  21593. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21594. }
  21595. if (parsedMesh.renderOverlay !== undefined) {
  21596. mesh.renderOverlay = parsedMesh.renderOverlay;
  21597. }
  21598. // Geometry
  21599. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21600. if (parsedMesh.delayLoadingFile) {
  21601. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21602. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21603. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21604. if (parsedMesh._binaryInfo) {
  21605. mesh._binaryInfo = parsedMesh._binaryInfo;
  21606. }
  21607. mesh._delayInfo = [];
  21608. if (parsedMesh.hasUVs) {
  21609. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21610. }
  21611. if (parsedMesh.hasUVs2) {
  21612. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21613. }
  21614. if (parsedMesh.hasUVs3) {
  21615. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21616. }
  21617. if (parsedMesh.hasUVs4) {
  21618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21619. }
  21620. if (parsedMesh.hasUVs5) {
  21621. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21622. }
  21623. if (parsedMesh.hasUVs6) {
  21624. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21625. }
  21626. if (parsedMesh.hasColors) {
  21627. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21628. }
  21629. if (parsedMesh.hasMatricesIndices) {
  21630. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21631. }
  21632. if (parsedMesh.hasMatricesWeights) {
  21633. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21634. }
  21635. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21636. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21637. mesh._checkDelayState();
  21638. }
  21639. }
  21640. else {
  21641. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21642. }
  21643. // Material
  21644. if (parsedMesh.materialId) {
  21645. mesh.setMaterialByID(parsedMesh.materialId);
  21646. }
  21647. else {
  21648. mesh.material = null;
  21649. }
  21650. // Morph targets
  21651. if (parsedMesh.morphTargetManagerId > -1) {
  21652. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21653. }
  21654. // Skeleton
  21655. if (parsedMesh.skeletonId > -1) {
  21656. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21657. if (parsedMesh.numBoneInfluencers) {
  21658. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21659. }
  21660. }
  21661. // Animations
  21662. if (parsedMesh.animations) {
  21663. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21664. var parsedAnimation = parsedMesh.animations[animationIndex];
  21665. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21666. }
  21667. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21668. }
  21669. if (parsedMesh.autoAnimate) {
  21670. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21671. }
  21672. // Layer Mask
  21673. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21674. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21675. }
  21676. else {
  21677. mesh.layerMask = 0x0FFFFFFF;
  21678. }
  21679. // Physics
  21680. if (parsedMesh.physicsImpostor) {
  21681. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21682. mass: parsedMesh.physicsMass,
  21683. friction: parsedMesh.physicsFriction,
  21684. restitution: parsedMesh.physicsRestitution
  21685. }, scene);
  21686. }
  21687. // Instances
  21688. if (parsedMesh.instances) {
  21689. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21690. var parsedInstance = parsedMesh.instances[index];
  21691. var instance = mesh.createInstance(parsedInstance.name);
  21692. if (BABYLON.Tags) {
  21693. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21694. }
  21695. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21696. if (parsedInstance.parentId) {
  21697. instance._waitingParentId = parsedInstance.parentId;
  21698. }
  21699. if (parsedInstance.rotationQuaternion) {
  21700. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21701. }
  21702. else if (parsedInstance.rotation) {
  21703. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21704. }
  21705. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21706. instance.checkCollisions = mesh.checkCollisions;
  21707. if (parsedMesh.animations) {
  21708. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21709. parsedAnimation = parsedMesh.animations[animationIndex];
  21710. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21711. }
  21712. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21713. }
  21714. }
  21715. }
  21716. return mesh;
  21717. };
  21718. /**
  21719. * Creates a ribbon mesh.
  21720. * Please consider using the same method from the MeshBuilder class instead.
  21721. * 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.
  21722. *
  21723. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21724. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21725. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21726. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21727. * 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.
  21728. * 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.
  21729. * 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
  21730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21731. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21733. */
  21734. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21735. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21736. pathArray: pathArray,
  21737. closeArray: closeArray,
  21738. closePath: closePath,
  21739. offset: offset,
  21740. updatable: updatable,
  21741. sideOrientation: sideOrientation,
  21742. instance: instance
  21743. }, scene);
  21744. };
  21745. /**
  21746. * Creates a plane polygonal mesh. By default, this is a disc.
  21747. * Please consider using the same method from the MeshBuilder class instead.
  21748. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21749. * 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.
  21750. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21751. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21752. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21753. */
  21754. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21755. var options = {
  21756. radius: radius,
  21757. tessellation: tessellation,
  21758. sideOrientation: sideOrientation,
  21759. updatable: updatable
  21760. };
  21761. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates a box mesh.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. * The parameter `size` sets the size (float) of each box side (default 1).
  21767. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21768. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21769. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21770. */
  21771. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21772. var options = {
  21773. size: size,
  21774. sideOrientation: sideOrientation,
  21775. updatable: updatable
  21776. };
  21777. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21778. };
  21779. /**
  21780. * Creates a sphere mesh.
  21781. * Please consider using the same method from the MeshBuilder class instead.
  21782. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21783. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21787. */
  21788. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21789. var options = {
  21790. segments: segments,
  21791. diameterX: diameter,
  21792. diameterY: diameter,
  21793. diameterZ: diameter,
  21794. sideOrientation: sideOrientation,
  21795. updatable: updatable
  21796. };
  21797. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21798. };
  21799. /**
  21800. * Creates a cylinder or a cone mesh.
  21801. * Please consider using the same method from the MeshBuilder class instead.
  21802. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21803. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21804. * 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.
  21805. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21806. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21810. */
  21811. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21812. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21813. if (scene !== undefined) {
  21814. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21815. updatable = scene;
  21816. }
  21817. scene = subdivisions;
  21818. subdivisions = 1;
  21819. }
  21820. var options = {
  21821. height: height,
  21822. diameterTop: diameterTop,
  21823. diameterBottom: diameterBottom,
  21824. tessellation: tessellation,
  21825. subdivisions: subdivisions,
  21826. sideOrientation: sideOrientation,
  21827. updatable: updatable
  21828. };
  21829. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21830. };
  21831. // Torus (Code from SharpDX.org)
  21832. /**
  21833. * Creates a torus mesh.
  21834. * Please consider using the same method from the MeshBuilder class instead.
  21835. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21836. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21837. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21841. */
  21842. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21843. var options = {
  21844. diameter: diameter,
  21845. thickness: thickness,
  21846. tessellation: tessellation,
  21847. sideOrientation: sideOrientation,
  21848. updatable: updatable
  21849. };
  21850. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21851. };
  21852. /**
  21853. * Creates a torus knot mesh.
  21854. * Please consider using the same method from the MeshBuilder class instead.
  21855. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21856. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21857. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21858. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21860. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21862. */
  21863. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21864. var options = {
  21865. radius: radius,
  21866. tube: tube,
  21867. radialSegments: radialSegments,
  21868. tubularSegments: tubularSegments,
  21869. p: p,
  21870. q: q,
  21871. sideOrientation: sideOrientation,
  21872. updatable: updatable
  21873. };
  21874. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21875. };
  21876. /**
  21877. * Creates a line mesh.
  21878. * Please consider using the same method from the MeshBuilder class instead.
  21879. * 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.
  21880. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21881. * The parameter `points` is an array successive Vector3.
  21882. * 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
  21883. * When updating an instance, remember that only point positions can change, not the number of points.
  21884. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21885. */
  21886. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21887. var options = {
  21888. points: points,
  21889. updatable: updatable,
  21890. instance: instance
  21891. };
  21892. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21893. };
  21894. /**
  21895. * Creates a dashed line mesh.
  21896. * Please consider using the same method from the MeshBuilder class instead.
  21897. * 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.
  21898. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21899. * The parameter `points` is an array successive Vector3.
  21900. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21901. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21902. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21903. * 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
  21904. * When updating an instance, remember that only point positions can change, not the number of points.
  21905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21906. */
  21907. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21908. var options = {
  21909. points: points,
  21910. dashSize: dashSize,
  21911. gapSize: gapSize,
  21912. dashNb: dashNb,
  21913. updatable: updatable,
  21914. instance: instance
  21915. };
  21916. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21917. };
  21918. /**
  21919. * Creates a polygon mesh.
  21920. * Please consider using the same method from the MeshBuilder class instead.
  21921. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21922. * 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.
  21923. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21925. * Remember you can only change the shape positions, not their number when updating a polygon.
  21926. */
  21927. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21928. var options = {
  21929. shape: shape,
  21930. holes: holes,
  21931. updatable: updatable,
  21932. sideOrientation: sideOrientation
  21933. };
  21934. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21935. };
  21936. /**
  21937. * Creates an extruded polygon mesh, with depth in the Y direction.
  21938. * Please consider using the same method from the MeshBuilder class instead.
  21939. */
  21940. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21941. var options = {
  21942. shape: shape,
  21943. holes: holes,
  21944. depth: depth,
  21945. updatable: updatable,
  21946. sideOrientation: sideOrientation
  21947. };
  21948. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21949. };
  21950. /**
  21951. * Creates an extruded shape mesh.
  21952. * 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.
  21953. * Please consider using the same method from the MeshBuilder class instead.
  21954. *
  21955. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21956. * 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
  21957. * extruded along the Z axis.
  21958. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21959. * 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.
  21960. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21961. * 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
  21962. * 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
  21963. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21964. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21965. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21966. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21967. */
  21968. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21969. var options = {
  21970. shape: shape,
  21971. path: path,
  21972. scale: scale,
  21973. rotation: rotation,
  21974. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21975. sideOrientation: sideOrientation,
  21976. instance: instance,
  21977. updatable: updatable
  21978. };
  21979. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21980. };
  21981. /**
  21982. * Creates an custom extruded shape mesh.
  21983. * 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.
  21984. * Please consider using the same method from the MeshBuilder class instead.
  21985. *
  21986. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21987. * 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
  21988. * extruded along the Z axis.
  21989. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21990. * 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
  21991. * and the distance of this point from the begining of the path :
  21992. * ```javascript
  21993. * var rotationFunction = function(i, distance) {
  21994. * // do things
  21995. * return rotationValue; }
  21996. * ```
  21997. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21998. * 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
  21999. * and the distance of this point from the begining of the path :
  22000. * ```javascript
  22001. * var scaleFunction = function(i, distance) {
  22002. * // do things
  22003. * return scaleValue;}
  22004. * ```
  22005. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22006. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22007. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22008. * 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
  22009. * 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
  22010. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22012. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22014. */
  22015. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22016. var options = {
  22017. shape: shape,
  22018. path: path,
  22019. scaleFunction: scaleFunction,
  22020. rotationFunction: rotationFunction,
  22021. ribbonCloseArray: ribbonCloseArray,
  22022. ribbonClosePath: ribbonClosePath,
  22023. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22024. sideOrientation: sideOrientation,
  22025. instance: instance,
  22026. updatable: updatable
  22027. };
  22028. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22029. };
  22030. /**
  22031. * Creates lathe mesh.
  22032. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22033. * Please consider using the same method from the MeshBuilder class instead.
  22034. * 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
  22035. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22036. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22037. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22038. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22039. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22041. */
  22042. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22043. var options = {
  22044. shape: shape,
  22045. radius: radius,
  22046. tessellation: tessellation,
  22047. sideOrientation: sideOrientation,
  22048. updatable: updatable
  22049. };
  22050. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22051. };
  22052. /**
  22053. * Creates a plane mesh.
  22054. * Please consider using the same method from the MeshBuilder class instead.
  22055. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22059. */
  22060. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22061. var options = {
  22062. size: size,
  22063. width: size,
  22064. height: size,
  22065. sideOrientation: sideOrientation,
  22066. updatable: updatable
  22067. };
  22068. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22069. };
  22070. /**
  22071. * Creates a ground mesh.
  22072. * Please consider using the same method from the MeshBuilder class instead.
  22073. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22074. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22076. */
  22077. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22078. var options = {
  22079. width: width,
  22080. height: height,
  22081. subdivisions: subdivisions,
  22082. updatable: updatable
  22083. };
  22084. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22085. };
  22086. /**
  22087. * Creates a tiled ground mesh.
  22088. * Please consider using the same method from the MeshBuilder class instead.
  22089. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22090. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22091. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22092. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22093. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22094. * numbers of subdivisions on the ground width and height of each tile.
  22095. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22096. */
  22097. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22098. var options = {
  22099. xmin: xmin,
  22100. zmin: zmin,
  22101. xmax: xmax,
  22102. zmax: zmax,
  22103. subdivisions: subdivisions,
  22104. precision: precision,
  22105. updatable: updatable
  22106. };
  22107. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22108. };
  22109. /**
  22110. * Creates a ground mesh from a height map.
  22111. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22112. * Please consider using the same method from the MeshBuilder class instead.
  22113. * The parameter `url` sets the URL of the height map image resource.
  22114. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22115. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22116. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22117. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22118. * 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).
  22119. * This function is passed the newly built mesh :
  22120. * ```javascript
  22121. * function(mesh) { // do things
  22122. * return; }
  22123. * ```
  22124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22125. */
  22126. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22127. var options = {
  22128. width: width,
  22129. height: height,
  22130. subdivisions: subdivisions,
  22131. minHeight: minHeight,
  22132. maxHeight: maxHeight,
  22133. updatable: updatable,
  22134. onReady: onReady
  22135. };
  22136. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22137. };
  22138. /**
  22139. * Creates a tube mesh.
  22140. * 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.
  22141. * Please consider using the same method from the MeshBuilder class instead.
  22142. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22143. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22144. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22145. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22146. * 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.
  22147. * It must return a radius value (positive float) :
  22148. * ```javascript
  22149. * var radiusFunction = function(i, distance) {
  22150. * // do things
  22151. * return radius; }
  22152. * ```
  22153. * 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
  22154. * 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
  22155. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22156. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22158. */
  22159. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22160. var options = {
  22161. path: path,
  22162. radius: radius,
  22163. tessellation: tessellation,
  22164. radiusFunction: radiusFunction,
  22165. arc: 1,
  22166. cap: cap,
  22167. updatable: updatable,
  22168. sideOrientation: sideOrientation,
  22169. instance: instance
  22170. };
  22171. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22172. };
  22173. /**
  22174. * Creates a polyhedron mesh.
  22175. * Please consider using the same method from the MeshBuilder class instead.
  22176. * 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
  22177. * to choose the wanted type.
  22178. * The parameter `size` (positive float, default 1) sets the polygon size.
  22179. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22180. * 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`.
  22181. * 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
  22182. * 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)`).
  22183. * 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
  22184. * 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.
  22185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22186. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22188. */
  22189. Mesh.CreatePolyhedron = function (name, options, scene) {
  22190. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22191. };
  22192. /**
  22193. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22194. * Please consider using the same method from the MeshBuilder class instead.
  22195. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22196. * 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`).
  22197. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22198. * 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.
  22199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22202. */
  22203. Mesh.CreateIcoSphere = function (name, options, scene) {
  22204. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22205. };
  22206. /**
  22207. * Creates a decal mesh.
  22208. * Please consider using the same method from the MeshBuilder class instead.
  22209. * 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.
  22210. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22211. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22212. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22213. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22214. */
  22215. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22216. var options = {
  22217. position: position,
  22218. normal: normal,
  22219. size: size,
  22220. angle: angle
  22221. };
  22222. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22223. };
  22224. // Skeletons
  22225. /**
  22226. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22227. */
  22228. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22229. var source;
  22230. if (!this._sourcePositions) {
  22231. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22232. this._sourcePositions = new Float32Array(source);
  22233. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22234. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22235. }
  22236. }
  22237. return this._sourcePositions;
  22238. };
  22239. /**
  22240. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22241. */
  22242. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22243. var source;
  22244. if (!this._sourceNormals) {
  22245. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22246. this._sourceNormals = new Float32Array(source);
  22247. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22248. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22249. }
  22250. }
  22251. return this._sourceNormals;
  22252. };
  22253. /**
  22254. * Updates the vertex buffer by applying transformation from the bones.
  22255. * Returns the Mesh.
  22256. *
  22257. * @param {skeleton} skeleton to apply
  22258. */
  22259. Mesh.prototype.applySkeleton = function (skeleton) {
  22260. if (!this.geometry) {
  22261. return this;
  22262. }
  22263. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22264. return this;
  22265. }
  22266. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22268. return this;
  22269. }
  22270. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22271. return this;
  22272. }
  22273. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22274. return this;
  22275. }
  22276. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22277. return this;
  22278. }
  22279. if (!this._sourcePositions) {
  22280. var submeshes = this.subMeshes.slice();
  22281. this.setPositionsForCPUSkinning();
  22282. this.subMeshes = submeshes;
  22283. }
  22284. if (!this._sourceNormals) {
  22285. this.setNormalsForCPUSkinning();
  22286. }
  22287. // positionsData checks for not being Float32Array will only pass at most once
  22288. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22289. if (!(positionsData instanceof Float32Array)) {
  22290. positionsData = new Float32Array(positionsData);
  22291. }
  22292. // normalsData checks for not being Float32Array will only pass at most once
  22293. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22294. if (!(normalsData instanceof Float32Array)) {
  22295. normalsData = new Float32Array(normalsData);
  22296. }
  22297. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22298. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22299. var needExtras = this.numBoneInfluencers > 4;
  22300. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22301. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22302. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22303. var tempVector3 = BABYLON.Vector3.Zero();
  22304. var finalMatrix = new BABYLON.Matrix();
  22305. var tempMatrix = new BABYLON.Matrix();
  22306. var matWeightIdx = 0;
  22307. var inf;
  22308. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22309. var weight;
  22310. for (inf = 0; inf < 4; inf++) {
  22311. weight = matricesWeightsData[matWeightIdx + inf];
  22312. if (weight > 0) {
  22313. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22314. finalMatrix.addToSelf(tempMatrix);
  22315. }
  22316. else
  22317. break;
  22318. }
  22319. if (needExtras) {
  22320. for (inf = 0; inf < 4; inf++) {
  22321. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22322. if (weight > 0) {
  22323. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22324. finalMatrix.addToSelf(tempMatrix);
  22325. }
  22326. else
  22327. break;
  22328. }
  22329. }
  22330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22331. tempVector3.toArray(positionsData, index);
  22332. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22333. tempVector3.toArray(normalsData, index);
  22334. finalMatrix.reset();
  22335. }
  22336. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22337. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22338. return this;
  22339. };
  22340. // Tools
  22341. /**
  22342. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22343. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22344. */
  22345. Mesh.MinMax = function (meshes) {
  22346. var minVector = null;
  22347. var maxVector = null;
  22348. meshes.forEach(function (mesh, index, array) {
  22349. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22350. if (!minVector) {
  22351. minVector = boundingBox.minimumWorld;
  22352. maxVector = boundingBox.maximumWorld;
  22353. }
  22354. else {
  22355. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22356. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22357. }
  22358. });
  22359. return {
  22360. min: minVector,
  22361. max: maxVector
  22362. };
  22363. };
  22364. /**
  22365. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22366. */
  22367. Mesh.Center = function (meshesOrMinMaxVector) {
  22368. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22369. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22370. };
  22371. /**
  22372. * Merge the array of meshes into a single mesh for performance reasons.
  22373. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22374. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22375. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22376. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22377. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22378. */
  22379. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22380. if (disposeSource === void 0) { disposeSource = true; }
  22381. var index;
  22382. if (!allow32BitsIndices) {
  22383. var totalVertices = 0;
  22384. // Counting vertices
  22385. for (index = 0; index < meshes.length; index++) {
  22386. if (meshes[index]) {
  22387. totalVertices += meshes[index].getTotalVertices();
  22388. if (totalVertices > 65536) {
  22389. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22390. return null;
  22391. }
  22392. }
  22393. }
  22394. }
  22395. // Merge
  22396. var vertexData;
  22397. var otherVertexData;
  22398. var indiceArray = new Array();
  22399. var source;
  22400. for (index = 0; index < meshes.length; index++) {
  22401. if (meshes[index]) {
  22402. meshes[index].computeWorldMatrix(true);
  22403. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22404. otherVertexData.transform(meshes[index].getWorldMatrix());
  22405. if (vertexData) {
  22406. vertexData.merge(otherVertexData);
  22407. }
  22408. else {
  22409. vertexData = otherVertexData;
  22410. source = meshes[index];
  22411. }
  22412. if (subdivideWithSubMeshes) {
  22413. indiceArray.push(meshes[index].getTotalIndices());
  22414. }
  22415. }
  22416. }
  22417. if (!meshSubclass) {
  22418. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22419. }
  22420. vertexData.applyToMesh(meshSubclass);
  22421. // Setting properties
  22422. meshSubclass.material = source.material;
  22423. meshSubclass.checkCollisions = source.checkCollisions;
  22424. // Cleaning
  22425. if (disposeSource) {
  22426. for (index = 0; index < meshes.length; index++) {
  22427. if (meshes[index]) {
  22428. meshes[index].dispose();
  22429. }
  22430. }
  22431. }
  22432. // Subdivide
  22433. if (subdivideWithSubMeshes) {
  22434. //-- Suppresions du submesh global
  22435. meshSubclass.releaseSubMeshes();
  22436. index = 0;
  22437. var offset = 0;
  22438. //-- aplique la subdivision en fonction du tableau d'indices
  22439. while (index < indiceArray.length) {
  22440. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22441. offset += indiceArray[index];
  22442. index++;
  22443. }
  22444. }
  22445. return meshSubclass;
  22446. };
  22447. return Mesh;
  22448. }(BABYLON.AbstractMesh));
  22449. // Consts
  22450. Mesh._FRONTSIDE = 0;
  22451. Mesh._BACKSIDE = 1;
  22452. Mesh._DOUBLESIDE = 2;
  22453. Mesh._DEFAULTSIDE = 0;
  22454. Mesh._NO_CAP = 0;
  22455. Mesh._CAP_START = 1;
  22456. Mesh._CAP_END = 2;
  22457. Mesh._CAP_ALL = 3;
  22458. BABYLON.Mesh = Mesh;
  22459. })(BABYLON || (BABYLON = {}));
  22460. //# sourceMappingURL=babylon.mesh.js.map
  22461. var BABYLON;
  22462. (function (BABYLON) {
  22463. var BaseSubMesh = (function () {
  22464. function BaseSubMesh() {
  22465. }
  22466. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22467. get: function () {
  22468. return this._materialEffect;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22474. if (this._materialEffect === effect) {
  22475. return;
  22476. }
  22477. this._materialDefines = defines;
  22478. this._materialEffect = effect;
  22479. };
  22480. return BaseSubMesh;
  22481. }());
  22482. BABYLON.BaseSubMesh = BaseSubMesh;
  22483. var SubMesh = (function (_super) {
  22484. __extends(SubMesh, _super);
  22485. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22486. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22487. var _this = _super.call(this) || this;
  22488. _this.materialIndex = materialIndex;
  22489. _this.verticesStart = verticesStart;
  22490. _this.verticesCount = verticesCount;
  22491. _this.indexStart = indexStart;
  22492. _this.indexCount = indexCount;
  22493. _this._renderId = 0;
  22494. _this._mesh = mesh;
  22495. _this._renderingMesh = renderingMesh || mesh;
  22496. mesh.subMeshes.push(_this);
  22497. _this._trianglePlanes = [];
  22498. _this._id = mesh.subMeshes.length - 1;
  22499. if (createBoundingBox) {
  22500. _this.refreshBoundingInfo();
  22501. mesh.computeWorldMatrix(true);
  22502. }
  22503. return _this;
  22504. }
  22505. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22506. get: function () {
  22507. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22508. },
  22509. enumerable: true,
  22510. configurable: true
  22511. });
  22512. /**
  22513. * Returns the submesh BoudingInfo object.
  22514. */
  22515. SubMesh.prototype.getBoundingInfo = function () {
  22516. if (this.IsGlobal) {
  22517. return this._mesh.getBoundingInfo();
  22518. }
  22519. return this._boundingInfo;
  22520. };
  22521. /**
  22522. * Sets the submesh BoundingInfo.
  22523. * Return the SubMesh.
  22524. */
  22525. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22526. this._boundingInfo = boundingInfo;
  22527. return this;
  22528. };
  22529. /**
  22530. * Returns the mesh of the current submesh.
  22531. */
  22532. SubMesh.prototype.getMesh = function () {
  22533. return this._mesh;
  22534. };
  22535. /**
  22536. * Returns the rendering mesh of the submesh.
  22537. */
  22538. SubMesh.prototype.getRenderingMesh = function () {
  22539. return this._renderingMesh;
  22540. };
  22541. /**
  22542. * Returns the submesh material.
  22543. */
  22544. SubMesh.prototype.getMaterial = function () {
  22545. var rootMaterial = this._renderingMesh.material;
  22546. if (rootMaterial && rootMaterial.getSubMaterial) {
  22547. var multiMaterial = rootMaterial;
  22548. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22549. if (this._currentMaterial !== effectiveMaterial) {
  22550. this._currentMaterial = effectiveMaterial;
  22551. if (this._materialDefines) {
  22552. this._materialDefines.markAllAsDirty();
  22553. }
  22554. }
  22555. return effectiveMaterial;
  22556. }
  22557. if (!rootMaterial) {
  22558. return this._mesh.getScene().defaultMaterial;
  22559. }
  22560. return rootMaterial;
  22561. };
  22562. // Methods
  22563. /**
  22564. * Sets a new updated BoundingInfo object to the submesh.
  22565. * Returns the SubMesh.
  22566. */
  22567. SubMesh.prototype.refreshBoundingInfo = function () {
  22568. this._lastColliderWorldVertices = null;
  22569. if (this.IsGlobal) {
  22570. return;
  22571. }
  22572. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22573. if (!data) {
  22574. this._boundingInfo = this._mesh._boundingInfo;
  22575. return;
  22576. }
  22577. var indices = this._renderingMesh.getIndices();
  22578. var extend;
  22579. //is this the only submesh?
  22580. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22581. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22582. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22583. }
  22584. else {
  22585. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22586. }
  22587. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22588. return this;
  22589. };
  22590. SubMesh.prototype._checkCollision = function (collider) {
  22591. return this.getBoundingInfo()._checkCollision(collider);
  22592. };
  22593. /**
  22594. * Updates the submesh BoundingInfo.
  22595. * Returns the Submesh.
  22596. */
  22597. SubMesh.prototype.updateBoundingInfo = function (world) {
  22598. if (!this.getBoundingInfo()) {
  22599. this.refreshBoundingInfo();
  22600. }
  22601. this.getBoundingInfo().update(world);
  22602. return this;
  22603. };
  22604. /**
  22605. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22606. * Boolean returned.
  22607. */
  22608. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22609. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22610. };
  22611. /**
  22612. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22613. * Boolean returned.
  22614. */
  22615. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22616. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22617. };
  22618. /**
  22619. * Renders the submesh.
  22620. * Returns it.
  22621. */
  22622. SubMesh.prototype.render = function (enableAlphaMode) {
  22623. this._renderingMesh.render(this, enableAlphaMode);
  22624. return this;
  22625. };
  22626. /**
  22627. * Returns a new Index Buffer.
  22628. * Type returned : WebGLBuffer.
  22629. */
  22630. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22631. if (!this._linesIndexBuffer) {
  22632. var linesIndices = [];
  22633. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22634. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22635. }
  22636. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22637. this.linesIndexCount = linesIndices.length;
  22638. }
  22639. return this._linesIndexBuffer;
  22640. };
  22641. /**
  22642. * True is the passed Ray intersects the submesh bounding box.
  22643. * Boolean returned.
  22644. */
  22645. SubMesh.prototype.canIntersects = function (ray) {
  22646. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22647. };
  22648. /**
  22649. * Returns an object IntersectionInfo.
  22650. */
  22651. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22652. var intersectInfo = null;
  22653. // LineMesh first as it's also a Mesh...
  22654. if (this._mesh instanceof BABYLON.LinesMesh) {
  22655. var lineMesh = this._mesh;
  22656. // Line test
  22657. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22658. var p0 = positions[indices[index]];
  22659. var p1 = positions[indices[index + 1]];
  22660. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22661. if (length < 0) {
  22662. continue;
  22663. }
  22664. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22665. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22666. if (fastCheck) {
  22667. break;
  22668. }
  22669. }
  22670. }
  22671. }
  22672. else {
  22673. // Triangles test
  22674. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22675. var p0 = positions[indices[index]];
  22676. var p1 = positions[indices[index + 1]];
  22677. var p2 = positions[indices[index + 2]];
  22678. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22679. if (currentIntersectInfo) {
  22680. if (currentIntersectInfo.distance < 0) {
  22681. continue;
  22682. }
  22683. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22684. intersectInfo = currentIntersectInfo;
  22685. intersectInfo.faceId = index / 3;
  22686. if (fastCheck) {
  22687. break;
  22688. }
  22689. }
  22690. }
  22691. }
  22692. }
  22693. return intersectInfo;
  22694. };
  22695. // Clone
  22696. /**
  22697. * Creates a new Submesh from the passed Mesh.
  22698. */
  22699. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22700. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22701. if (!this.IsGlobal) {
  22702. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22703. }
  22704. return result;
  22705. };
  22706. // Dispose
  22707. /**
  22708. * Disposes the Submesh.
  22709. * Returns nothing.
  22710. */
  22711. SubMesh.prototype.dispose = function () {
  22712. if (this._linesIndexBuffer) {
  22713. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22714. this._linesIndexBuffer = null;
  22715. }
  22716. // Remove from mesh
  22717. var index = this._mesh.subMeshes.indexOf(this);
  22718. this._mesh.subMeshes.splice(index, 1);
  22719. };
  22720. // Statics
  22721. /**
  22722. * Creates a new Submesh from the passed parameters :
  22723. * - materialIndex (integer) : the index of the main mesh material.
  22724. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22725. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22726. * - mesh (Mesh) : the main mesh to create the submesh from.
  22727. * - renderingMesh (optional Mesh) : rendering mesh.
  22728. */
  22729. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22730. var minVertexIndex = Number.MAX_VALUE;
  22731. var maxVertexIndex = -Number.MAX_VALUE;
  22732. renderingMesh = renderingMesh || mesh;
  22733. var indices = renderingMesh.getIndices();
  22734. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22735. var vertexIndex = indices[index];
  22736. if (vertexIndex < minVertexIndex)
  22737. minVertexIndex = vertexIndex;
  22738. if (vertexIndex > maxVertexIndex)
  22739. maxVertexIndex = vertexIndex;
  22740. }
  22741. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22742. };
  22743. return SubMesh;
  22744. }(BaseSubMesh));
  22745. BABYLON.SubMesh = SubMesh;
  22746. })(BABYLON || (BABYLON = {}));
  22747. //# sourceMappingURL=babylon.subMesh.js.map
  22748. var BABYLON;
  22749. (function (BABYLON) {
  22750. var EffectFallbacks = (function () {
  22751. function EffectFallbacks() {
  22752. this._defines = {};
  22753. this._currentRank = 32;
  22754. this._maxRank = -1;
  22755. }
  22756. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22757. if (!this._defines[rank]) {
  22758. if (rank < this._currentRank) {
  22759. this._currentRank = rank;
  22760. }
  22761. if (rank > this._maxRank) {
  22762. this._maxRank = rank;
  22763. }
  22764. this._defines[rank] = new Array();
  22765. }
  22766. this._defines[rank].push(define);
  22767. };
  22768. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22769. this._meshRank = rank;
  22770. this._mesh = mesh;
  22771. if (rank < this._currentRank) {
  22772. this._currentRank = rank;
  22773. }
  22774. if (rank > this._maxRank) {
  22775. this._maxRank = rank;
  22776. }
  22777. };
  22778. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22779. get: function () {
  22780. return this._currentRank <= this._maxRank;
  22781. },
  22782. enumerable: true,
  22783. configurable: true
  22784. });
  22785. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22786. // First we try to switch to CPU skinning
  22787. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22788. this._mesh.computeBonesUsingShaders = false;
  22789. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22790. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22791. var scene = this._mesh.getScene();
  22792. for (var index = 0; index < scene.meshes.length; index++) {
  22793. var otherMesh = scene.meshes[index];
  22794. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22795. otherMesh.computeBonesUsingShaders = false;
  22796. }
  22797. }
  22798. }
  22799. else {
  22800. var currentFallbacks = this._defines[this._currentRank];
  22801. if (currentFallbacks) {
  22802. for (var index = 0; index < currentFallbacks.length; index++) {
  22803. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22804. }
  22805. }
  22806. this._currentRank++;
  22807. }
  22808. return currentDefines;
  22809. };
  22810. return EffectFallbacks;
  22811. }());
  22812. BABYLON.EffectFallbacks = EffectFallbacks;
  22813. var EffectCreationOptions = (function () {
  22814. function EffectCreationOptions() {
  22815. }
  22816. return EffectCreationOptions;
  22817. }());
  22818. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22819. var Effect = (function () {
  22820. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22821. var _this = this;
  22822. this.uniqueId = 0;
  22823. this.onCompileObservable = new BABYLON.Observable();
  22824. this.onErrorObservable = new BABYLON.Observable();
  22825. this.onBindObservable = new BABYLON.Observable();
  22826. this._uniformBuffersNames = {};
  22827. this._isReady = false;
  22828. this._compilationError = "";
  22829. this._valueCache = {};
  22830. this.name = baseName;
  22831. if (attributesNamesOrOptions.attributes) {
  22832. var options = attributesNamesOrOptions;
  22833. this._engine = uniformsNamesOrEngine;
  22834. this._attributesNames = options.attributes;
  22835. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22836. this._samplers = options.samplers;
  22837. this.defines = options.defines;
  22838. this.onError = options.onError;
  22839. this.onCompiled = options.onCompiled;
  22840. this._fallbacks = options.fallbacks;
  22841. this._indexParameters = options.indexParameters;
  22842. if (options.uniformBuffersNames) {
  22843. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22844. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22845. }
  22846. }
  22847. }
  22848. else {
  22849. this._engine = engine;
  22850. this.defines = defines;
  22851. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22852. this._samplers = samplers;
  22853. this._attributesNames = attributesNamesOrOptions;
  22854. this.onError = onError;
  22855. this.onCompiled = onCompiled;
  22856. this._indexParameters = indexParameters;
  22857. this._fallbacks = fallbacks;
  22858. }
  22859. this.uniqueId = Effect._uniqueIdSeed++;
  22860. var vertexSource;
  22861. var fragmentSource;
  22862. if (baseName.vertexElement) {
  22863. vertexSource = document.getElementById(baseName.vertexElement);
  22864. if (!vertexSource) {
  22865. vertexSource = baseName.vertexElement;
  22866. }
  22867. }
  22868. else {
  22869. vertexSource = baseName.vertex || baseName;
  22870. }
  22871. if (baseName.fragmentElement) {
  22872. fragmentSource = document.getElementById(baseName.fragmentElement);
  22873. if (!fragmentSource) {
  22874. fragmentSource = baseName.fragmentElement;
  22875. }
  22876. }
  22877. else {
  22878. fragmentSource = baseName.fragment || baseName;
  22879. }
  22880. this._loadVertexShader(vertexSource, function (vertexCode) {
  22881. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22882. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22883. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22884. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22885. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22886. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22887. });
  22888. });
  22889. });
  22890. });
  22891. });
  22892. });
  22893. }
  22894. Object.defineProperty(Effect.prototype, "key", {
  22895. get: function () {
  22896. return this._key;
  22897. },
  22898. enumerable: true,
  22899. configurable: true
  22900. });
  22901. // Properties
  22902. Effect.prototype.isReady = function () {
  22903. return this._isReady;
  22904. };
  22905. Effect.prototype.getEngine = function () {
  22906. return this._engine;
  22907. };
  22908. Effect.prototype.getProgram = function () {
  22909. return this._program;
  22910. };
  22911. Effect.prototype.getAttributesNames = function () {
  22912. return this._attributesNames;
  22913. };
  22914. Effect.prototype.getAttributeLocation = function (index) {
  22915. return this._attributes[index];
  22916. };
  22917. Effect.prototype.getAttributeLocationByName = function (name) {
  22918. var index = this._attributesNames.indexOf(name);
  22919. return this._attributes[index];
  22920. };
  22921. Effect.prototype.getAttributesCount = function () {
  22922. return this._attributes.length;
  22923. };
  22924. Effect.prototype.getUniformIndex = function (uniformName) {
  22925. return this._uniformsNames.indexOf(uniformName);
  22926. };
  22927. Effect.prototype.getUniform = function (uniformName) {
  22928. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22929. };
  22930. Effect.prototype.getSamplers = function () {
  22931. return this._samplers;
  22932. };
  22933. Effect.prototype.getCompilationError = function () {
  22934. return this._compilationError;
  22935. };
  22936. Effect.prototype.getVertexShaderSource = function () {
  22937. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22938. };
  22939. Effect.prototype.getFragmentShaderSource = function () {
  22940. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22941. };
  22942. // Methods
  22943. Effect.prototype.executeWhenCompiled = function (func) {
  22944. var _this = this;
  22945. if (this.isReady()) {
  22946. func(this);
  22947. return;
  22948. }
  22949. var observer = this.onCompileObservable.add(function (effect) {
  22950. _this.onCompileObservable.remove(observer);
  22951. func(effect);
  22952. });
  22953. };
  22954. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22955. // DOM element ?
  22956. if (vertex instanceof HTMLElement) {
  22957. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22958. callback(vertexCode);
  22959. return;
  22960. }
  22961. // Base64 encoded ?
  22962. if (vertex.substr(0, 7) === "base64:") {
  22963. var vertexBinary = window.atob(vertex.substr(7));
  22964. callback(vertexBinary);
  22965. return;
  22966. }
  22967. // Is in local store ?
  22968. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22969. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22970. return;
  22971. }
  22972. var vertexShaderUrl;
  22973. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22974. vertexShaderUrl = vertex;
  22975. }
  22976. else {
  22977. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22978. }
  22979. // Vertex shader
  22980. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22981. };
  22982. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22983. // DOM element ?
  22984. if (fragment instanceof HTMLElement) {
  22985. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22986. callback(fragmentCode);
  22987. return;
  22988. }
  22989. // Base64 encoded ?
  22990. if (fragment.substr(0, 7) === "base64:") {
  22991. var fragmentBinary = window.atob(fragment.substr(7));
  22992. callback(fragmentBinary);
  22993. return;
  22994. }
  22995. // Is in local store ?
  22996. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22997. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22998. return;
  22999. }
  23000. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23001. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23002. return;
  23003. }
  23004. var fragmentShaderUrl;
  23005. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23006. fragmentShaderUrl = fragment;
  23007. }
  23008. else {
  23009. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23010. }
  23011. // Fragment shader
  23012. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23013. };
  23014. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  23015. // Rebuild shaders source code
  23016. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  23017. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  23018. vertexCode = prefix + vertexCode;
  23019. fragmentCode = prefix + fragmentCode;
  23020. // Number lines of shaders source code
  23021. var i = 2;
  23022. var regex = /\n/gm;
  23023. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23024. i = 2;
  23025. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  23026. // Dump shaders name and formatted source code
  23027. if (this.name.vertexElement) {
  23028. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  23029. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  23030. }
  23031. else if (this.name.vertex) {
  23032. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  23033. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  23034. }
  23035. else {
  23036. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  23037. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  23038. }
  23039. };
  23040. ;
  23041. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  23042. var preparedSourceCode = this._processPrecision(sourceCode);
  23043. if (this._engine.webGLVersion == 1) {
  23044. callback(preparedSourceCode);
  23045. return;
  23046. }
  23047. // Already converted
  23048. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  23049. callback(preparedSourceCode.replace("#version 300 es", ""));
  23050. return;
  23051. }
  23052. // Remove extensions
  23053. // #extension GL_OES_standard_derivatives : enable
  23054. // #extension GL_EXT_shader_texture_lod : enable
  23055. // #extension GL_EXT_frag_depth : enable
  23056. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  23057. var result = preparedSourceCode.replace(regex, "");
  23058. // Migrate to GLSL v300
  23059. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  23060. result = result.replace(/attribute[ \t]/g, "in ");
  23061. result = result.replace(/[ \t]attribute/g, " in");
  23062. if (isFragment) {
  23063. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  23064. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  23065. result = result.replace(/texture2D\(/g, "texture(");
  23066. result = result.replace(/textureCube\(/g, "texture(");
  23067. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  23068. result = result.replace(/gl_FragColor/g, "glFragColor");
  23069. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  23070. }
  23071. callback(result);
  23072. };
  23073. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23074. var _this = this;
  23075. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23076. var match = regex.exec(sourceCode);
  23077. var returnValue = new String(sourceCode);
  23078. while (match != null) {
  23079. var includeFile = match[1];
  23080. // Uniform declaration
  23081. if (includeFile.indexOf("__decl__") !== -1) {
  23082. includeFile = includeFile.replace(/__decl__/, "");
  23083. if (this._engine.webGLVersion != 1) {
  23084. includeFile = includeFile.replace(/Vertex/, "Ubo");
  23085. includeFile = includeFile.replace(/Fragment/, "Ubo");
  23086. }
  23087. includeFile = includeFile + "Declaration";
  23088. }
  23089. if (Effect.IncludesShadersStore[includeFile]) {
  23090. // Substitution
  23091. var includeContent = Effect.IncludesShadersStore[includeFile];
  23092. if (match[2]) {
  23093. var splits = match[3].split(",");
  23094. for (var index = 0; index < splits.length; index += 2) {
  23095. var source = new RegExp(splits[index], "g");
  23096. var dest = splits[index + 1];
  23097. includeContent = includeContent.replace(source, dest);
  23098. }
  23099. }
  23100. if (match[4]) {
  23101. var indexString = match[5];
  23102. if (indexString.indexOf("..") !== -1) {
  23103. var indexSplits = indexString.split("..");
  23104. var minIndex = parseInt(indexSplits[0]);
  23105. var maxIndex = parseInt(indexSplits[1]);
  23106. var sourceIncludeContent = includeContent.slice(0);
  23107. includeContent = "";
  23108. if (isNaN(maxIndex)) {
  23109. maxIndex = this._indexParameters[indexSplits[1]];
  23110. }
  23111. for (var i = minIndex; i < maxIndex; i++) {
  23112. if (this._engine.webGLVersion === 1) {
  23113. // Ubo replacement
  23114. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23115. return p1 + "{X}";
  23116. });
  23117. }
  23118. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23119. }
  23120. }
  23121. else {
  23122. if (this._engine.webGLVersion === 1) {
  23123. // Ubo replacement
  23124. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  23125. return p1 + "{X}";
  23126. });
  23127. }
  23128. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23129. }
  23130. }
  23131. // Replace
  23132. returnValue = returnValue.replace(match[0], includeContent);
  23133. }
  23134. else {
  23135. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23136. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23137. Effect.IncludesShadersStore[includeFile] = fileContent;
  23138. _this._processIncludes(returnValue, callback);
  23139. });
  23140. return;
  23141. }
  23142. match = regex.exec(sourceCode);
  23143. }
  23144. callback(returnValue);
  23145. };
  23146. Effect.prototype._processPrecision = function (source) {
  23147. if (source.indexOf("precision highp float") === -1) {
  23148. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23149. source = "precision mediump float;\n" + source;
  23150. }
  23151. else {
  23152. source = "precision highp float;\n" + source;
  23153. }
  23154. }
  23155. else {
  23156. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23157. source = source.replace("precision highp float", "precision mediump float");
  23158. }
  23159. }
  23160. return source;
  23161. };
  23162. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23163. try {
  23164. var engine = this._engine;
  23165. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23166. if (engine.webGLVersion > 1) {
  23167. for (var name in this._uniformBuffersNames) {
  23168. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  23169. }
  23170. }
  23171. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23172. this._attributes = engine.getAttributes(this._program, attributesNames);
  23173. var index;
  23174. for (index = 0; index < this._samplers.length; index++) {
  23175. var sampler = this.getUniform(this._samplers[index]);
  23176. if (sampler == null) {
  23177. this._samplers.splice(index, 1);
  23178. index--;
  23179. }
  23180. }
  23181. engine.bindSamplers(this);
  23182. this._compilationError = "";
  23183. this._isReady = true;
  23184. if (this.onCompiled) {
  23185. this.onCompiled(this);
  23186. }
  23187. this.onCompileObservable.notifyObservers(this);
  23188. }
  23189. catch (e) {
  23190. this._compilationError = e.message;
  23191. // Let's go through fallbacks then
  23192. BABYLON.Tools.Error("Unable to compile effect:");
  23193. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23194. return " " + uniform;
  23195. }));
  23196. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23197. return " " + attribute;
  23198. }));
  23199. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23200. BABYLON.Tools.Error("Error: " + this._compilationError);
  23201. if (fallbacks && fallbacks.isMoreFallbacks) {
  23202. BABYLON.Tools.Error("Trying next fallback.");
  23203. defines = fallbacks.reduce(defines);
  23204. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23205. }
  23206. else {
  23207. if (this.onError) {
  23208. this.onError(this, this._compilationError);
  23209. }
  23210. this.onErrorObservable.notifyObservers(this);
  23211. }
  23212. }
  23213. };
  23214. Object.defineProperty(Effect.prototype, "isSupported", {
  23215. get: function () {
  23216. return this._compilationError === "";
  23217. },
  23218. enumerable: true,
  23219. configurable: true
  23220. });
  23221. Effect.prototype._bindTexture = function (channel, texture) {
  23222. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23223. };
  23224. Effect.prototype.setTexture = function (channel, texture) {
  23225. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23226. };
  23227. Effect.prototype.setTextureArray = function (channel, textures) {
  23228. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23229. var initialPos = this._samplers.indexOf(channel);
  23230. for (var index = 1; index < textures.length; index++) {
  23231. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23232. }
  23233. }
  23234. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23235. };
  23236. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23237. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23238. };
  23239. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23240. var cache = this._valueCache[uniformName];
  23241. var flag = matrix.updateFlag;
  23242. if (cache !== undefined && cache === flag) {
  23243. return false;
  23244. }
  23245. this._valueCache[uniformName] = flag;
  23246. return true;
  23247. };
  23248. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23249. var cache = this._valueCache[uniformName];
  23250. if (!cache) {
  23251. cache = [x, y];
  23252. this._valueCache[uniformName] = cache;
  23253. return true;
  23254. }
  23255. var changed = false;
  23256. if (cache[0] !== x) {
  23257. cache[0] = x;
  23258. changed = true;
  23259. }
  23260. if (cache[1] !== y) {
  23261. cache[1] = y;
  23262. changed = true;
  23263. }
  23264. return changed;
  23265. };
  23266. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23267. var cache = this._valueCache[uniformName];
  23268. if (!cache) {
  23269. cache = [x, y, z];
  23270. this._valueCache[uniformName] = cache;
  23271. return true;
  23272. }
  23273. var changed = false;
  23274. if (cache[0] !== x) {
  23275. cache[0] = x;
  23276. changed = true;
  23277. }
  23278. if (cache[1] !== y) {
  23279. cache[1] = y;
  23280. changed = true;
  23281. }
  23282. if (cache[2] !== z) {
  23283. cache[2] = z;
  23284. changed = true;
  23285. }
  23286. return changed;
  23287. };
  23288. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23289. var cache = this._valueCache[uniformName];
  23290. if (!cache) {
  23291. cache = [x, y, z, w];
  23292. this._valueCache[uniformName] = cache;
  23293. return true;
  23294. }
  23295. var changed = false;
  23296. if (cache[0] !== x) {
  23297. cache[0] = x;
  23298. changed = true;
  23299. }
  23300. if (cache[1] !== y) {
  23301. cache[1] = y;
  23302. changed = true;
  23303. }
  23304. if (cache[2] !== z) {
  23305. cache[2] = z;
  23306. changed = true;
  23307. }
  23308. if (cache[3] !== w) {
  23309. cache[3] = w;
  23310. changed = true;
  23311. }
  23312. return changed;
  23313. };
  23314. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23315. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23316. return;
  23317. }
  23318. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23319. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23320. };
  23321. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23322. this._engine.bindUniformBlock(this._program, blockName, index);
  23323. };
  23324. Effect.prototype.setIntArray = function (uniformName, array) {
  23325. this._valueCache[uniformName] = null;
  23326. this._engine.setIntArray(this.getUniform(uniformName), array);
  23327. return this;
  23328. };
  23329. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23330. this._valueCache[uniformName] = null;
  23331. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23332. return this;
  23333. };
  23334. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23335. this._valueCache[uniformName] = null;
  23336. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23337. return this;
  23338. };
  23339. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23340. this._valueCache[uniformName] = null;
  23341. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23342. return this;
  23343. };
  23344. Effect.prototype.setFloatArray = function (uniformName, array) {
  23345. this._valueCache[uniformName] = null;
  23346. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23347. return this;
  23348. };
  23349. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23350. this._valueCache[uniformName] = null;
  23351. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23352. return this;
  23353. };
  23354. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23355. this._valueCache[uniformName] = null;
  23356. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23357. return this;
  23358. };
  23359. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23360. this._valueCache[uniformName] = null;
  23361. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23362. return this;
  23363. };
  23364. Effect.prototype.setArray = function (uniformName, array) {
  23365. this._valueCache[uniformName] = null;
  23366. this._engine.setArray(this.getUniform(uniformName), array);
  23367. return this;
  23368. };
  23369. Effect.prototype.setArray2 = function (uniformName, array) {
  23370. this._valueCache[uniformName] = null;
  23371. this._engine.setArray2(this.getUniform(uniformName), array);
  23372. return this;
  23373. };
  23374. Effect.prototype.setArray3 = function (uniformName, array) {
  23375. this._valueCache[uniformName] = null;
  23376. this._engine.setArray3(this.getUniform(uniformName), array);
  23377. return this;
  23378. };
  23379. Effect.prototype.setArray4 = function (uniformName, array) {
  23380. this._valueCache[uniformName] = null;
  23381. this._engine.setArray4(this.getUniform(uniformName), array);
  23382. return this;
  23383. };
  23384. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23385. if (!matrices) {
  23386. return;
  23387. }
  23388. this._valueCache[uniformName] = null;
  23389. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23390. return this;
  23391. };
  23392. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23393. if (this._cacheMatrix(uniformName, matrix)) {
  23394. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23395. }
  23396. return this;
  23397. };
  23398. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23399. this._valueCache[uniformName] = null;
  23400. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23401. return this;
  23402. };
  23403. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23404. this._valueCache[uniformName] = null;
  23405. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23406. return this;
  23407. };
  23408. Effect.prototype.setFloat = function (uniformName, value) {
  23409. var cache = this._valueCache[uniformName];
  23410. if (cache !== undefined && cache === value)
  23411. return this;
  23412. this._valueCache[uniformName] = value;
  23413. this._engine.setFloat(this.getUniform(uniformName), value);
  23414. return this;
  23415. };
  23416. Effect.prototype.setBool = function (uniformName, bool) {
  23417. var cache = this._valueCache[uniformName];
  23418. if (cache !== undefined && cache === bool)
  23419. return this;
  23420. this._valueCache[uniformName] = bool;
  23421. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23422. return this;
  23423. };
  23424. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23425. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23426. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23427. }
  23428. return this;
  23429. };
  23430. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23431. if (this._cacheFloat2(uniformName, x, y)) {
  23432. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23433. }
  23434. return this;
  23435. };
  23436. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23437. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23438. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23439. }
  23440. return this;
  23441. };
  23442. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23443. if (this._cacheFloat3(uniformName, x, y, z)) {
  23444. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23445. }
  23446. return this;
  23447. };
  23448. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23449. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23450. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23451. }
  23452. return this;
  23453. };
  23454. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23455. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23456. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23457. }
  23458. return this;
  23459. };
  23460. Effect.prototype.setColor3 = function (uniformName, color3) {
  23461. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23462. this._engine.setColor3(this.getUniform(uniformName), color3);
  23463. }
  23464. return this;
  23465. };
  23466. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23467. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23468. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23469. }
  23470. return this;
  23471. };
  23472. Effect.prototype._recombineShader = function (node) {
  23473. if (node.define) {
  23474. if (node.condition) {
  23475. var defineIndex = this.defines.indexOf("#define " + node.define);
  23476. if (defineIndex === -1) {
  23477. return null;
  23478. }
  23479. var nextComma = this.defines.indexOf("\n", defineIndex);
  23480. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23481. var condition = defineValue + node.condition;
  23482. if (!eval(condition)) {
  23483. return null;
  23484. }
  23485. }
  23486. else if (node.ndef) {
  23487. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23488. return null;
  23489. }
  23490. }
  23491. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23492. return null;
  23493. }
  23494. }
  23495. var result = "";
  23496. for (var index = 0; index < node.children.length; index++) {
  23497. var line = node.children[index];
  23498. if (line.children) {
  23499. var combined = this._recombineShader(line);
  23500. if (combined !== null) {
  23501. result += combined + "\r\n";
  23502. }
  23503. continue;
  23504. }
  23505. if (line.length > 0) {
  23506. result += line + "\r\n";
  23507. }
  23508. }
  23509. return result;
  23510. };
  23511. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23512. var root = {
  23513. children: []
  23514. };
  23515. var currentNode = root;
  23516. var lines = shaderString.split("\n");
  23517. for (var index = 0; index < lines.length; index++) {
  23518. var line = lines[index].trim();
  23519. // #ifdef
  23520. var pos = line.indexOf("#ifdef ");
  23521. if (pos !== -1) {
  23522. var define = line.substr(pos + 7);
  23523. var newNode = {
  23524. condition: null,
  23525. ndef: false,
  23526. define: define,
  23527. children: [],
  23528. parent: currentNode
  23529. };
  23530. currentNode.children.push(newNode);
  23531. currentNode = newNode;
  23532. continue;
  23533. }
  23534. // #ifndef
  23535. var pos = line.indexOf("#ifndef ");
  23536. if (pos !== -1) {
  23537. var define = line.substr(pos + 8);
  23538. newNode = {
  23539. condition: null,
  23540. define: define,
  23541. ndef: true,
  23542. children: [],
  23543. parent: currentNode
  23544. };
  23545. currentNode.children.push(newNode);
  23546. currentNode = newNode;
  23547. continue;
  23548. }
  23549. // #if
  23550. var pos = line.indexOf("#if ");
  23551. if (pos !== -1) {
  23552. var define = line.substr(pos + 4).trim();
  23553. var conditionPos = define.indexOf(" ");
  23554. newNode = {
  23555. condition: define.substr(conditionPos + 1),
  23556. define: define.substr(0, conditionPos),
  23557. ndef: false,
  23558. children: [],
  23559. parent: currentNode
  23560. };
  23561. currentNode.children.push(newNode);
  23562. currentNode = newNode;
  23563. continue;
  23564. }
  23565. // #endif
  23566. pos = line.indexOf("#endif");
  23567. if (pos !== -1) {
  23568. currentNode = currentNode.parent;
  23569. continue;
  23570. }
  23571. currentNode.children.push(line);
  23572. }
  23573. // Recombine
  23574. return this._recombineShader(root);
  23575. };
  23576. return Effect;
  23577. }());
  23578. Effect._uniqueIdSeed = 0;
  23579. Effect._baseCache = {};
  23580. // Statics
  23581. Effect.ShadersStore = {};
  23582. Effect.IncludesShadersStore = {};
  23583. BABYLON.Effect = Effect;
  23584. })(BABYLON || (BABYLON = {}));
  23585. //# sourceMappingURL=babylon.effect.js.map
  23586. var BABYLON;
  23587. (function (BABYLON) {
  23588. var MaterialHelper = (function () {
  23589. function MaterialHelper() {
  23590. }
  23591. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  23592. defines._needUVs = true;
  23593. defines[key] = true;
  23594. if (texture.getTextureMatrix().isIdentity(true)) {
  23595. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  23596. if (texture.coordinatesIndex === 0) {
  23597. defines["MAINUV1"] = true;
  23598. }
  23599. else {
  23600. defines["MAINUV2"] = true;
  23601. }
  23602. }
  23603. else {
  23604. defines[key + "DIRECTUV"] = 0;
  23605. }
  23606. };
  23607. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  23608. var matrix = texture.getTextureMatrix();
  23609. if (!matrix.isIdentity(true)) {
  23610. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  23611. }
  23612. };
  23613. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23614. if (defines._areMiscDirty) {
  23615. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23616. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23617. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23618. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23619. }
  23620. };
  23621. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23622. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23623. var changed = false;
  23624. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23625. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23626. changed = true;
  23627. }
  23628. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23629. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23630. changed = true;
  23631. }
  23632. if (defines["INSTANCES"] !== useInstances) {
  23633. defines["INSTANCES"] = useInstances;
  23634. changed = true;
  23635. }
  23636. if (changed) {
  23637. defines.markAsUnprocessed();
  23638. }
  23639. };
  23640. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23641. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23642. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23643. return false;
  23644. }
  23645. defines._normals = defines._needNormals;
  23646. defines._uvs = defines._needUVs;
  23647. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23648. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23649. defines["TANGENT"] = true;
  23650. }
  23651. if (defines._needUVs) {
  23652. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23653. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23654. }
  23655. else {
  23656. defines["UV1"] = false;
  23657. defines["UV2"] = false;
  23658. }
  23659. if (useVertexColor) {
  23660. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23661. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23662. }
  23663. if (useBones) {
  23664. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23665. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23666. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23667. }
  23668. else {
  23669. defines["NUM_BONE_INFLUENCERS"] = 0;
  23670. defines["BonesPerMesh"] = 0;
  23671. }
  23672. }
  23673. if (useMorphTargets) {
  23674. if (mesh.morphTargetManager) {
  23675. var manager = mesh.morphTargetManager;
  23676. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23677. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23678. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23679. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23680. }
  23681. else {
  23682. defines["MORPHTARGETS_TANGENT"] = false;
  23683. defines["MORPHTARGETS_NORMAL"] = false;
  23684. defines["MORPHTARGETS"] = false;
  23685. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23686. }
  23687. }
  23688. return true;
  23689. };
  23690. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23691. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23692. if (disableLighting === void 0) { disableLighting = false; }
  23693. if (!defines._areLightsDirty) {
  23694. return defines._needNormals;
  23695. }
  23696. var lightIndex = 0;
  23697. var needNormals = false;
  23698. var needRebuild = false;
  23699. var lightmapMode = false;
  23700. var shadowEnabled = false;
  23701. var specularEnabled = false;
  23702. if (scene.lightsEnabled && !disableLighting) {
  23703. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23704. var light = _a[_i];
  23705. needNormals = true;
  23706. if (defines["LIGHT" + lightIndex] === undefined) {
  23707. needRebuild = true;
  23708. }
  23709. defines["LIGHT" + lightIndex] = true;
  23710. defines["SPOTLIGHT" + lightIndex] = false;
  23711. defines["HEMILIGHT" + lightIndex] = false;
  23712. defines["POINTLIGHT" + lightIndex] = false;
  23713. defines["DIRLIGHT" + lightIndex] = false;
  23714. var type;
  23715. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23716. type = "SPOTLIGHT" + lightIndex;
  23717. }
  23718. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23719. type = "HEMILIGHT" + lightIndex;
  23720. }
  23721. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23722. type = "POINTLIGHT" + lightIndex;
  23723. }
  23724. else {
  23725. type = "DIRLIGHT" + lightIndex;
  23726. }
  23727. defines[type] = true;
  23728. // Specular
  23729. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23730. specularEnabled = true;
  23731. }
  23732. // Shadows
  23733. defines["SHADOW" + lightIndex] = false;
  23734. defines["SHADOWPCF" + lightIndex] = false;
  23735. defines["SHADOWESM" + lightIndex] = false;
  23736. defines["SHADOWCUBE" + lightIndex] = false;
  23737. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23738. var shadowGenerator = light.getShadowGenerator();
  23739. if (shadowGenerator) {
  23740. shadowEnabled = true;
  23741. shadowGenerator.prepareDefines(defines, lightIndex);
  23742. }
  23743. }
  23744. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23745. lightmapMode = true;
  23746. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23747. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23748. }
  23749. else {
  23750. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23751. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23752. }
  23753. lightIndex++;
  23754. if (lightIndex === maxSimultaneousLights)
  23755. break;
  23756. }
  23757. }
  23758. defines["SPECULARTERM"] = specularEnabled;
  23759. defines["SHADOWS"] = shadowEnabled;
  23760. // Resetting all other lights if any
  23761. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23762. if (defines["LIGHT" + index] !== undefined) {
  23763. defines["LIGHT" + index] = false;
  23764. defines["HEMILIGHT" + lightIndex] = false;
  23765. defines["POINTLIGHT" + lightIndex] = false;
  23766. defines["DIRLIGHT" + lightIndex] = false;
  23767. defines["SPOTLIGHT" + lightIndex] = false;
  23768. defines["SHADOW" + lightIndex] = false;
  23769. }
  23770. }
  23771. var caps = scene.getEngine().getCaps();
  23772. if (defines["SHADOWFLOAT"] === undefined) {
  23773. needRebuild = true;
  23774. }
  23775. defines["SHADOWFLOAT"] = shadowEnabled &&
  23776. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23777. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23778. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23779. if (needRebuild) {
  23780. defines.rebuild();
  23781. }
  23782. return needNormals;
  23783. };
  23784. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23785. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23786. var uniformsList, uniformBuffersList, samplersList, defines;
  23787. if (uniformsListOrOptions.uniformsNames) {
  23788. var options = uniformsListOrOptions;
  23789. uniformsList = options.uniformsNames;
  23790. uniformBuffersList = options.uniformBuffersNames;
  23791. samplersList = options.samplers;
  23792. defines = options.defines;
  23793. maxSimultaneousLights = options.maxSimultaneousLights;
  23794. }
  23795. else {
  23796. uniformsList = uniformsListOrOptions;
  23797. }
  23798. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23799. if (!defines["LIGHT" + lightIndex]) {
  23800. break;
  23801. }
  23802. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23803. if (uniformBuffersList) {
  23804. uniformBuffersList.push("Light" + lightIndex);
  23805. }
  23806. samplersList.push("shadowSampler" + lightIndex);
  23807. }
  23808. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23809. uniformsList.push("morphTargetInfluences");
  23810. }
  23811. };
  23812. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23813. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23814. if (!defines["SHADOWS"]) {
  23815. return;
  23816. }
  23817. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23818. if (!defines["LIGHT" + lightIndex]) {
  23819. break;
  23820. }
  23821. if (lightIndex > 0) {
  23822. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23823. }
  23824. if (defines["SHADOW" + lightIndex]) {
  23825. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23826. }
  23827. if (defines["SHADOWPCF" + lightIndex]) {
  23828. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23829. }
  23830. if (defines["SHADOWESM" + lightIndex]) {
  23831. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23832. }
  23833. }
  23834. };
  23835. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23836. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23837. if (influencers > 0) {
  23838. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23839. var manager = mesh.morphTargetManager;
  23840. var normal = manager.supportsNormals && defines["NORMAL"];
  23841. var tangent = manager.supportsTangents && defines["TANGENT"];
  23842. for (var index = 0; index < influencers; index++) {
  23843. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23844. if (normal) {
  23845. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23846. }
  23847. if (tangent) {
  23848. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23849. }
  23850. if (attribs.length > maxAttributesCount) {
  23851. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23852. }
  23853. }
  23854. }
  23855. };
  23856. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23857. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23858. fallbacks.addCPUSkinningFallback(0, mesh);
  23859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23861. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23864. }
  23865. }
  23866. };
  23867. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23868. if (defines["INSTANCES"]) {
  23869. attribs.push("world0");
  23870. attribs.push("world1");
  23871. attribs.push("world2");
  23872. attribs.push("world3");
  23873. }
  23874. };
  23875. // Bindings
  23876. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23877. if (light.shadowEnabled && mesh.receiveShadows) {
  23878. var shadowGenerator = light.getShadowGenerator();
  23879. if (shadowGenerator) {
  23880. shadowGenerator.bindShadowLight(lightIndex, effect);
  23881. }
  23882. }
  23883. };
  23884. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23885. light.transferToEffect(effect, lightIndex + "");
  23886. };
  23887. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23888. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23889. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23890. var lightIndex = 0;
  23891. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23892. var light = _a[_i];
  23893. var scaledIntensity = light.getScaledIntensity();
  23894. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23895. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23896. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23897. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23898. if (defines["SPECULARTERM"]) {
  23899. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23900. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23901. }
  23902. // Shadows
  23903. if (scene.shadowsEnabled) {
  23904. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23905. }
  23906. light._uniformBuffer.update();
  23907. lightIndex++;
  23908. if (lightIndex === maxSimultaneousLights)
  23909. break;
  23910. }
  23911. };
  23912. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23913. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23914. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23915. effect.setColor3("vFogColor", scene.fogColor);
  23916. }
  23917. };
  23918. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23919. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23920. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23921. if (matrices) {
  23922. effect.setMatrices("mBones", matrices);
  23923. }
  23924. }
  23925. };
  23926. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23927. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23928. return;
  23929. }
  23930. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23931. };
  23932. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23933. if (defines["LOGARITHMICDEPTH"]) {
  23934. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23935. }
  23936. };
  23937. MaterialHelper.BindClipPlane = function (effect, scene) {
  23938. if (scene.clipPlane) {
  23939. var clipPlane = scene.clipPlane;
  23940. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23941. }
  23942. };
  23943. return MaterialHelper;
  23944. }());
  23945. BABYLON.MaterialHelper = MaterialHelper;
  23946. })(BABYLON || (BABYLON = {}));
  23947. //# sourceMappingURL=babylon.materialHelper.js.map
  23948. var BABYLON;
  23949. (function (BABYLON) {
  23950. var MaterialDefines = (function () {
  23951. function MaterialDefines() {
  23952. this._isDirty = true;
  23953. this._areLightsDirty = true;
  23954. this._areAttributesDirty = true;
  23955. this._areTexturesDirty = true;
  23956. this._areFresnelDirty = true;
  23957. this._areMiscDirty = true;
  23958. this._areImageProcessingDirty = true;
  23959. this._normals = false;
  23960. this._uvs = false;
  23961. this._needNormals = false;
  23962. this._needUVs = false;
  23963. }
  23964. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23965. get: function () {
  23966. return this._isDirty;
  23967. },
  23968. enumerable: true,
  23969. configurable: true
  23970. });
  23971. MaterialDefines.prototype.markAsProcessed = function () {
  23972. this._isDirty = false;
  23973. this._areAttributesDirty = false;
  23974. this._areTexturesDirty = false;
  23975. this._areFresnelDirty = false;
  23976. this._areLightsDirty = false;
  23977. this._areMiscDirty = false;
  23978. this._areImageProcessingDirty = false;
  23979. };
  23980. MaterialDefines.prototype.markAsUnprocessed = function () {
  23981. this._isDirty = true;
  23982. };
  23983. MaterialDefines.prototype.markAllAsDirty = function () {
  23984. this._areTexturesDirty = true;
  23985. this._areAttributesDirty = true;
  23986. this._areLightsDirty = true;
  23987. this._areFresnelDirty = true;
  23988. this._areMiscDirty = true;
  23989. this._areImageProcessingDirty = true;
  23990. this._isDirty = true;
  23991. };
  23992. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23993. this._areImageProcessingDirty = true;
  23994. this._isDirty = true;
  23995. };
  23996. MaterialDefines.prototype.markAsLightDirty = function () {
  23997. this._areLightsDirty = true;
  23998. this._isDirty = true;
  23999. };
  24000. MaterialDefines.prototype.markAsAttributesDirty = function () {
  24001. this._areAttributesDirty = true;
  24002. this._isDirty = true;
  24003. };
  24004. MaterialDefines.prototype.markAsTexturesDirty = function () {
  24005. this._areTexturesDirty = true;
  24006. this._isDirty = true;
  24007. };
  24008. MaterialDefines.prototype.markAsFresnelDirty = function () {
  24009. this._areFresnelDirty = true;
  24010. this._isDirty = true;
  24011. };
  24012. MaterialDefines.prototype.markAsMiscDirty = function () {
  24013. this._areMiscDirty = true;
  24014. this._isDirty = true;
  24015. };
  24016. MaterialDefines.prototype.rebuild = function () {
  24017. if (this._keys) {
  24018. delete this._keys;
  24019. }
  24020. this._keys = [];
  24021. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  24022. var key = _a[_i];
  24023. if (key[0] === "_") {
  24024. continue;
  24025. }
  24026. this._keys.push(key);
  24027. }
  24028. };
  24029. MaterialDefines.prototype.isEqual = function (other) {
  24030. if (this._keys.length !== other._keys.length) {
  24031. return false;
  24032. }
  24033. for (var index = 0; index < this._keys.length; index++) {
  24034. var prop = this._keys[index];
  24035. if (this[prop] !== other[prop]) {
  24036. return false;
  24037. }
  24038. }
  24039. return true;
  24040. };
  24041. MaterialDefines.prototype.cloneTo = function (other) {
  24042. if (this._keys.length !== other._keys.length) {
  24043. other._keys = this._keys.slice(0);
  24044. }
  24045. for (var index = 0; index < this._keys.length; index++) {
  24046. var prop = this._keys[index];
  24047. other[prop] = this[prop];
  24048. }
  24049. };
  24050. MaterialDefines.prototype.reset = function () {
  24051. for (var index = 0; index < this._keys.length; index++) {
  24052. var prop = this._keys[index];
  24053. if (typeof (this[prop]) === "number") {
  24054. this[prop] = 0;
  24055. }
  24056. else {
  24057. this[prop] = false;
  24058. }
  24059. }
  24060. };
  24061. MaterialDefines.prototype.toString = function () {
  24062. var result = "";
  24063. for (var index = 0; index < this._keys.length; index++) {
  24064. var prop = this._keys[index];
  24065. var value = this[prop];
  24066. if (typeof (value) === "number") {
  24067. result += "#define " + prop + " " + this[prop] + "\n";
  24068. }
  24069. else if (value) {
  24070. result += "#define " + prop + "\n";
  24071. }
  24072. }
  24073. return result;
  24074. };
  24075. return MaterialDefines;
  24076. }());
  24077. BABYLON.MaterialDefines = MaterialDefines;
  24078. var Material = (function () {
  24079. function Material(name, scene, doNotAdd) {
  24080. this.checkReadyOnEveryCall = false;
  24081. this.checkReadyOnlyOnce = false;
  24082. this.state = "";
  24083. this.alpha = 1.0;
  24084. this._backFaceCulling = true;
  24085. this.doNotSerialize = false;
  24086. this.storeEffectOnSubMeshes = false;
  24087. /**
  24088. * An event triggered when the material is disposed.
  24089. * @type {BABYLON.Observable}
  24090. */
  24091. this.onDisposeObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered when the material is bound.
  24094. * @type {BABYLON.Observable}
  24095. */
  24096. this.onBindObservable = new BABYLON.Observable();
  24097. /**
  24098. * An event triggered when the material is unbound.
  24099. * @type {BABYLON.Observable}
  24100. */
  24101. this.onUnBindObservable = new BABYLON.Observable();
  24102. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24103. this.disableDepthWrite = false;
  24104. this._fogEnabled = true;
  24105. this.pointSize = 1.0;
  24106. this.zOffset = 0;
  24107. this._wasPreviouslyReady = false;
  24108. this._fillMode = Material.TriangleFillMode;
  24109. this.name = name;
  24110. this.id = name;
  24111. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24112. if (this._scene.useRightHandedSystem) {
  24113. this.sideOrientation = Material.ClockWiseSideOrientation;
  24114. }
  24115. else {
  24116. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24117. }
  24118. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  24119. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  24120. if (!doNotAdd) {
  24121. this._scene.materials.push(this);
  24122. }
  24123. }
  24124. Object.defineProperty(Material, "TriangleFillMode", {
  24125. get: function () {
  24126. return Material._TriangleFillMode;
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. Object.defineProperty(Material, "WireFrameFillMode", {
  24132. get: function () {
  24133. return Material._WireFrameFillMode;
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(Material, "PointFillMode", {
  24139. get: function () {
  24140. return Material._PointFillMode;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24146. get: function () {
  24147. return Material._ClockWiseSideOrientation;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24153. get: function () {
  24154. return Material._CounterClockWiseSideOrientation;
  24155. },
  24156. enumerable: true,
  24157. configurable: true
  24158. });
  24159. Object.defineProperty(Material, "TextureDirtyFlag", {
  24160. get: function () {
  24161. return Material._TextureDirtyFlag;
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. Object.defineProperty(Material, "LightDirtyFlag", {
  24167. get: function () {
  24168. return Material._LightDirtyFlag;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(Material, "FresnelDirtyFlag", {
  24174. get: function () {
  24175. return Material._FresnelDirtyFlag;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. Object.defineProperty(Material, "AttributesDirtyFlag", {
  24181. get: function () {
  24182. return Material._AttributesDirtyFlag;
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(Material, "MiscDirtyFlag", {
  24188. get: function () {
  24189. return Material._MiscDirtyFlag;
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24195. get: function () {
  24196. return this._backFaceCulling;
  24197. },
  24198. set: function (value) {
  24199. if (this._backFaceCulling === value) {
  24200. return;
  24201. }
  24202. this._backFaceCulling = value;
  24203. this.markAsDirty(Material.TextureDirtyFlag);
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Material.prototype, "onDispose", {
  24209. set: function (callback) {
  24210. if (this._onDisposeObserver) {
  24211. this.onDisposeObservable.remove(this._onDisposeObserver);
  24212. }
  24213. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24214. },
  24215. enumerable: true,
  24216. configurable: true
  24217. });
  24218. Object.defineProperty(Material.prototype, "onBind", {
  24219. set: function (callback) {
  24220. if (this._onBindObserver) {
  24221. this.onBindObservable.remove(this._onBindObserver);
  24222. }
  24223. this._onBindObserver = this.onBindObservable.add(callback);
  24224. },
  24225. enumerable: true,
  24226. configurable: true
  24227. });
  24228. Object.defineProperty(Material.prototype, "fogEnabled", {
  24229. get: function () {
  24230. return this._fogEnabled;
  24231. },
  24232. set: function (value) {
  24233. if (this._fogEnabled === value) {
  24234. return;
  24235. }
  24236. this._fogEnabled = value;
  24237. this.markAsDirty(Material.MiscDirtyFlag);
  24238. },
  24239. enumerable: true,
  24240. configurable: true
  24241. });
  24242. Object.defineProperty(Material.prototype, "wireframe", {
  24243. get: function () {
  24244. return this._fillMode === Material.WireFrameFillMode;
  24245. },
  24246. set: function (value) {
  24247. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24248. },
  24249. enumerable: true,
  24250. configurable: true
  24251. });
  24252. Object.defineProperty(Material.prototype, "pointsCloud", {
  24253. get: function () {
  24254. return this._fillMode === Material.PointFillMode;
  24255. },
  24256. set: function (value) {
  24257. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. Object.defineProperty(Material.prototype, "fillMode", {
  24263. get: function () {
  24264. return this._fillMode;
  24265. },
  24266. set: function (value) {
  24267. if (this._fillMode === value) {
  24268. return;
  24269. }
  24270. this._fillMode = value;
  24271. this.markAsDirty(Material.MiscDirtyFlag);
  24272. },
  24273. enumerable: true,
  24274. configurable: true
  24275. });
  24276. /**
  24277. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24278. * subclasses should override adding information pertainent to themselves
  24279. */
  24280. Material.prototype.toString = function (fullDetails) {
  24281. var ret = "Name: " + this.name;
  24282. if (fullDetails) {
  24283. }
  24284. return ret;
  24285. };
  24286. /**
  24287. * Child classes can use it to update shaders
  24288. */
  24289. Material.prototype.getClassName = function () {
  24290. return "Material";
  24291. };
  24292. Object.defineProperty(Material.prototype, "isFrozen", {
  24293. get: function () {
  24294. return this.checkReadyOnlyOnce;
  24295. },
  24296. enumerable: true,
  24297. configurable: true
  24298. });
  24299. Material.prototype.freeze = function () {
  24300. this.checkReadyOnlyOnce = true;
  24301. };
  24302. Material.prototype.unfreeze = function () {
  24303. this.checkReadyOnlyOnce = false;
  24304. };
  24305. Material.prototype.isReady = function (mesh, useInstances) {
  24306. return true;
  24307. };
  24308. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24309. return false;
  24310. };
  24311. Material.prototype.getEffect = function () {
  24312. return this._effect;
  24313. };
  24314. Material.prototype.getScene = function () {
  24315. return this._scene;
  24316. };
  24317. Material.prototype.needAlphaBlending = function () {
  24318. return (this.alpha < 1.0);
  24319. };
  24320. Material.prototype.needAlphaTesting = function () {
  24321. return false;
  24322. };
  24323. Material.prototype.getAlphaTestTexture = function () {
  24324. return null;
  24325. };
  24326. Material.prototype.markDirty = function () {
  24327. this._wasPreviouslyReady = false;
  24328. };
  24329. Material.prototype._preBind = function (effect) {
  24330. var engine = this._scene.getEngine();
  24331. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24332. engine.enableEffect(effect ? effect : this._effect);
  24333. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24334. };
  24335. Material.prototype.bind = function (world, mesh) {
  24336. };
  24337. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24338. };
  24339. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24340. };
  24341. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24342. sceneUbo.bindToEffect(effect, "Scene");
  24343. };
  24344. Material.prototype.bindView = function (effect) {
  24345. if (!this._useUBO) {
  24346. effect.setMatrix("view", this.getScene().getViewMatrix());
  24347. }
  24348. else {
  24349. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24350. }
  24351. };
  24352. Material.prototype.bindViewProjection = function (effect) {
  24353. if (!this._useUBO) {
  24354. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24355. }
  24356. else {
  24357. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24358. }
  24359. };
  24360. Material.prototype._afterBind = function (mesh) {
  24361. this._scene._cachedMaterial = this;
  24362. this.onBindObservable.notifyObservers(mesh);
  24363. if (this.disableDepthWrite) {
  24364. var engine = this._scene.getEngine();
  24365. this._cachedDepthWriteState = engine.getDepthWrite();
  24366. engine.setDepthWrite(false);
  24367. }
  24368. };
  24369. Material.prototype.unbind = function () {
  24370. this.onUnBindObservable.notifyObservers(this);
  24371. if (this.disableDepthWrite) {
  24372. var engine = this._scene.getEngine();
  24373. engine.setDepthWrite(this._cachedDepthWriteState);
  24374. }
  24375. };
  24376. Material.prototype.getActiveTextures = function () {
  24377. return [];
  24378. };
  24379. Material.prototype.hasTexture = function (texture) {
  24380. return false;
  24381. };
  24382. Material.prototype.clone = function (name) {
  24383. return null;
  24384. };
  24385. Material.prototype.getBindedMeshes = function () {
  24386. var result = new Array();
  24387. for (var index = 0; index < this._scene.meshes.length; index++) {
  24388. var mesh = this._scene.meshes[index];
  24389. if (mesh.material === this) {
  24390. result.push(mesh);
  24391. }
  24392. }
  24393. return result;
  24394. };
  24395. // Force shader compilation including textures ready check
  24396. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24397. var _this = this;
  24398. var subMesh = new BABYLON.BaseSubMesh();
  24399. var scene = this.getScene();
  24400. var engine = scene.getEngine();
  24401. var beforeRenderCallback = function () {
  24402. if (subMesh._materialDefines) {
  24403. subMesh._materialDefines._renderId = -1;
  24404. }
  24405. var alphaTestState = engine.getAlphaTesting();
  24406. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24407. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24408. scene.unregisterBeforeRender(beforeRenderCallback);
  24409. if (onCompiled) {
  24410. onCompiled(_this);
  24411. }
  24412. }
  24413. engine.setAlphaTesting(alphaTestState);
  24414. };
  24415. scene.registerBeforeRender(beforeRenderCallback);
  24416. };
  24417. Material.prototype.markAsDirty = function (flag) {
  24418. if (flag & Material.TextureDirtyFlag) {
  24419. this._markAllSubMeshesAsTexturesDirty();
  24420. }
  24421. if (flag & Material.LightDirtyFlag) {
  24422. this._markAllSubMeshesAsLightsDirty();
  24423. }
  24424. if (flag & Material.FresnelDirtyFlag) {
  24425. this._markAllSubMeshesAsFresnelDirty();
  24426. }
  24427. if (flag & Material.AttributesDirtyFlag) {
  24428. this._markAllSubMeshesAsAttributesDirty();
  24429. }
  24430. if (flag & Material.MiscDirtyFlag) {
  24431. this._markAllSubMeshesAsMiscDirty();
  24432. }
  24433. this.getScene().resetCachedMaterial();
  24434. };
  24435. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24436. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24437. var mesh = _a[_i];
  24438. if (!mesh.subMeshes) {
  24439. continue;
  24440. }
  24441. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24442. var subMesh = _c[_b];
  24443. if (subMesh.getMaterial() !== this) {
  24444. continue;
  24445. }
  24446. if (!subMesh._materialDefines) {
  24447. return;
  24448. }
  24449. func(subMesh._materialDefines);
  24450. }
  24451. }
  24452. };
  24453. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24454. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24455. };
  24456. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24457. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24458. };
  24459. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24460. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24461. };
  24462. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24463. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24464. };
  24465. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24466. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24467. };
  24468. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24469. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24470. };
  24471. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24472. // Animations
  24473. this.getScene().stopAnimation(this);
  24474. // Remove from scene
  24475. var index = this._scene.materials.indexOf(this);
  24476. if (index >= 0) {
  24477. this._scene.materials.splice(index, 1);
  24478. }
  24479. // Remove from meshes
  24480. for (index = 0; index < this._scene.meshes.length; index++) {
  24481. var mesh = this._scene.meshes[index];
  24482. if (mesh.material === this) {
  24483. mesh.material = null;
  24484. if (mesh.geometry) {
  24485. var geometry = mesh.geometry;
  24486. if (this.storeEffectOnSubMeshes) {
  24487. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24488. var subMesh = _a[_i];
  24489. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24490. }
  24491. }
  24492. else {
  24493. geometry._releaseVertexArrayObject(this._effect);
  24494. }
  24495. }
  24496. }
  24497. }
  24498. this._uniformBuffer.dispose();
  24499. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24500. if (forceDisposeEffect && this._effect) {
  24501. if (this.storeEffectOnSubMeshes) {
  24502. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24503. var subMesh = _c[_b];
  24504. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24505. }
  24506. }
  24507. else {
  24508. this._scene.getEngine()._releaseEffect(this._effect);
  24509. }
  24510. this._effect = null;
  24511. }
  24512. // Callback
  24513. this.onDisposeObservable.notifyObservers(this);
  24514. this.onDisposeObservable.clear();
  24515. this.onBindObservable.clear();
  24516. this.onUnBindObservable.clear();
  24517. };
  24518. Material.prototype.serialize = function () {
  24519. return BABYLON.SerializationHelper.Serialize(this);
  24520. };
  24521. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24522. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24523. multiMaterial.id = parsedMultiMaterial.id;
  24524. if (BABYLON.Tags) {
  24525. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24526. }
  24527. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24528. var subMatId = parsedMultiMaterial.materials[matIndex];
  24529. if (subMatId) {
  24530. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24531. }
  24532. else {
  24533. multiMaterial.subMaterials.push(null);
  24534. }
  24535. }
  24536. return multiMaterial;
  24537. };
  24538. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24539. if (!parsedMaterial.customType) {
  24540. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24541. }
  24542. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24543. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24544. if (!BABYLON.LegacyPBRMaterial) {
  24545. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24546. return;
  24547. }
  24548. }
  24549. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24550. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24551. ;
  24552. };
  24553. return Material;
  24554. }());
  24555. Material._TriangleFillMode = 0;
  24556. Material._WireFrameFillMode = 1;
  24557. Material._PointFillMode = 2;
  24558. Material._ClockWiseSideOrientation = 0;
  24559. Material._CounterClockWiseSideOrientation = 1;
  24560. Material._TextureDirtyFlag = 1;
  24561. Material._LightDirtyFlag = 2;
  24562. Material._FresnelDirtyFlag = 4;
  24563. Material._AttributesDirtyFlag = 8;
  24564. Material._MiscDirtyFlag = 16;
  24565. __decorate([
  24566. BABYLON.serialize()
  24567. ], Material.prototype, "id", void 0);
  24568. __decorate([
  24569. BABYLON.serialize()
  24570. ], Material.prototype, "name", void 0);
  24571. __decorate([
  24572. BABYLON.serialize()
  24573. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24574. __decorate([
  24575. BABYLON.serialize()
  24576. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24577. __decorate([
  24578. BABYLON.serialize()
  24579. ], Material.prototype, "state", void 0);
  24580. __decorate([
  24581. BABYLON.serialize()
  24582. ], Material.prototype, "alpha", void 0);
  24583. __decorate([
  24584. BABYLON.serialize("backFaceCulling")
  24585. ], Material.prototype, "_backFaceCulling", void 0);
  24586. __decorate([
  24587. BABYLON.serialize()
  24588. ], Material.prototype, "sideOrientation", void 0);
  24589. __decorate([
  24590. BABYLON.serialize()
  24591. ], Material.prototype, "alphaMode", void 0);
  24592. __decorate([
  24593. BABYLON.serialize()
  24594. ], Material.prototype, "disableDepthWrite", void 0);
  24595. __decorate([
  24596. BABYLON.serialize("fogEnabled")
  24597. ], Material.prototype, "_fogEnabled", void 0);
  24598. __decorate([
  24599. BABYLON.serialize()
  24600. ], Material.prototype, "pointSize", void 0);
  24601. __decorate([
  24602. BABYLON.serialize()
  24603. ], Material.prototype, "zOffset", void 0);
  24604. __decorate([
  24605. BABYLON.serialize()
  24606. ], Material.prototype, "wireframe", null);
  24607. __decorate([
  24608. BABYLON.serialize()
  24609. ], Material.prototype, "pointsCloud", null);
  24610. __decorate([
  24611. BABYLON.serialize()
  24612. ], Material.prototype, "fillMode", null);
  24613. BABYLON.Material = Material;
  24614. })(BABYLON || (BABYLON = {}));
  24615. //# sourceMappingURL=babylon.material.js.map
  24616. var BABYLON;
  24617. (function (BABYLON) {
  24618. var UniformBuffer = (function () {
  24619. /**
  24620. * Uniform buffer objects.
  24621. *
  24622. * Handles blocks of uniform on the GPU.
  24623. *
  24624. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24625. *
  24626. * For more information, please refer to :
  24627. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24628. */
  24629. function UniformBuffer(engine, data, dynamic) {
  24630. this._engine = engine;
  24631. this._noUBO = engine.webGLVersion === 1;
  24632. this._dynamic = dynamic;
  24633. this._data = data || [];
  24634. this._uniformLocations = {};
  24635. this._uniformSizes = {};
  24636. this._uniformLocationPointer = 0;
  24637. this._needSync = false;
  24638. if (this._noUBO) {
  24639. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24640. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24641. this.updateFloat = this._updateFloatForEffect;
  24642. this.updateFloat2 = this._updateFloat2ForEffect;
  24643. this.updateFloat3 = this._updateFloat3ForEffect;
  24644. this.updateFloat4 = this._updateFloat4ForEffect;
  24645. this.updateMatrix = this._updateMatrixForEffect;
  24646. this.updateVector3 = this._updateVector3ForEffect;
  24647. this.updateVector4 = this._updateVector4ForEffect;
  24648. this.updateColor3 = this._updateColor3ForEffect;
  24649. this.updateColor4 = this._updateColor4ForEffect;
  24650. }
  24651. else {
  24652. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24653. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24654. this.updateFloat = this._updateFloatForUniform;
  24655. this.updateFloat2 = this._updateFloat2ForUniform;
  24656. this.updateFloat3 = this._updateFloat3ForUniform;
  24657. this.updateFloat4 = this._updateFloat4ForUniform;
  24658. this.updateMatrix = this._updateMatrixForUniform;
  24659. this.updateVector3 = this._updateVector3ForUniform;
  24660. this.updateVector4 = this._updateVector4ForUniform;
  24661. this.updateColor3 = this._updateColor3ForUniform;
  24662. this.updateColor4 = this._updateColor4ForUniform;
  24663. }
  24664. }
  24665. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24666. // Properties
  24667. /**
  24668. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24669. * or just falling back on setUniformXXX calls.
  24670. */
  24671. get: function () {
  24672. return !this._noUBO;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24678. /**
  24679. * Indicates if the WebGL underlying uniform buffer is in sync
  24680. * with the javascript cache data.
  24681. */
  24682. get: function () {
  24683. return !this._needSync;
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. /**
  24689. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24690. * Also, a dynamic UniformBuffer will disable cache verification and always
  24691. * update the underlying WebGL uniform buffer to the GPU.
  24692. */
  24693. UniformBuffer.prototype.isDynamic = function () {
  24694. return this._dynamic;
  24695. };
  24696. /**
  24697. * The data cache on JS side.
  24698. */
  24699. UniformBuffer.prototype.getData = function () {
  24700. return this._bufferData;
  24701. };
  24702. /**
  24703. * The underlying WebGL Uniform buffer.
  24704. */
  24705. UniformBuffer.prototype.getBuffer = function () {
  24706. return this._buffer;
  24707. };
  24708. /**
  24709. * std140 layout specifies how to align data within an UBO structure.
  24710. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24711. * for specs.
  24712. */
  24713. UniformBuffer.prototype._fillAlignment = function (size) {
  24714. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24715. // and 4x4 matrices
  24716. // TODO : change if other types are used
  24717. var alignment;
  24718. if (size <= 2) {
  24719. alignment = size;
  24720. }
  24721. else {
  24722. alignment = 4;
  24723. }
  24724. if ((this._uniformLocationPointer % alignment) !== 0) {
  24725. var oldPointer = this._uniformLocationPointer;
  24726. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24727. var diff = this._uniformLocationPointer - oldPointer;
  24728. for (var i = 0; i < diff; i++) {
  24729. this._data.push(0);
  24730. }
  24731. }
  24732. };
  24733. /**
  24734. * Adds an uniform in the buffer.
  24735. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24736. * for the layout to be correct !
  24737. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24738. * @param {number|number[]} size Data size, or data directly.
  24739. */
  24740. UniformBuffer.prototype.addUniform = function (name, size) {
  24741. if (this._noUBO) {
  24742. return;
  24743. }
  24744. if (this._uniformLocations[name] !== undefined) {
  24745. // Already existing uniform
  24746. return;
  24747. }
  24748. // This function must be called in the order of the shader layout !
  24749. // size can be the size of the uniform, or data directly
  24750. var data;
  24751. if (size instanceof Array) {
  24752. data = size;
  24753. size = data.length;
  24754. }
  24755. else {
  24756. size = size;
  24757. data = [];
  24758. // Fill with zeros
  24759. for (var i = 0; i < size; i++) {
  24760. data.push(0);
  24761. }
  24762. }
  24763. this._fillAlignment(size);
  24764. this._uniformSizes[name] = size;
  24765. this._uniformLocations[name] = this._uniformLocationPointer;
  24766. this._uniformLocationPointer += size;
  24767. for (var i = 0; i < size; i++) {
  24768. this._data.push(data[i]);
  24769. }
  24770. this._needSync = true;
  24771. };
  24772. /**
  24773. * Wrapper for addUniform.
  24774. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24775. * @param {Matrix} mat A 4x4 matrix.
  24776. */
  24777. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24778. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24779. };
  24780. /**
  24781. * Wrapper for addUniform.
  24782. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24783. * @param {number} x
  24784. * @param {number} y
  24785. */
  24786. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24787. var temp = [x, y];
  24788. this.addUniform(name, temp);
  24789. };
  24790. /**
  24791. * Wrapper for addUniform.
  24792. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24793. * @param {number} x
  24794. * @param {number} y
  24795. * @param {number} z
  24796. */
  24797. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24798. var temp = [x, y, z];
  24799. this.addUniform(name, temp);
  24800. };
  24801. /**
  24802. * Wrapper for addUniform.
  24803. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24804. * @param {Color3} color
  24805. */
  24806. UniformBuffer.prototype.addColor3 = function (name, color) {
  24807. var temp = [];
  24808. color.toArray(temp);
  24809. this.addUniform(name, temp);
  24810. };
  24811. /**
  24812. * Wrapper for addUniform.
  24813. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24814. * @param {Color3} color
  24815. * @param {number} alpha
  24816. */
  24817. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24818. var temp = [];
  24819. color.toArray(temp);
  24820. temp.push(alpha);
  24821. this.addUniform(name, temp);
  24822. };
  24823. /**
  24824. * Wrapper for addUniform.
  24825. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24826. * @param {Vector3} vector
  24827. */
  24828. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24829. var temp = [];
  24830. vector.toArray(temp);
  24831. this.addUniform(name, temp);
  24832. };
  24833. /**
  24834. * Wrapper for addUniform.
  24835. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24836. */
  24837. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24838. this.addUniform(name, 12);
  24839. };
  24840. /**
  24841. * Wrapper for addUniform.
  24842. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24843. */
  24844. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24845. this.addUniform(name, 8);
  24846. };
  24847. /**
  24848. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24849. */
  24850. UniformBuffer.prototype.create = function () {
  24851. if (this._noUBO) {
  24852. return;
  24853. }
  24854. if (this._buffer) {
  24855. return; // nothing to do
  24856. }
  24857. // See spec, alignment must be filled as a vec4
  24858. this._fillAlignment(4);
  24859. this._bufferData = new Float32Array(this._data);
  24860. if (this._dynamic) {
  24861. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24862. }
  24863. else {
  24864. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24865. }
  24866. this._needSync = true;
  24867. };
  24868. /**
  24869. * Updates the WebGL Uniform Buffer on the GPU.
  24870. * If the `dynamic` flag is set to true, no cache comparison is done.
  24871. * Otherwise, the buffer will be updated only if the cache differs.
  24872. */
  24873. UniformBuffer.prototype.update = function () {
  24874. if (!this._buffer) {
  24875. this.create();
  24876. return;
  24877. }
  24878. if (!this._dynamic && !this._needSync) {
  24879. return;
  24880. }
  24881. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24882. this._needSync = false;
  24883. };
  24884. /**
  24885. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24886. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24887. * @param {number[]|Float32Array} data Flattened data
  24888. * @param {number} size Size of the data.
  24889. */
  24890. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24891. var location = this._uniformLocations[uniformName];
  24892. if (location === undefined) {
  24893. if (this._buffer) {
  24894. // Cannot add an uniform if the buffer is already created
  24895. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24896. return;
  24897. }
  24898. this.addUniform(uniformName, size);
  24899. location = this._uniformLocations[uniformName];
  24900. }
  24901. if (!this._buffer) {
  24902. this.create();
  24903. }
  24904. if (!this._dynamic) {
  24905. // Cache for static uniform buffers
  24906. var changed = false;
  24907. for (var i = 0; i < size; i++) {
  24908. if (this._bufferData[location + i] !== data[i]) {
  24909. changed = true;
  24910. this._bufferData[location + i] = data[i];
  24911. }
  24912. }
  24913. this._needSync = this._needSync || changed;
  24914. }
  24915. else {
  24916. // No cache for dynamic
  24917. for (var i = 0; i < size; i++) {
  24918. this._bufferData[location + i] = data[i];
  24919. }
  24920. }
  24921. };
  24922. // Update methods
  24923. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24924. // To match std140, matrix must be realigned
  24925. for (var i = 0; i < 3; i++) {
  24926. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24927. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24928. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24929. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24930. }
  24931. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24932. };
  24933. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24934. this._currentEffect.setMatrix3x3(name, matrix);
  24935. };
  24936. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24937. this._currentEffect.setMatrix2x2(name, matrix);
  24938. };
  24939. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24940. // To match std140, matrix must be realigned
  24941. for (var i = 0; i < 2; i++) {
  24942. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24943. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24944. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24945. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24946. }
  24947. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24948. };
  24949. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24950. this._currentEffect.setFloat(name, x);
  24951. };
  24952. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24953. UniformBuffer._tempBuffer[0] = x;
  24954. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24955. };
  24956. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24957. if (suffix === void 0) { suffix = ""; }
  24958. this._currentEffect.setFloat2(name + suffix, x, y);
  24959. };
  24960. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24961. if (suffix === void 0) { suffix = ""; }
  24962. UniformBuffer._tempBuffer[0] = x;
  24963. UniformBuffer._tempBuffer[1] = y;
  24964. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24965. };
  24966. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24967. if (suffix === void 0) { suffix = ""; }
  24968. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24969. };
  24970. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24971. if (suffix === void 0) { suffix = ""; }
  24972. UniformBuffer._tempBuffer[0] = x;
  24973. UniformBuffer._tempBuffer[1] = y;
  24974. UniformBuffer._tempBuffer[2] = z;
  24975. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24976. };
  24977. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24978. if (suffix === void 0) { suffix = ""; }
  24979. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24980. };
  24981. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24982. if (suffix === void 0) { suffix = ""; }
  24983. UniformBuffer._tempBuffer[0] = x;
  24984. UniformBuffer._tempBuffer[1] = y;
  24985. UniformBuffer._tempBuffer[2] = z;
  24986. UniformBuffer._tempBuffer[3] = w;
  24987. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24988. };
  24989. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24990. this._currentEffect.setMatrix(name, mat);
  24991. };
  24992. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24993. this.updateUniform(name, mat.toArray(), 16);
  24994. };
  24995. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24996. this._currentEffect.setVector3(name, vector);
  24997. };
  24998. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24999. vector.toArray(UniformBuffer._tempBuffer);
  25000. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25001. };
  25002. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  25003. this._currentEffect.setVector4(name, vector);
  25004. };
  25005. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  25006. vector.toArray(UniformBuffer._tempBuffer);
  25007. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25008. };
  25009. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  25010. if (suffix === void 0) { suffix = ""; }
  25011. this._currentEffect.setColor3(name + suffix, color);
  25012. };
  25013. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  25014. if (suffix === void 0) { suffix = ""; }
  25015. color.toArray(UniformBuffer._tempBuffer);
  25016. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  25017. };
  25018. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  25019. if (suffix === void 0) { suffix = ""; }
  25020. this._currentEffect.setColor4(name + suffix, color, alpha);
  25021. };
  25022. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  25023. if (suffix === void 0) { suffix = ""; }
  25024. color.toArray(UniformBuffer._tempBuffer);
  25025. UniformBuffer._tempBuffer[3] = alpha;
  25026. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  25027. };
  25028. /**
  25029. * Sets a sampler uniform on the effect.
  25030. * @param {string} name Name of the sampler.
  25031. * @param {Texture} texture
  25032. */
  25033. UniformBuffer.prototype.setTexture = function (name, texture) {
  25034. this._currentEffect.setTexture(name, texture);
  25035. };
  25036. /**
  25037. * Directly updates the value of the uniform in the cache AND on the GPU.
  25038. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25039. * @param {number[]|Float32Array} data Flattened data
  25040. */
  25041. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  25042. this.updateUniform(uniformName, data, data.length);
  25043. this.update();
  25044. };
  25045. /**
  25046. * Binds this uniform buffer to an effect.
  25047. * @param {Effect} effect
  25048. * @param {string} name Name of the uniform block in the shader.
  25049. */
  25050. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  25051. this._currentEffect = effect;
  25052. if (this._noUBO) {
  25053. return;
  25054. }
  25055. effect.bindUniformBuffer(this._buffer, name);
  25056. };
  25057. /**
  25058. * Disposes the uniform buffer.
  25059. */
  25060. UniformBuffer.prototype.dispose = function () {
  25061. if (!this._buffer) {
  25062. return;
  25063. }
  25064. if (this._engine._releaseBuffer(this._buffer)) {
  25065. this._buffer = null;
  25066. }
  25067. };
  25068. return UniformBuffer;
  25069. }());
  25070. // Pool for avoiding memory leaks
  25071. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  25072. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  25073. BABYLON.UniformBuffer = UniformBuffer;
  25074. })(BABYLON || (BABYLON = {}));
  25075. //# sourceMappingURL=babylon.uniformBuffer.js.map
  25076. var BABYLON;
  25077. (function (BABYLON) {
  25078. var PushMaterial = (function (_super) {
  25079. __extends(PushMaterial, _super);
  25080. function PushMaterial(name, scene) {
  25081. var _this = _super.call(this, name, scene) || this;
  25082. _this.storeEffectOnSubMeshes = true;
  25083. return _this;
  25084. }
  25085. PushMaterial.prototype.getEffect = function () {
  25086. return this._activeEffect;
  25087. };
  25088. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  25089. if (!mesh) {
  25090. return false;
  25091. }
  25092. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25093. return true;
  25094. }
  25095. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  25096. };
  25097. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25098. this._activeEffect.setMatrix("world", world);
  25099. };
  25100. PushMaterial.prototype.bind = function (world, mesh) {
  25101. if (!mesh) {
  25102. return;
  25103. }
  25104. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  25105. };
  25106. PushMaterial.prototype._afterBind = function (mesh, effect) {
  25107. _super.prototype._afterBind.call(this, mesh);
  25108. this.getScene()._cachedEffect = effect;
  25109. };
  25110. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  25111. if (visibility === void 0) { visibility = 0; }
  25112. return scene.isCachedMaterialValid(this, effect, visibility);
  25113. };
  25114. return PushMaterial;
  25115. }(BABYLON.Material));
  25116. BABYLON.PushMaterial = PushMaterial;
  25117. })(BABYLON || (BABYLON = {}));
  25118. //# sourceMappingURL=babylon.pushMaterial.js.map
  25119. var BABYLON;
  25120. (function (BABYLON) {
  25121. var VertexData = (function () {
  25122. function VertexData() {
  25123. }
  25124. VertexData.prototype.set = function (data, kind) {
  25125. switch (kind) {
  25126. case BABYLON.VertexBuffer.PositionKind:
  25127. this.positions = data;
  25128. break;
  25129. case BABYLON.VertexBuffer.NormalKind:
  25130. this.normals = data;
  25131. break;
  25132. case BABYLON.VertexBuffer.TangentKind:
  25133. this.tangents = data;
  25134. break;
  25135. case BABYLON.VertexBuffer.UVKind:
  25136. this.uvs = data;
  25137. break;
  25138. case BABYLON.VertexBuffer.UV2Kind:
  25139. this.uvs2 = data;
  25140. break;
  25141. case BABYLON.VertexBuffer.UV3Kind:
  25142. this.uvs3 = data;
  25143. break;
  25144. case BABYLON.VertexBuffer.UV4Kind:
  25145. this.uvs4 = data;
  25146. break;
  25147. case BABYLON.VertexBuffer.UV5Kind:
  25148. this.uvs5 = data;
  25149. break;
  25150. case BABYLON.VertexBuffer.UV6Kind:
  25151. this.uvs6 = data;
  25152. break;
  25153. case BABYLON.VertexBuffer.ColorKind:
  25154. this.colors = data;
  25155. break;
  25156. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25157. this.matricesIndices = data;
  25158. break;
  25159. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25160. this.matricesWeights = data;
  25161. break;
  25162. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  25163. this.matricesIndicesExtra = data;
  25164. break;
  25165. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  25166. this.matricesWeightsExtra = data;
  25167. break;
  25168. }
  25169. };
  25170. /**
  25171. * Associates the vertexData to the passed Mesh.
  25172. * Sets it as updatable or not (default `false`).
  25173. * Returns the VertexData.
  25174. */
  25175. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25176. this._applyTo(mesh, updatable);
  25177. return this;
  25178. };
  25179. /**
  25180. * Associates the vertexData to the passed Geometry.
  25181. * Sets it as updatable or not (default `false`).
  25182. * Returns the VertexData.
  25183. */
  25184. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25185. this._applyTo(geometry, updatable);
  25186. return this;
  25187. };
  25188. /**
  25189. * Updates the associated mesh.
  25190. * Returns the VertexData.
  25191. */
  25192. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25193. this._update(mesh);
  25194. return this;
  25195. };
  25196. /**
  25197. * Updates the associated geometry.
  25198. * Returns the VertexData.
  25199. */
  25200. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25201. this._update(geometry);
  25202. return this;
  25203. };
  25204. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25205. if (this.positions) {
  25206. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25207. }
  25208. if (this.normals) {
  25209. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25210. }
  25211. if (this.tangents) {
  25212. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25213. }
  25214. if (this.uvs) {
  25215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25216. }
  25217. if (this.uvs2) {
  25218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25219. }
  25220. if (this.uvs3) {
  25221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25222. }
  25223. if (this.uvs4) {
  25224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25225. }
  25226. if (this.uvs5) {
  25227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25228. }
  25229. if (this.uvs6) {
  25230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25231. }
  25232. if (this.colors) {
  25233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25234. }
  25235. if (this.matricesIndices) {
  25236. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25237. }
  25238. if (this.matricesWeights) {
  25239. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25240. }
  25241. if (this.matricesIndicesExtra) {
  25242. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25243. }
  25244. if (this.matricesWeightsExtra) {
  25245. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25246. }
  25247. if (this.indices) {
  25248. meshOrGeometry.setIndices(this.indices);
  25249. }
  25250. return this;
  25251. };
  25252. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25253. if (this.positions) {
  25254. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25255. }
  25256. if (this.normals) {
  25257. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25258. }
  25259. if (this.tangents) {
  25260. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25261. }
  25262. if (this.uvs) {
  25263. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25264. }
  25265. if (this.uvs2) {
  25266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25267. }
  25268. if (this.uvs3) {
  25269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25270. }
  25271. if (this.uvs4) {
  25272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25273. }
  25274. if (this.uvs5) {
  25275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25276. }
  25277. if (this.uvs6) {
  25278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25279. }
  25280. if (this.colors) {
  25281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25282. }
  25283. if (this.matricesIndices) {
  25284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25285. }
  25286. if (this.matricesWeights) {
  25287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25288. }
  25289. if (this.matricesIndicesExtra) {
  25290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25291. }
  25292. if (this.matricesWeightsExtra) {
  25293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25294. }
  25295. if (this.indices) {
  25296. meshOrGeometry.setIndices(this.indices);
  25297. }
  25298. return this;
  25299. };
  25300. /**
  25301. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25302. * Returns the VertexData.
  25303. */
  25304. VertexData.prototype.transform = function (matrix) {
  25305. var transformed = BABYLON.Vector3.Zero();
  25306. var index;
  25307. if (this.positions) {
  25308. var position = BABYLON.Vector3.Zero();
  25309. for (index = 0; index < this.positions.length; index += 3) {
  25310. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25311. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25312. this.positions[index] = transformed.x;
  25313. this.positions[index + 1] = transformed.y;
  25314. this.positions[index + 2] = transformed.z;
  25315. }
  25316. }
  25317. if (this.normals) {
  25318. var normal = BABYLON.Vector3.Zero();
  25319. for (index = 0; index < this.normals.length; index += 3) {
  25320. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25321. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25322. this.normals[index] = transformed.x;
  25323. this.normals[index + 1] = transformed.y;
  25324. this.normals[index + 2] = transformed.z;
  25325. }
  25326. }
  25327. if (this.tangents) {
  25328. var tangent = BABYLON.Vector4.Zero();
  25329. var tangentTransformed = BABYLON.Vector4.Zero();
  25330. for (index = 0; index < this.tangents.length; index += 4) {
  25331. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25332. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25333. this.tangents[index] = tangentTransformed.x;
  25334. this.tangents[index + 1] = tangentTransformed.y;
  25335. this.tangents[index + 2] = tangentTransformed.z;
  25336. this.tangents[index + 3] = tangentTransformed.w;
  25337. }
  25338. }
  25339. return this;
  25340. };
  25341. /**
  25342. * Merges the passed VertexData into the current one.
  25343. * Returns the modified VertexData.
  25344. */
  25345. VertexData.prototype.merge = function (other) {
  25346. if (other.indices) {
  25347. if (!this.indices) {
  25348. this.indices = [];
  25349. }
  25350. var offset = this.positions ? this.positions.length / 3 : 0;
  25351. for (var index = 0; index < other.indices.length; index++) {
  25352. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25353. this.indices.push(other.indices[index] + offset);
  25354. }
  25355. }
  25356. this.positions = this._mergeElement(this.positions, other.positions);
  25357. this.normals = this._mergeElement(this.normals, other.normals);
  25358. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25359. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25360. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25361. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25362. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25363. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25364. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25365. this.colors = this._mergeElement(this.colors, other.colors);
  25366. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25367. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25368. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25369. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25370. return this;
  25371. };
  25372. VertexData.prototype._mergeElement = function (source, other) {
  25373. if (!other)
  25374. return source;
  25375. if (!source)
  25376. return other;
  25377. var len = other.length + source.length;
  25378. var isSrcTypedArray = source instanceof Float32Array;
  25379. var isOthTypedArray = other instanceof Float32Array;
  25380. // use non-loop method when the source is Float32Array
  25381. if (isSrcTypedArray) {
  25382. var ret32 = new Float32Array(len);
  25383. ret32.set(source);
  25384. ret32.set(other, source.length);
  25385. return ret32;
  25386. // source is number[], when other is also use concat
  25387. }
  25388. else if (!isOthTypedArray) {
  25389. return source.concat(other);
  25390. // source is a number[], but other is a Float32Array, loop required
  25391. }
  25392. else {
  25393. var ret = source.slice(0); // copy source to a separate array
  25394. for (var i = 0, len = other.length; i < len; i++) {
  25395. ret.push(other[i]);
  25396. }
  25397. return ret;
  25398. }
  25399. };
  25400. /**
  25401. * Serializes the VertexData.
  25402. * Returns a serialized object.
  25403. */
  25404. VertexData.prototype.serialize = function () {
  25405. var serializationObject = this.serialize();
  25406. if (this.positions) {
  25407. serializationObject.positions = this.positions;
  25408. }
  25409. if (this.normals) {
  25410. serializationObject.normals = this.normals;
  25411. }
  25412. if (this.tangents) {
  25413. serializationObject.tangents = this.tangents;
  25414. }
  25415. if (this.uvs) {
  25416. serializationObject.uvs = this.uvs;
  25417. }
  25418. if (this.uvs2) {
  25419. serializationObject.uvs2 = this.uvs2;
  25420. }
  25421. if (this.uvs3) {
  25422. serializationObject.uvs3 = this.uvs3;
  25423. }
  25424. if (this.uvs4) {
  25425. serializationObject.uvs4 = this.uvs4;
  25426. }
  25427. if (this.uvs5) {
  25428. serializationObject.uvs5 = this.uvs5;
  25429. }
  25430. if (this.uvs6) {
  25431. serializationObject.uvs6 = this.uvs6;
  25432. }
  25433. if (this.colors) {
  25434. serializationObject.colors = this.colors;
  25435. }
  25436. if (this.matricesIndices) {
  25437. serializationObject.matricesIndices = this.matricesIndices;
  25438. serializationObject.matricesIndices._isExpanded = true;
  25439. }
  25440. if (this.matricesWeights) {
  25441. serializationObject.matricesWeights = this.matricesWeights;
  25442. }
  25443. if (this.matricesIndicesExtra) {
  25444. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25445. serializationObject.matricesIndicesExtra._isExpanded = true;
  25446. }
  25447. if (this.matricesWeightsExtra) {
  25448. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25449. }
  25450. serializationObject.indices = this.indices;
  25451. return serializationObject;
  25452. };
  25453. // Statics
  25454. /**
  25455. * Returns the object VertexData associated to the passed mesh.
  25456. */
  25457. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25458. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25459. };
  25460. /**
  25461. * Returns the object VertexData associated to the passed geometry.
  25462. */
  25463. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25464. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25465. };
  25466. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25467. var result = new VertexData();
  25468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25469. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25470. }
  25471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25472. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25473. }
  25474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25475. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25476. }
  25477. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25478. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25479. }
  25480. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25481. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25482. }
  25483. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25484. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25485. }
  25486. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25487. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25488. }
  25489. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25490. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25491. }
  25492. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25493. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25494. }
  25495. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25496. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25497. }
  25498. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25499. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25500. }
  25501. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25502. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25503. }
  25504. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25505. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25506. }
  25507. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25508. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25509. }
  25510. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25511. return result;
  25512. };
  25513. /**
  25514. * Creates the vertexData of the Ribbon.
  25515. */
  25516. VertexData.CreateRibbon = function (options) {
  25517. var pathArray = options.pathArray;
  25518. var closeArray = options.closeArray || false;
  25519. var closePath = options.closePath || false;
  25520. var invertUV = options.invertUV || false;
  25521. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25522. var offset = options.offset || defaultOffset;
  25523. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25524. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25525. var customUV = options.uvs;
  25526. var customColors = options.colors;
  25527. var positions = [];
  25528. var indices = [];
  25529. var normals = [];
  25530. var uvs = [];
  25531. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25532. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25533. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25534. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25535. var minlg; // minimal length among all paths from pathArray
  25536. var lg = []; // array of path lengths : nb of vertex per path
  25537. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25538. var p; // path iterator
  25539. var i; // point iterator
  25540. var j; // point iterator
  25541. // if single path in pathArray
  25542. if (pathArray.length < 2) {
  25543. var ar1 = [];
  25544. var ar2 = [];
  25545. for (i = 0; i < pathArray[0].length - offset; i++) {
  25546. ar1.push(pathArray[0][i]);
  25547. ar2.push(pathArray[0][i + offset]);
  25548. }
  25549. pathArray = [ar1, ar2];
  25550. }
  25551. // positions and horizontal distances (u)
  25552. var idc = 0;
  25553. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25554. var path;
  25555. var l;
  25556. minlg = pathArray[0].length;
  25557. var vectlg;
  25558. var dist;
  25559. for (p = 0; p < pathArray.length; p++) {
  25560. uTotalDistance[p] = 0;
  25561. us[p] = [0];
  25562. path = pathArray[p];
  25563. l = path.length;
  25564. minlg = (minlg < l) ? minlg : l;
  25565. j = 0;
  25566. while (j < l) {
  25567. positions.push(path[j].x, path[j].y, path[j].z);
  25568. if (j > 0) {
  25569. vectlg = path[j].subtract(path[j - 1]).length();
  25570. dist = vectlg + uTotalDistance[p];
  25571. us[p].push(dist);
  25572. uTotalDistance[p] = dist;
  25573. }
  25574. j++;
  25575. }
  25576. if (closePath) {
  25577. j--;
  25578. positions.push(path[0].x, path[0].y, path[0].z);
  25579. vectlg = path[j].subtract(path[0]).length();
  25580. dist = vectlg + uTotalDistance[p];
  25581. us[p].push(dist);
  25582. uTotalDistance[p] = dist;
  25583. }
  25584. lg[p] = l + closePathCorr;
  25585. idx[p] = idc;
  25586. idc += (l + closePathCorr);
  25587. }
  25588. // vertical distances (v)
  25589. var path1;
  25590. var path2;
  25591. var vertex1;
  25592. var vertex2;
  25593. for (i = 0; i < minlg + closePathCorr; i++) {
  25594. vTotalDistance[i] = 0;
  25595. vs[i] = [0];
  25596. for (p = 0; p < pathArray.length - 1; p++) {
  25597. path1 = pathArray[p];
  25598. path2 = pathArray[p + 1];
  25599. if (i === minlg) {
  25600. vertex1 = path1[0];
  25601. vertex2 = path2[0];
  25602. }
  25603. else {
  25604. vertex1 = path1[i];
  25605. vertex2 = path2[i];
  25606. }
  25607. vectlg = vertex2.subtract(vertex1).length();
  25608. dist = vectlg + vTotalDistance[i];
  25609. vs[i].push(dist);
  25610. vTotalDistance[i] = dist;
  25611. }
  25612. if (closeArray) {
  25613. path1 = pathArray[p];
  25614. path2 = pathArray[0];
  25615. if (i === minlg) {
  25616. vertex2 = path2[0];
  25617. }
  25618. vectlg = vertex2.subtract(vertex1).length();
  25619. dist = vectlg + vTotalDistance[i];
  25620. vTotalDistance[i] = dist;
  25621. }
  25622. }
  25623. // uvs
  25624. var u;
  25625. var v;
  25626. if (customUV) {
  25627. for (p = 0; p < customUV.length; p++) {
  25628. uvs.push(customUV[p].x, customUV[p].y);
  25629. }
  25630. }
  25631. else {
  25632. for (p = 0; p < pathArray.length; p++) {
  25633. for (i = 0; i < minlg + closePathCorr; i++) {
  25634. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25635. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25636. if (invertUV) {
  25637. uvs.push(v, u);
  25638. }
  25639. else {
  25640. uvs.push(u, v);
  25641. }
  25642. }
  25643. }
  25644. }
  25645. // indices
  25646. p = 0; // path index
  25647. var pi = 0; // positions array index
  25648. var l1 = lg[p] - 1; // path1 length
  25649. var l2 = lg[p + 1] - 1; // path2 length
  25650. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25651. var shft = idx[1] - idx[0]; // shift
  25652. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25653. while (pi <= min && p < path1nb) {
  25654. // 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
  25655. indices.push(pi, pi + shft, pi + 1);
  25656. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25657. pi += 1;
  25658. if (pi === min) {
  25659. p++;
  25660. if (p === lg.length - 1) {
  25661. shft = idx[0] - idx[p];
  25662. l1 = lg[p] - 1;
  25663. l2 = lg[0] - 1;
  25664. }
  25665. else {
  25666. shft = idx[p + 1] - idx[p];
  25667. l1 = lg[p] - 1;
  25668. l2 = lg[p + 1] - 1;
  25669. }
  25670. pi = idx[p];
  25671. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25672. }
  25673. }
  25674. // normals
  25675. VertexData.ComputeNormals(positions, indices, normals);
  25676. if (closePath) {
  25677. var indexFirst = 0;
  25678. var indexLast = 0;
  25679. for (p = 0; p < pathArray.length; p++) {
  25680. indexFirst = idx[p] * 3;
  25681. if (p + 1 < pathArray.length) {
  25682. indexLast = (idx[p + 1] - 1) * 3;
  25683. }
  25684. else {
  25685. indexLast = normals.length - 3;
  25686. }
  25687. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25688. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25689. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25690. normals[indexLast] = normals[indexFirst];
  25691. normals[indexLast + 1] = normals[indexFirst + 1];
  25692. normals[indexLast + 2] = normals[indexFirst + 2];
  25693. }
  25694. }
  25695. // sides
  25696. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25697. // Colors
  25698. if (customColors) {
  25699. var colors = new Float32Array(customColors.length * 4);
  25700. for (var c = 0; c < customColors.length; c++) {
  25701. colors[c * 4] = customColors[c].r;
  25702. colors[c * 4 + 1] = customColors[c].g;
  25703. colors[c * 4 + 2] = customColors[c].b;
  25704. colors[c * 4 + 3] = customColors[c].a;
  25705. }
  25706. }
  25707. // Result
  25708. var vertexData = new VertexData();
  25709. var positions32 = new Float32Array(positions);
  25710. var normals32 = new Float32Array(normals);
  25711. var uvs32 = new Float32Array(uvs);
  25712. vertexData.indices = indices;
  25713. vertexData.positions = positions32;
  25714. vertexData.normals = normals32;
  25715. vertexData.uvs = uvs32;
  25716. if (customColors) {
  25717. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25718. }
  25719. if (closePath) {
  25720. vertexData._idx = idx;
  25721. }
  25722. return vertexData;
  25723. };
  25724. /**
  25725. * Creates the VertexData of the Box.
  25726. */
  25727. VertexData.CreateBox = function (options) {
  25728. var normalsSource = [
  25729. new BABYLON.Vector3(0, 0, 1),
  25730. new BABYLON.Vector3(0, 0, -1),
  25731. new BABYLON.Vector3(1, 0, 0),
  25732. new BABYLON.Vector3(-1, 0, 0),
  25733. new BABYLON.Vector3(0, 1, 0),
  25734. new BABYLON.Vector3(0, -1, 0)
  25735. ];
  25736. var indices = [];
  25737. var positions = [];
  25738. var normals = [];
  25739. var uvs = [];
  25740. var width = options.width || options.size || 1;
  25741. var height = options.height || options.size || 1;
  25742. var depth = options.depth || options.size || 1;
  25743. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25744. var faceUV = options.faceUV || new Array(6);
  25745. var faceColors = options.faceColors;
  25746. var colors = [];
  25747. // default face colors and UV if undefined
  25748. for (var f = 0; f < 6; f++) {
  25749. if (faceUV[f] === undefined) {
  25750. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25751. }
  25752. if (faceColors && faceColors[f] === undefined) {
  25753. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25754. }
  25755. }
  25756. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25757. // Create each face in turn.
  25758. for (var index = 0; index < normalsSource.length; index++) {
  25759. var normal = normalsSource[index];
  25760. // Get two vectors perpendicular to the face normal and to each other.
  25761. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25762. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25763. // Six indices (two triangles) per face.
  25764. var verticesLength = positions.length / 3;
  25765. indices.push(verticesLength);
  25766. indices.push(verticesLength + 1);
  25767. indices.push(verticesLength + 2);
  25768. indices.push(verticesLength);
  25769. indices.push(verticesLength + 2);
  25770. indices.push(verticesLength + 3);
  25771. // Four vertices per face.
  25772. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25773. positions.push(vertex.x, vertex.y, vertex.z);
  25774. normals.push(normal.x, normal.y, normal.z);
  25775. uvs.push(faceUV[index].z, faceUV[index].w);
  25776. if (faceColors) {
  25777. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25778. }
  25779. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25780. positions.push(vertex.x, vertex.y, vertex.z);
  25781. normals.push(normal.x, normal.y, normal.z);
  25782. uvs.push(faceUV[index].x, faceUV[index].w);
  25783. if (faceColors) {
  25784. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25785. }
  25786. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25787. positions.push(vertex.x, vertex.y, vertex.z);
  25788. normals.push(normal.x, normal.y, normal.z);
  25789. uvs.push(faceUV[index].x, faceUV[index].y);
  25790. if (faceColors) {
  25791. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25792. }
  25793. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25794. positions.push(vertex.x, vertex.y, vertex.z);
  25795. normals.push(normal.x, normal.y, normal.z);
  25796. uvs.push(faceUV[index].z, faceUV[index].y);
  25797. if (faceColors) {
  25798. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25799. }
  25800. }
  25801. // sides
  25802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25803. // Result
  25804. var vertexData = new VertexData();
  25805. vertexData.indices = indices;
  25806. vertexData.positions = positions;
  25807. vertexData.normals = normals;
  25808. vertexData.uvs = uvs;
  25809. if (faceColors) {
  25810. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25811. vertexData.colors = totalColors;
  25812. }
  25813. return vertexData;
  25814. };
  25815. /**
  25816. * Creates the VertexData of the Sphere.
  25817. */
  25818. VertexData.CreateSphere = function (options) {
  25819. var segments = options.segments || 32;
  25820. var diameterX = options.diameterX || options.diameter || 1;
  25821. var diameterY = options.diameterY || options.diameter || 1;
  25822. var diameterZ = options.diameterZ || options.diameter || 1;
  25823. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25824. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25825. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25826. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25827. var totalZRotationSteps = 2 + segments;
  25828. var totalYRotationSteps = 2 * totalZRotationSteps;
  25829. var indices = [];
  25830. var positions = [];
  25831. var normals = [];
  25832. var uvs = [];
  25833. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25834. var normalizedZ = zRotationStep / totalZRotationSteps;
  25835. var angleZ = normalizedZ * Math.PI * slice;
  25836. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25837. var normalizedY = yRotationStep / totalYRotationSteps;
  25838. var angleY = normalizedY * Math.PI * 2 * arc;
  25839. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25840. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25841. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25842. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25843. var vertex = complete.multiply(radius);
  25844. var normal = complete.divide(radius).normalize();
  25845. positions.push(vertex.x, vertex.y, vertex.z);
  25846. normals.push(normal.x, normal.y, normal.z);
  25847. uvs.push(normalizedY, normalizedZ);
  25848. }
  25849. if (zRotationStep > 0) {
  25850. var verticesCount = positions.length / 3;
  25851. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25852. indices.push((firstIndex));
  25853. indices.push((firstIndex + 1));
  25854. indices.push(firstIndex + totalYRotationSteps + 1);
  25855. indices.push((firstIndex + totalYRotationSteps + 1));
  25856. indices.push((firstIndex + 1));
  25857. indices.push((firstIndex + totalYRotationSteps + 2));
  25858. }
  25859. }
  25860. }
  25861. // Sides
  25862. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25863. // Result
  25864. var vertexData = new VertexData();
  25865. vertexData.indices = indices;
  25866. vertexData.positions = positions;
  25867. vertexData.normals = normals;
  25868. vertexData.uvs = uvs;
  25869. return vertexData;
  25870. };
  25871. /**
  25872. * Creates the VertexData of the Cylinder or Cone.
  25873. */
  25874. VertexData.CreateCylinder = function (options) {
  25875. var height = options.height || 2;
  25876. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25877. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25878. var tessellation = options.tessellation || 24;
  25879. var subdivisions = options.subdivisions || 1;
  25880. var hasRings = options.hasRings;
  25881. var enclose = options.enclose;
  25882. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25883. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25884. var faceUV = options.faceUV || new Array(3);
  25885. var faceColors = options.faceColors;
  25886. // default face colors and UV if undefined
  25887. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25888. var ringNb = (hasRings) ? subdivisions : 1;
  25889. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25890. var f;
  25891. for (f = 0; f < surfaceNb; f++) {
  25892. if (faceColors && faceColors[f] === undefined) {
  25893. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25894. }
  25895. }
  25896. for (f = 0; f < surfaceNb; f++) {
  25897. if (faceUV && faceUV[f] === undefined) {
  25898. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25899. }
  25900. }
  25901. var indices = [];
  25902. var positions = [];
  25903. var normals = [];
  25904. var uvs = [];
  25905. var colors = [];
  25906. var angle_step = Math.PI * 2 * arc / tessellation;
  25907. var angle;
  25908. var h;
  25909. var radius;
  25910. var tan = (diameterBottom - diameterTop) / 2 / height;
  25911. var ringVertex = BABYLON.Vector3.Zero();
  25912. var ringNormal = BABYLON.Vector3.Zero();
  25913. var ringFirstVertex = BABYLON.Vector3.Zero();
  25914. var ringFirstNormal = BABYLON.Vector3.Zero();
  25915. var quadNormal = BABYLON.Vector3.Zero();
  25916. var Y = BABYLON.Axis.Y;
  25917. // positions, normals, uvs
  25918. var i;
  25919. var j;
  25920. var r;
  25921. var ringIdx = 1;
  25922. var s = 1; // surface index
  25923. var cs = 0;
  25924. var v = 0;
  25925. for (i = 0; i <= subdivisions; i++) {
  25926. h = i / subdivisions;
  25927. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25928. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25929. for (r = 0; r < ringIdx; r++) {
  25930. if (hasRings) {
  25931. s += r;
  25932. }
  25933. if (enclose) {
  25934. s += 2 * r;
  25935. }
  25936. for (j = 0; j <= tessellation; j++) {
  25937. angle = j * angle_step;
  25938. // position
  25939. ringVertex.x = Math.cos(-angle) * radius;
  25940. ringVertex.y = -height / 2 + h * height;
  25941. ringVertex.z = Math.sin(-angle) * radius;
  25942. // normal
  25943. if (diameterTop === 0 && i === subdivisions) {
  25944. // if no top cap, reuse former normals
  25945. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25946. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25947. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25948. }
  25949. else {
  25950. ringNormal.x = ringVertex.x;
  25951. ringNormal.z = ringVertex.z;
  25952. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25953. ringNormal.normalize();
  25954. }
  25955. // keep first ring vertex values for enclose
  25956. if (j === 0) {
  25957. ringFirstVertex.copyFrom(ringVertex);
  25958. ringFirstNormal.copyFrom(ringNormal);
  25959. }
  25960. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25961. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25962. if (hasRings) {
  25963. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25964. }
  25965. else {
  25966. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25967. }
  25968. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25969. if (faceColors) {
  25970. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25971. }
  25972. }
  25973. // if enclose, add four vertices and their dedicated normals
  25974. if (arc !== 1 && enclose) {
  25975. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25976. positions.push(0, ringVertex.y, 0);
  25977. positions.push(0, ringVertex.y, 0);
  25978. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25979. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25980. quadNormal.normalize();
  25981. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25982. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25983. quadNormal.normalize();
  25984. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25985. if (hasRings) {
  25986. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25987. }
  25988. else {
  25989. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25990. }
  25991. uvs.push(faceUV[s + 1].x, v);
  25992. uvs.push(faceUV[s + 1].z, v);
  25993. if (hasRings) {
  25994. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25995. }
  25996. else {
  25997. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25998. }
  25999. uvs.push(faceUV[s + 2].x, v);
  26000. uvs.push(faceUV[s + 2].z, v);
  26001. if (faceColors) {
  26002. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26003. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  26004. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26005. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  26006. }
  26007. }
  26008. if (cs !== s) {
  26009. cs = s;
  26010. }
  26011. }
  26012. }
  26013. // indices
  26014. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  26015. var s;
  26016. i = 0;
  26017. for (s = 0; s < subdivisions; s++) {
  26018. for (j = 0; j < tessellation; j++) {
  26019. var i0 = i * (e + 1) + j;
  26020. var i1 = (i + 1) * (e + 1) + j;
  26021. var i2 = i * (e + 1) + (j + 1);
  26022. var i3 = (i + 1) * (e + 1) + (j + 1);
  26023. indices.push(i0, i1, i2);
  26024. indices.push(i3, i2, i1);
  26025. }
  26026. if (arc !== 1 && enclose) {
  26027. indices.push(i0 + 2, i1 + 2, i2 + 2);
  26028. indices.push(i3 + 2, i2 + 2, i1 + 2);
  26029. indices.push(i0 + 4, i1 + 4, i2 + 4);
  26030. indices.push(i3 + 4, i2 + 4, i1 + 4);
  26031. }
  26032. i = (hasRings) ? (i + 2) : (i + 1);
  26033. }
  26034. // Caps
  26035. var createCylinderCap = function (isTop) {
  26036. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26037. if (radius === 0) {
  26038. return;
  26039. }
  26040. // Cap positions, normals & uvs
  26041. var angle;
  26042. var circleVector;
  26043. var i;
  26044. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  26045. var c;
  26046. if (faceColors) {
  26047. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  26048. }
  26049. // cap center
  26050. var vbase = positions.length / 3;
  26051. var offset = isTop ? height / 2 : -height / 2;
  26052. var center = new BABYLON.Vector3(0, offset, 0);
  26053. positions.push(center.x, center.y, center.z);
  26054. normals.push(0, isTop ? 1 : -1, 0);
  26055. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  26056. if (faceColors) {
  26057. colors.push(c.r, c.g, c.b, c.a);
  26058. }
  26059. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26060. for (i = 0; i <= tessellation; i++) {
  26061. angle = Math.PI * 2 * i * arc / tessellation;
  26062. var cos = Math.cos(-angle);
  26063. var sin = Math.sin(-angle);
  26064. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  26065. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  26066. positions.push(circleVector.x, circleVector.y, circleVector.z);
  26067. normals.push(0, isTop ? 1 : -1, 0);
  26068. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  26069. if (faceColors) {
  26070. colors.push(c.r, c.g, c.b, c.a);
  26071. }
  26072. }
  26073. // Cap indices
  26074. for (i = 0; i < tessellation; i++) {
  26075. if (!isTop) {
  26076. indices.push(vbase);
  26077. indices.push(vbase + (i + 1));
  26078. indices.push(vbase + (i + 2));
  26079. }
  26080. else {
  26081. indices.push(vbase);
  26082. indices.push(vbase + (i + 2));
  26083. indices.push(vbase + (i + 1));
  26084. }
  26085. }
  26086. };
  26087. // add caps to geometry
  26088. createCylinderCap(false);
  26089. createCylinderCap(true);
  26090. // Sides
  26091. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26092. var vertexData = new VertexData();
  26093. vertexData.indices = indices;
  26094. vertexData.positions = positions;
  26095. vertexData.normals = normals;
  26096. vertexData.uvs = uvs;
  26097. if (faceColors) {
  26098. vertexData.colors = colors;
  26099. }
  26100. return vertexData;
  26101. };
  26102. /**
  26103. * Creates the VertexData of the Torus.
  26104. */
  26105. VertexData.CreateTorus = function (options) {
  26106. var indices = [];
  26107. var positions = [];
  26108. var normals = [];
  26109. var uvs = [];
  26110. var diameter = options.diameter || 1;
  26111. var thickness = options.thickness || 0.5;
  26112. var tessellation = options.tessellation || 16;
  26113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26114. var stride = tessellation + 1;
  26115. for (var i = 0; i <= tessellation; i++) {
  26116. var u = i / tessellation;
  26117. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26118. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26119. for (var j = 0; j <= tessellation; j++) {
  26120. var v = 1 - j / tessellation;
  26121. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26122. var dx = Math.cos(innerAngle);
  26123. var dy = Math.sin(innerAngle);
  26124. // Create a vertex.
  26125. var normal = new BABYLON.Vector3(dx, dy, 0);
  26126. var position = normal.scale(thickness / 2);
  26127. var textureCoordinate = new BABYLON.Vector2(u, v);
  26128. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26129. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26130. positions.push(position.x, position.y, position.z);
  26131. normals.push(normal.x, normal.y, normal.z);
  26132. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26133. // And create indices for two triangles.
  26134. var nextI = (i + 1) % stride;
  26135. var nextJ = (j + 1) % stride;
  26136. indices.push(i * stride + j);
  26137. indices.push(i * stride + nextJ);
  26138. indices.push(nextI * stride + j);
  26139. indices.push(i * stride + nextJ);
  26140. indices.push(nextI * stride + nextJ);
  26141. indices.push(nextI * stride + j);
  26142. }
  26143. }
  26144. // Sides
  26145. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26146. // Result
  26147. var vertexData = new VertexData();
  26148. vertexData.indices = indices;
  26149. vertexData.positions = positions;
  26150. vertexData.normals = normals;
  26151. vertexData.uvs = uvs;
  26152. return vertexData;
  26153. };
  26154. /**
  26155. * Creates the VertexData of the LineSystem.
  26156. */
  26157. VertexData.CreateLineSystem = function (options) {
  26158. var indices = [];
  26159. var positions = [];
  26160. var lines = options.lines;
  26161. var idx = 0;
  26162. for (var l = 0; l < lines.length; l++) {
  26163. var points = lines[l];
  26164. for (var index = 0; index < points.length; index++) {
  26165. positions.push(points[index].x, points[index].y, points[index].z);
  26166. if (index > 0) {
  26167. indices.push(idx - 1);
  26168. indices.push(idx);
  26169. }
  26170. idx++;
  26171. }
  26172. }
  26173. var vertexData = new VertexData();
  26174. vertexData.indices = indices;
  26175. vertexData.positions = positions;
  26176. return vertexData;
  26177. };
  26178. /**
  26179. * Create the VertexData of the DashedLines.
  26180. */
  26181. VertexData.CreateDashedLines = function (options) {
  26182. var dashSize = options.dashSize || 3;
  26183. var gapSize = options.gapSize || 1;
  26184. var dashNb = options.dashNb || 200;
  26185. var points = options.points;
  26186. var positions = new Array();
  26187. var indices = new Array();
  26188. var curvect = BABYLON.Vector3.Zero();
  26189. var lg = 0;
  26190. var nb = 0;
  26191. var shft = 0;
  26192. var dashshft = 0;
  26193. var curshft = 0;
  26194. var idx = 0;
  26195. var i = 0;
  26196. for (i = 0; i < points.length - 1; i++) {
  26197. points[i + 1].subtractToRef(points[i], curvect);
  26198. lg += curvect.length();
  26199. }
  26200. shft = lg / dashNb;
  26201. dashshft = dashSize * shft / (dashSize + gapSize);
  26202. for (i = 0; i < points.length - 1; i++) {
  26203. points[i + 1].subtractToRef(points[i], curvect);
  26204. nb = Math.floor(curvect.length() / shft);
  26205. curvect.normalize();
  26206. for (var j = 0; j < nb; j++) {
  26207. curshft = shft * j;
  26208. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26209. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26210. indices.push(idx, idx + 1);
  26211. idx += 2;
  26212. }
  26213. }
  26214. // Result
  26215. var vertexData = new VertexData();
  26216. vertexData.positions = positions;
  26217. vertexData.indices = indices;
  26218. return vertexData;
  26219. };
  26220. /**
  26221. * Creates the VertexData of the Ground.
  26222. */
  26223. VertexData.CreateGround = function (options) {
  26224. var indices = [];
  26225. var positions = [];
  26226. var normals = [];
  26227. var uvs = [];
  26228. var row, col;
  26229. var width = options.width || 1;
  26230. var height = options.height || 1;
  26231. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26232. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26233. for (row = 0; row <= subdivisionsY; row++) {
  26234. for (col = 0; col <= subdivisionsX; col++) {
  26235. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26236. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26237. positions.push(position.x, position.y, position.z);
  26238. normals.push(normal.x, normal.y, normal.z);
  26239. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26240. }
  26241. }
  26242. for (row = 0; row < subdivisionsY; row++) {
  26243. for (col = 0; col < subdivisionsX; col++) {
  26244. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26245. indices.push(col + 1 + row * (subdivisionsX + 1));
  26246. indices.push(col + row * (subdivisionsX + 1));
  26247. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26248. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26249. indices.push(col + row * (subdivisionsX + 1));
  26250. }
  26251. }
  26252. // Result
  26253. var vertexData = new VertexData();
  26254. vertexData.indices = indices;
  26255. vertexData.positions = positions;
  26256. vertexData.normals = normals;
  26257. vertexData.uvs = uvs;
  26258. return vertexData;
  26259. };
  26260. /**
  26261. * Creates the VertexData of the TiledGround.
  26262. */
  26263. VertexData.CreateTiledGround = function (options) {
  26264. var xmin = options.xmin || -1.0;
  26265. var zmin = options.zmin || -1.0;
  26266. var xmax = options.xmax || 1.0;
  26267. var zmax = options.zmax || 1.0;
  26268. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26269. var precision = options.precision || { w: 1, h: 1 };
  26270. var indices = [];
  26271. var positions = [];
  26272. var normals = [];
  26273. var uvs = [];
  26274. var row, col, tileRow, tileCol;
  26275. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26276. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26277. precision.w = (precision.w < 1) ? 1 : precision.w;
  26278. precision.h = (precision.h < 1) ? 1 : precision.h;
  26279. var tileSize = {
  26280. 'w': (xmax - xmin) / subdivisions.w,
  26281. 'h': (zmax - zmin) / subdivisions.h
  26282. };
  26283. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26284. // Indices
  26285. var base = positions.length / 3;
  26286. var rowLength = precision.w + 1;
  26287. for (row = 0; row < precision.h; row++) {
  26288. for (col = 0; col < precision.w; col++) {
  26289. var square = [
  26290. base + col + row * rowLength,
  26291. base + (col + 1) + row * rowLength,
  26292. base + (col + 1) + (row + 1) * rowLength,
  26293. base + col + (row + 1) * rowLength
  26294. ];
  26295. indices.push(square[1]);
  26296. indices.push(square[2]);
  26297. indices.push(square[3]);
  26298. indices.push(square[0]);
  26299. indices.push(square[1]);
  26300. indices.push(square[3]);
  26301. }
  26302. }
  26303. // Position, normals and uvs
  26304. var position = BABYLON.Vector3.Zero();
  26305. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26306. for (row = 0; row <= precision.h; row++) {
  26307. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26308. for (col = 0; col <= precision.w; col++) {
  26309. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26310. position.y = 0;
  26311. positions.push(position.x, position.y, position.z);
  26312. normals.push(normal.x, normal.y, normal.z);
  26313. uvs.push(col / precision.w, row / precision.h);
  26314. }
  26315. }
  26316. }
  26317. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26318. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26319. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26320. }
  26321. }
  26322. // Result
  26323. var vertexData = new VertexData();
  26324. vertexData.indices = indices;
  26325. vertexData.positions = positions;
  26326. vertexData.normals = normals;
  26327. vertexData.uvs = uvs;
  26328. return vertexData;
  26329. };
  26330. /**
  26331. * Creates the VertexData of the Ground designed from a heightmap.
  26332. */
  26333. VertexData.CreateGroundFromHeightMap = function (options) {
  26334. var indices = [];
  26335. var positions = [];
  26336. var normals = [];
  26337. var uvs = [];
  26338. var row, col;
  26339. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26340. // Vertices
  26341. for (row = 0; row <= options.subdivisions; row++) {
  26342. for (col = 0; col <= options.subdivisions; col++) {
  26343. 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));
  26344. // Compute height
  26345. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26346. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26347. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26348. var r = options.buffer[pos] / 255.0;
  26349. var g = options.buffer[pos + 1] / 255.0;
  26350. var b = options.buffer[pos + 2] / 255.0;
  26351. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26352. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26353. // Add vertex
  26354. positions.push(position.x, position.y, position.z);
  26355. normals.push(0, 0, 0);
  26356. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26357. }
  26358. }
  26359. // Indices
  26360. for (row = 0; row < options.subdivisions; row++) {
  26361. for (col = 0; col < options.subdivisions; col++) {
  26362. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26363. indices.push(col + 1 + row * (options.subdivisions + 1));
  26364. indices.push(col + row * (options.subdivisions + 1));
  26365. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26366. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26367. indices.push(col + row * (options.subdivisions + 1));
  26368. }
  26369. }
  26370. // Normals
  26371. VertexData.ComputeNormals(positions, indices, normals);
  26372. // Result
  26373. var vertexData = new VertexData();
  26374. vertexData.indices = indices;
  26375. vertexData.positions = positions;
  26376. vertexData.normals = normals;
  26377. vertexData.uvs = uvs;
  26378. return vertexData;
  26379. };
  26380. /**
  26381. * Creates the VertexData of the Plane.
  26382. */
  26383. VertexData.CreatePlane = function (options) {
  26384. var indices = [];
  26385. var positions = [];
  26386. var normals = [];
  26387. var uvs = [];
  26388. var width = options.width || options.size || 1;
  26389. var height = options.height || options.size || 1;
  26390. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26391. // Vertices
  26392. var halfWidth = width / 2.0;
  26393. var halfHeight = height / 2.0;
  26394. positions.push(-halfWidth, -halfHeight, 0);
  26395. normals.push(0, 0, -1.0);
  26396. uvs.push(0.0, 0.0);
  26397. positions.push(halfWidth, -halfHeight, 0);
  26398. normals.push(0, 0, -1.0);
  26399. uvs.push(1.0, 0.0);
  26400. positions.push(halfWidth, halfHeight, 0);
  26401. normals.push(0, 0, -1.0);
  26402. uvs.push(1.0, 1.0);
  26403. positions.push(-halfWidth, halfHeight, 0);
  26404. normals.push(0, 0, -1.0);
  26405. uvs.push(0.0, 1.0);
  26406. // Indices
  26407. indices.push(0);
  26408. indices.push(1);
  26409. indices.push(2);
  26410. indices.push(0);
  26411. indices.push(2);
  26412. indices.push(3);
  26413. // Sides
  26414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26415. // Result
  26416. var vertexData = new VertexData();
  26417. vertexData.indices = indices;
  26418. vertexData.positions = positions;
  26419. vertexData.normals = normals;
  26420. vertexData.uvs = uvs;
  26421. return vertexData;
  26422. };
  26423. /**
  26424. * Creates the VertexData of the Disc or regular Polygon.
  26425. */
  26426. VertexData.CreateDisc = function (options) {
  26427. var positions = [];
  26428. var indices = [];
  26429. var normals = [];
  26430. var uvs = [];
  26431. var radius = options.radius || 0.5;
  26432. var tessellation = options.tessellation || 64;
  26433. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26434. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26435. // positions and uvs
  26436. positions.push(0, 0, 0); // disc center first
  26437. uvs.push(0.5, 0.5);
  26438. var theta = Math.PI * 2 * arc;
  26439. var step = theta / tessellation;
  26440. for (var a = 0; a < theta; a += step) {
  26441. var x = Math.cos(a);
  26442. var y = Math.sin(a);
  26443. var u = (x + 1) / 2;
  26444. var v = (1 - y) / 2;
  26445. positions.push(radius * x, radius * y, 0);
  26446. uvs.push(u, v);
  26447. }
  26448. if (arc === 1) {
  26449. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26450. uvs.push(uvs[2], uvs[3]);
  26451. }
  26452. //indices
  26453. var vertexNb = positions.length / 3;
  26454. for (var i = 1; i < vertexNb - 1; i++) {
  26455. indices.push(i + 1, 0, i);
  26456. }
  26457. // result
  26458. VertexData.ComputeNormals(positions, indices, normals);
  26459. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26460. var vertexData = new VertexData();
  26461. vertexData.indices = indices;
  26462. vertexData.positions = positions;
  26463. vertexData.normals = normals;
  26464. vertexData.uvs = uvs;
  26465. return vertexData;
  26466. };
  26467. /**
  26468. * Re-creates the VertexData of the Polygon for sideOrientation.
  26469. */
  26470. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26471. var faceUV = fUV || new Array(3);
  26472. var faceColors = fColors;
  26473. var colors = [];
  26474. // default face colors and UV if undefined
  26475. for (var f = 0; f < 3; f++) {
  26476. if (faceUV[f] === undefined) {
  26477. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26478. }
  26479. if (faceColors && faceColors[f] === undefined) {
  26480. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26481. }
  26482. }
  26483. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26484. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26485. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26486. var indices = polygon.getIndices();
  26487. // set face colours and textures
  26488. var idx = 0;
  26489. var face = 0;
  26490. for (var index = 0; index < normals.length; index += 3) {
  26491. //Edge Face no. 1
  26492. if (Math.abs(normals[index + 1]) == 0) {
  26493. face = 1;
  26494. }
  26495. //Top Face no. 0
  26496. if (normals[index + 1] == 1) {
  26497. face = 0;
  26498. }
  26499. //Bottom Face no. 2
  26500. if (normals[index + 1] == -1) {
  26501. face = 2;
  26502. }
  26503. idx = index / 3;
  26504. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26505. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26506. if (faceColors) {
  26507. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26508. }
  26509. }
  26510. // sides
  26511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26512. // Result
  26513. var vertexData = new VertexData();
  26514. vertexData.indices = indices;
  26515. vertexData.positions = positions;
  26516. vertexData.normals = normals;
  26517. vertexData.uvs = uvs;
  26518. if (faceColors) {
  26519. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26520. vertexData.colors = totalColors;
  26521. }
  26522. return vertexData;
  26523. };
  26524. /**
  26525. * Creates the VertexData of the IcoSphere.
  26526. */
  26527. VertexData.CreateIcoSphere = function (options) {
  26528. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26529. var radius = options.radius || 1;
  26530. var flat = (options.flat === undefined) ? true : options.flat;
  26531. var subdivisions = options.subdivisions || 4;
  26532. var radiusX = options.radiusX || radius;
  26533. var radiusY = options.radiusY || radius;
  26534. var radiusZ = options.radiusZ || radius;
  26535. var t = (1 + Math.sqrt(5)) / 2;
  26536. // 12 vertex x,y,z
  26537. var ico_vertices = [
  26538. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26539. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26540. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26541. ];
  26542. // index of 3 vertex makes a face of icopshere
  26543. var ico_indices = [
  26544. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26545. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26546. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26547. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26548. ];
  26549. // vertex for uv have aliased position, not for UV
  26550. var vertices_unalias_id = [
  26551. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26552. // vertex alias
  26553. 0,
  26554. 2,
  26555. 3,
  26556. 3,
  26557. 3,
  26558. 4,
  26559. 7,
  26560. 8,
  26561. 9,
  26562. 9,
  26563. 10,
  26564. 11 // 23: B + 12
  26565. ];
  26566. // uv as integer step (not pixels !)
  26567. var ico_vertexuv = [
  26568. 5, 1, 3, 1, 6, 4, 0, 0,
  26569. 5, 3, 4, 2, 2, 2, 4, 0,
  26570. 2, 0, 1, 1, 6, 0, 6, 2,
  26571. // vertex alias (for same vertex on different faces)
  26572. 0, 4,
  26573. 3, 3,
  26574. 4, 4,
  26575. 3, 1,
  26576. 4, 2,
  26577. 4, 4,
  26578. 0, 2,
  26579. 1, 1,
  26580. 2, 2,
  26581. 3, 3,
  26582. 1, 3,
  26583. 2, 4 // 23: B + 12
  26584. ];
  26585. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26586. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26587. // First island of uv mapping
  26588. // v = 4h 3+ 2
  26589. // v = 3h 9+ 4
  26590. // v = 2h 9+ 5 B
  26591. // v = 1h 9 1 0
  26592. // v = 0h 3 8 7 A
  26593. // u = 0 1 2 3 4 5 6 *a
  26594. // Second island of uv mapping
  26595. // v = 4h 0+ B+ 4+
  26596. // v = 3h A+ 2+
  26597. // v = 2h 7+ 6 3+
  26598. // v = 1h 8+ 3+
  26599. // v = 0h
  26600. // u = 0 1 2 3 4 5 6 *a
  26601. // Face layout on texture UV mapping
  26602. // ============
  26603. // \ 4 /\ 16 / ======
  26604. // \ / \ / /\ 11 /
  26605. // \/ 7 \/ / \ /
  26606. // ======= / 10 \/
  26607. // /\ 17 /\ =======
  26608. // / \ / \ \ 15 /\
  26609. // / 8 \/ 12 \ \ / \
  26610. // ============ \/ 6 \
  26611. // \ 18 /\ ============
  26612. // \ / \ \ 5 /\ 0 /
  26613. // \/ 13 \ \ / \ /
  26614. // ======= \/ 1 \/
  26615. // =============
  26616. // /\ 19 /\ 2 /\
  26617. // / \ / \ / \
  26618. // / 14 \/ 9 \/ 3 \
  26619. // ===================
  26620. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26621. var ustep = 138 / 1024;
  26622. var vstep = 239 / 1024;
  26623. var uoffset = 60 / 1024;
  26624. var voffset = 26 / 1024;
  26625. // Second island should have margin, not to touch the first island
  26626. // avoid any borderline artefact in pixel rounding
  26627. var island_u_offset = -40 / 1024;
  26628. var island_v_offset = +20 / 1024;
  26629. // face is either island 0 or 1 :
  26630. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26631. var island = [
  26632. 0, 0, 0, 0, 1,
  26633. 0, 0, 1, 1, 0,
  26634. 0, 0, 1, 1, 0,
  26635. 0, 1, 1, 1, 0 // 15 - 19
  26636. ];
  26637. var indices = [];
  26638. var positions = [];
  26639. var normals = [];
  26640. var uvs = [];
  26641. var current_indice = 0;
  26642. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26643. var face_vertex_pos = new Array(3);
  26644. var face_vertex_uv = new Array(3);
  26645. var v012;
  26646. for (v012 = 0; v012 < 3; v012++) {
  26647. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26648. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26649. }
  26650. // create all with normals
  26651. for (var face = 0; face < 20; face++) {
  26652. // 3 vertex per face
  26653. for (v012 = 0; v012 < 3; v012++) {
  26654. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26655. var v_id = ico_indices[3 * face + v012];
  26656. // vertex have 3D position (x,y,z)
  26657. 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]);
  26658. // Normalize to get normal, then scale to radius
  26659. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26660. // uv Coordinates from vertex ID
  26661. 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);
  26662. }
  26663. // Subdivide the face (interpolate pos, norm, uv)
  26664. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26665. // - norm is linear interpolation of vertex corner normal
  26666. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26667. // - uv is linear interpolation
  26668. //
  26669. // Topology is as below for sub-divide by 2
  26670. // vertex shown as v0,v1,v2
  26671. // interp index is i1 to progress in range [v0,v1[
  26672. // interp index is i2 to progress in range [v0,v2[
  26673. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26674. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26675. //
  26676. //
  26677. // i2 v2
  26678. // ^ ^
  26679. // / / \
  26680. // / / \
  26681. // / / \
  26682. // / / (0,1) \
  26683. // / #---------\
  26684. // / / \ (0,0)'/ \
  26685. // / / \ / \
  26686. // / / \ / \
  26687. // / / (0,0) \ / (1,0) \
  26688. // / #---------#---------\
  26689. // v0 v1
  26690. //
  26691. // --------------------> i1
  26692. //
  26693. // interp of (i1,i2):
  26694. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26695. // along i1 : lerp(x0,x1, i1/(S-i2))
  26696. //
  26697. // centroid of triangle is needed to get help normal computation
  26698. // (c1,c2) are used for centroid location
  26699. var interp_vertex = function (i1, i2, c1, c2) {
  26700. // vertex is interpolated from
  26701. // - face_vertex_pos[0..2]
  26702. // - face_vertex_uv[0..2]
  26703. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26704. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26705. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26706. pos_interp.normalize();
  26707. var vertex_normal;
  26708. if (flat) {
  26709. // in flat mode, recalculate normal as face centroid normal
  26710. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26711. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26712. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26713. }
  26714. else {
  26715. // in smooth mode, recalculate normal from each single vertex position
  26716. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26717. }
  26718. // Vertex normal need correction due to X,Y,Z radius scaling
  26719. vertex_normal.x /= radiusX;
  26720. vertex_normal.y /= radiusY;
  26721. vertex_normal.z /= radiusZ;
  26722. vertex_normal.normalize();
  26723. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26724. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26725. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26726. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26727. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26728. uvs.push(uv_interp.x, uv_interp.y);
  26729. // push each vertex has member of a face
  26730. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26731. indices.push(current_indice);
  26732. current_indice++;
  26733. };
  26734. for (var i2 = 0; i2 < subdivisions; i2++) {
  26735. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26736. // face : (i1,i2) for /\ :
  26737. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26738. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26739. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26740. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26741. if (i1 + i2 + 1 < subdivisions) {
  26742. // face : (i1,i2)' for \/ :
  26743. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26744. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26745. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26746. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26747. }
  26748. }
  26749. }
  26750. }
  26751. // Sides
  26752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26753. // Result
  26754. var vertexData = new VertexData();
  26755. vertexData.indices = indices;
  26756. vertexData.positions = positions;
  26757. vertexData.normals = normals;
  26758. vertexData.uvs = uvs;
  26759. return vertexData;
  26760. };
  26761. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26762. /**
  26763. * Creates the VertexData of the Polyhedron.
  26764. */
  26765. VertexData.CreatePolyhedron = function (options) {
  26766. // provided polyhedron types :
  26767. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26768. // 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)
  26769. var polyhedra = [];
  26770. 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]] };
  26771. 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]] };
  26772. polyhedra[2] = {
  26773. 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]],
  26774. 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]]
  26775. };
  26776. polyhedra[3] = {
  26777. 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]],
  26778. 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]]
  26779. };
  26780. polyhedra[4] = {
  26781. 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]],
  26782. 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]]
  26783. };
  26784. 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]] };
  26785. 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]] };
  26786. 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]] };
  26787. 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]] };
  26788. 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]] };
  26789. 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]] };
  26790. 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]] };
  26791. 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]] };
  26792. 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]] };
  26793. polyhedra[14] = {
  26794. 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]],
  26795. 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]]
  26796. };
  26797. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26798. var size = options.size;
  26799. var sizeX = options.sizeX || size || 1;
  26800. var sizeY = options.sizeY || size || 1;
  26801. var sizeZ = options.sizeZ || size || 1;
  26802. var data = options.custom || polyhedra[type];
  26803. var nbfaces = data.face.length;
  26804. var faceUV = options.faceUV || new Array(nbfaces);
  26805. var faceColors = options.faceColors;
  26806. var flat = (options.flat === undefined) ? true : options.flat;
  26807. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26808. var positions = [];
  26809. var indices = [];
  26810. var normals = [];
  26811. var uvs = [];
  26812. var colors = [];
  26813. var index = 0;
  26814. var faceIdx = 0; // face cursor in the array "indexes"
  26815. var indexes = [];
  26816. var i = 0;
  26817. var f = 0;
  26818. var u, v, ang, x, y, tmp;
  26819. // default face colors and UV if undefined
  26820. if (flat) {
  26821. for (f = 0; f < nbfaces; f++) {
  26822. if (faceColors && faceColors[f] === undefined) {
  26823. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26824. }
  26825. if (faceUV && faceUV[f] === undefined) {
  26826. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26827. }
  26828. }
  26829. }
  26830. if (!flat) {
  26831. for (i = 0; i < data.vertex.length; i++) {
  26832. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26833. uvs.push(0, 0);
  26834. }
  26835. for (f = 0; f < nbfaces; f++) {
  26836. for (i = 0; i < data.face[f].length - 2; i++) {
  26837. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26838. }
  26839. }
  26840. }
  26841. else {
  26842. for (f = 0; f < nbfaces; f++) {
  26843. var fl = data.face[f].length; // number of vertices of the current face
  26844. ang = 2 * Math.PI / fl;
  26845. x = 0.5 * Math.tan(ang / 2);
  26846. y = 0.5;
  26847. // positions, uvs, colors
  26848. for (i = 0; i < fl; i++) {
  26849. // positions
  26850. 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);
  26851. indexes.push(index);
  26852. index++;
  26853. // uvs
  26854. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26855. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26856. uvs.push(u, v);
  26857. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26858. y = x * Math.sin(ang) + y * Math.cos(ang);
  26859. x = tmp;
  26860. // colors
  26861. if (faceColors) {
  26862. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26863. }
  26864. }
  26865. // indices from indexes
  26866. for (i = 0; i < fl - 2; i++) {
  26867. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26868. }
  26869. faceIdx += fl;
  26870. }
  26871. }
  26872. VertexData.ComputeNormals(positions, indices, normals);
  26873. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26874. var vertexData = new VertexData();
  26875. vertexData.positions = positions;
  26876. vertexData.indices = indices;
  26877. vertexData.normals = normals;
  26878. vertexData.uvs = uvs;
  26879. if (faceColors && flat) {
  26880. vertexData.colors = colors;
  26881. }
  26882. return vertexData;
  26883. };
  26884. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26885. /**
  26886. * Creates the VertexData of the Torus Knot.
  26887. */
  26888. VertexData.CreateTorusKnot = function (options) {
  26889. var indices = [];
  26890. var positions = [];
  26891. var normals = [];
  26892. var uvs = [];
  26893. var radius = options.radius || 2;
  26894. var tube = options.tube || 0.5;
  26895. var radialSegments = options.radialSegments || 32;
  26896. var tubularSegments = options.tubularSegments || 32;
  26897. var p = options.p || 2;
  26898. var q = options.q || 3;
  26899. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26900. // Helper
  26901. var getPos = function (angle) {
  26902. var cu = Math.cos(angle);
  26903. var su = Math.sin(angle);
  26904. var quOverP = q / p * angle;
  26905. var cs = Math.cos(quOverP);
  26906. var tx = radius * (2 + cs) * 0.5 * cu;
  26907. var ty = radius * (2 + cs) * su * 0.5;
  26908. var tz = radius * Math.sin(quOverP) * 0.5;
  26909. return new BABYLON.Vector3(tx, ty, tz);
  26910. };
  26911. // Vertices
  26912. var i;
  26913. var j;
  26914. for (i = 0; i <= radialSegments; i++) {
  26915. var modI = i % radialSegments;
  26916. var u = modI / radialSegments * 2 * p * Math.PI;
  26917. var p1 = getPos(u);
  26918. var p2 = getPos(u + 0.01);
  26919. var tang = p2.subtract(p1);
  26920. var n = p2.add(p1);
  26921. var bitan = BABYLON.Vector3.Cross(tang, n);
  26922. n = BABYLON.Vector3.Cross(bitan, tang);
  26923. bitan.normalize();
  26924. n.normalize();
  26925. for (j = 0; j < tubularSegments; j++) {
  26926. var modJ = j % tubularSegments;
  26927. var v = modJ / tubularSegments * 2 * Math.PI;
  26928. var cx = -tube * Math.cos(v);
  26929. var cy = tube * Math.sin(v);
  26930. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26931. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26932. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26933. uvs.push(i / radialSegments);
  26934. uvs.push(j / tubularSegments);
  26935. }
  26936. }
  26937. for (i = 0; i < radialSegments; i++) {
  26938. for (j = 0; j < tubularSegments; j++) {
  26939. var jNext = (j + 1) % tubularSegments;
  26940. var a = i * tubularSegments + j;
  26941. var b = (i + 1) * tubularSegments + j;
  26942. var c = (i + 1) * tubularSegments + jNext;
  26943. var d = i * tubularSegments + jNext;
  26944. indices.push(d);
  26945. indices.push(b);
  26946. indices.push(a);
  26947. indices.push(d);
  26948. indices.push(c);
  26949. indices.push(b);
  26950. }
  26951. }
  26952. // Normals
  26953. VertexData.ComputeNormals(positions, indices, normals);
  26954. // Sides
  26955. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26956. // Result
  26957. var vertexData = new VertexData();
  26958. vertexData.indices = indices;
  26959. vertexData.positions = positions;
  26960. vertexData.normals = normals;
  26961. vertexData.uvs = uvs;
  26962. return vertexData;
  26963. };
  26964. // Tools
  26965. /**
  26966. * @param {any} - positions (number[] or Float32Array)
  26967. * @param {any} - indices (number[] or Uint16Array)
  26968. * @param {any} - normals (number[] or Float32Array)
  26969. * options (optional) :
  26970. * facetPositions : optional array of facet positions (vector3)
  26971. * facetNormals : optional array of facet normals (vector3)
  26972. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26973. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26974. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26975. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26976. * bInfo : optional bounding info, required for facetPartitioning computation
  26977. */
  26978. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26979. // temporary scalar variables
  26980. var index = 0; // facet index
  26981. var p1p2x = 0.0; // p1p2 vector x coordinate
  26982. var p1p2y = 0.0; // p1p2 vector y coordinate
  26983. var p1p2z = 0.0; // p1p2 vector z coordinate
  26984. var p3p2x = 0.0; // p3p2 vector x coordinate
  26985. var p3p2y = 0.0; // p3p2 vector y coordinate
  26986. var p3p2z = 0.0; // p3p2 vector z coordinate
  26987. var faceNormalx = 0.0; // facet normal x coordinate
  26988. var faceNormaly = 0.0; // facet normal y coordinate
  26989. var faceNormalz = 0.0; // facet normal z coordinate
  26990. var length = 0.0; // facet normal length before normalization
  26991. var v1x = 0; // vector1 x index in the positions array
  26992. var v1y = 0; // vector1 y index in the positions array
  26993. var v1z = 0; // vector1 z index in the positions array
  26994. var v2x = 0; // vector2 x index in the positions array
  26995. var v2y = 0; // vector2 y index in the positions array
  26996. var v2z = 0; // vector2 z index in the positions array
  26997. var v3x = 0; // vector3 x index in the positions array
  26998. var v3y = 0; // vector3 y index in the positions array
  26999. var v3z = 0; // vector3 z index in the positions array
  27000. var computeFacetNormals = false;
  27001. var computeFacetPositions = false;
  27002. var computeFacetPartitioning = false;
  27003. var faceNormalSign = 1;
  27004. if (options) {
  27005. computeFacetNormals = (options.facetNormals) ? true : false;
  27006. computeFacetPositions = (options.facetPositions) ? true : false;
  27007. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  27008. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  27009. }
  27010. // facetPartitioning reinit if needed
  27011. if (computeFacetPartitioning) {
  27012. var ox = 0; // X partitioning index for facet position
  27013. var oy = 0; // Y partinioning index for facet position
  27014. var oz = 0; // Z partinioning index for facet position
  27015. var b1x = 0; // X partitioning index for facet v1 vertex
  27016. var b1y = 0; // Y partitioning index for facet v1 vertex
  27017. var b1z = 0; // z partitioning index for facet v1 vertex
  27018. var b2x = 0; // X partitioning index for facet v2 vertex
  27019. var b2y = 0; // Y partitioning index for facet v2 vertex
  27020. var b2z = 0; // Z partitioning index for facet v2 vertex
  27021. var b3x = 0; // X partitioning index for facet v3 vertex
  27022. var b3y = 0; // Y partitioning index for facet v3 vertex
  27023. var b3z = 0; // Z partitioning index for facet v3 vertex
  27024. var block_idx_o = 0; // facet barycenter block index
  27025. var block_idx_v1 = 0; // v1 vertex block index
  27026. var block_idx_v2 = 0; // v2 vertex block index
  27027. var block_idx_v3 = 0; // v3 vertex block index
  27028. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  27029. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  27030. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  27031. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  27032. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  27033. var subSq = options.subDiv.max * options.subDiv.max;
  27034. options.facetPartitioning.length = 0;
  27035. }
  27036. // reset the normals
  27037. for (index = 0; index < positions.length; index++) {
  27038. normals[index] = 0.0;
  27039. }
  27040. // Loop : 1 indice triplet = 1 facet
  27041. var nbFaces = indices.length / 3;
  27042. for (index = 0; index < nbFaces; index++) {
  27043. // get the indexes of the coordinates of each vertex of the facet
  27044. v1x = indices[index * 3] * 3;
  27045. v1y = v1x + 1;
  27046. v1z = v1x + 2;
  27047. v2x = indices[index * 3 + 1] * 3;
  27048. v2y = v2x + 1;
  27049. v2z = v2x + 2;
  27050. v3x = indices[index * 3 + 2] * 3;
  27051. v3y = v3x + 1;
  27052. v3z = v3x + 2;
  27053. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  27054. p1p2y = positions[v1y] - positions[v2y];
  27055. p1p2z = positions[v1z] - positions[v2z];
  27056. p3p2x = positions[v3x] - positions[v2x];
  27057. p3p2y = positions[v3y] - positions[v2y];
  27058. p3p2z = positions[v3z] - positions[v2z];
  27059. // compute the face normal with the cross product
  27060. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  27061. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  27062. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  27063. // normalize this normal and store it in the array facetData
  27064. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27065. length = (length === 0) ? 1.0 : length;
  27066. faceNormalx /= length;
  27067. faceNormaly /= length;
  27068. faceNormalz /= length;
  27069. if (computeFacetNormals) {
  27070. options.facetNormals[index].x = faceNormalx;
  27071. options.facetNormals[index].y = faceNormaly;
  27072. options.facetNormals[index].z = faceNormalz;
  27073. }
  27074. if (computeFacetPositions) {
  27075. // compute and the facet barycenter coordinates in the array facetPositions
  27076. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  27077. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  27078. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  27079. }
  27080. if (computeFacetPartitioning) {
  27081. // store the facet indexes in arrays in the main facetPartitioning array :
  27082. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  27083. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27084. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27085. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27086. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27087. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27088. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27089. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27090. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27091. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27092. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  27093. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  27094. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  27095. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  27096. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  27097. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  27098. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  27099. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  27100. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  27101. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  27102. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  27103. // push each facet index in each block containing the vertex
  27104. options.facetPartitioning[block_idx_v1].push(index);
  27105. if (block_idx_v2 != block_idx_v1) {
  27106. options.facetPartitioning[block_idx_v2].push(index);
  27107. }
  27108. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  27109. options.facetPartitioning[block_idx_v3].push(index);
  27110. }
  27111. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  27112. options.facetPartitioning[block_idx_o].push(index);
  27113. }
  27114. }
  27115. // compute the normals anyway
  27116. normals[v1x] += faceNormalx; // accumulate all the normals per face
  27117. normals[v1y] += faceNormaly;
  27118. normals[v1z] += faceNormalz;
  27119. normals[v2x] += faceNormalx;
  27120. normals[v2y] += faceNormaly;
  27121. normals[v2z] += faceNormalz;
  27122. normals[v3x] += faceNormalx;
  27123. normals[v3y] += faceNormaly;
  27124. normals[v3z] += faceNormalz;
  27125. }
  27126. // last normalization of each normal
  27127. for (index = 0; index < normals.length / 3; index++) {
  27128. faceNormalx = normals[index * 3];
  27129. faceNormaly = normals[index * 3 + 1];
  27130. faceNormalz = normals[index * 3 + 2];
  27131. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  27132. length = (length === 0) ? 1.0 : length;
  27133. faceNormalx /= length;
  27134. faceNormaly /= length;
  27135. faceNormalz /= length;
  27136. normals[index * 3] = faceNormalx;
  27137. normals[index * 3 + 1] = faceNormaly;
  27138. normals[index * 3 + 2] = faceNormalz;
  27139. }
  27140. };
  27141. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  27142. var li = indices.length;
  27143. var ln = normals.length;
  27144. var i;
  27145. var n;
  27146. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27147. switch (sideOrientation) {
  27148. case BABYLON.Mesh.FRONTSIDE:
  27149. // nothing changed
  27150. break;
  27151. case BABYLON.Mesh.BACKSIDE:
  27152. var tmp;
  27153. // indices
  27154. for (i = 0; i < li; i += 3) {
  27155. tmp = indices[i];
  27156. indices[i] = indices[i + 2];
  27157. indices[i + 2] = tmp;
  27158. }
  27159. // normals
  27160. for (n = 0; n < ln; n++) {
  27161. normals[n] = -normals[n];
  27162. }
  27163. break;
  27164. case BABYLON.Mesh.DOUBLESIDE:
  27165. // positions
  27166. var lp = positions.length;
  27167. var l = lp / 3;
  27168. for (var p = 0; p < lp; p++) {
  27169. positions[lp + p] = positions[p];
  27170. }
  27171. // indices
  27172. for (i = 0; i < li; i += 3) {
  27173. indices[i + li] = indices[i + 2] + l;
  27174. indices[i + 1 + li] = indices[i + 1] + l;
  27175. indices[i + 2 + li] = indices[i] + l;
  27176. }
  27177. // normals
  27178. for (n = 0; n < ln; n++) {
  27179. normals[ln + n] = -normals[n];
  27180. }
  27181. // uvs
  27182. var lu = uvs.length;
  27183. var u = 0;
  27184. for (u = 0; u < lu; u++) {
  27185. uvs[u + lu] = uvs[u];
  27186. }
  27187. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27188. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  27189. u = 0;
  27190. for (i = 0; i < lu / 2; i++) {
  27191. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  27192. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  27193. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  27194. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  27195. u += 2;
  27196. }
  27197. break;
  27198. }
  27199. };
  27200. /**
  27201. * Creates a new VertexData from the imported parameters.
  27202. */
  27203. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27204. var vertexData = new VertexData();
  27205. // positions
  27206. var positions = parsedVertexData.positions;
  27207. if (positions) {
  27208. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27209. }
  27210. // normals
  27211. var normals = parsedVertexData.normals;
  27212. if (normals) {
  27213. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27214. }
  27215. // tangents
  27216. var tangents = parsedVertexData.tangents;
  27217. if (tangents) {
  27218. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27219. }
  27220. // uvs
  27221. var uvs = parsedVertexData.uvs;
  27222. if (uvs) {
  27223. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27224. }
  27225. // uv2s
  27226. var uv2s = parsedVertexData.uv2s;
  27227. if (uv2s) {
  27228. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27229. }
  27230. // uv3s
  27231. var uv3s = parsedVertexData.uv3s;
  27232. if (uv3s) {
  27233. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27234. }
  27235. // uv4s
  27236. var uv4s = parsedVertexData.uv4s;
  27237. if (uv4s) {
  27238. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27239. }
  27240. // uv5s
  27241. var uv5s = parsedVertexData.uv5s;
  27242. if (uv5s) {
  27243. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27244. }
  27245. // uv6s
  27246. var uv6s = parsedVertexData.uv6s;
  27247. if (uv6s) {
  27248. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27249. }
  27250. // colors
  27251. var colors = parsedVertexData.colors;
  27252. if (colors) {
  27253. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27254. }
  27255. // matricesIndices
  27256. var matricesIndices = parsedVertexData.matricesIndices;
  27257. if (matricesIndices) {
  27258. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27259. }
  27260. // matricesWeights
  27261. var matricesWeights = parsedVertexData.matricesWeights;
  27262. if (matricesWeights) {
  27263. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27264. }
  27265. // indices
  27266. var indices = parsedVertexData.indices;
  27267. if (indices) {
  27268. vertexData.indices = indices;
  27269. }
  27270. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27271. };
  27272. return VertexData;
  27273. }());
  27274. BABYLON.VertexData = VertexData;
  27275. })(BABYLON || (BABYLON = {}));
  27276. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27277. var BABYLON;
  27278. (function (BABYLON) {
  27279. var Geometry = (function () {
  27280. function Geometry(id, scene, vertexData, updatable, mesh) {
  27281. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27282. this._totalVertices = 0;
  27283. this._isDisposed = false;
  27284. this.id = id;
  27285. this._engine = scene.getEngine();
  27286. this._meshes = [];
  27287. this._scene = scene;
  27288. //Init vertex buffer cache
  27289. this._vertexBuffers = {};
  27290. this._indices = [];
  27291. // vertexData
  27292. if (vertexData) {
  27293. this.setAllVerticesData(vertexData, updatable);
  27294. }
  27295. else {
  27296. this._totalVertices = 0;
  27297. this._indices = [];
  27298. }
  27299. if (this._engine.getCaps().vertexArrayObject) {
  27300. this._vertexArrayObjects = {};
  27301. }
  27302. // applyToMesh
  27303. if (mesh) {
  27304. if (mesh.getClassName() === "LinesMesh") {
  27305. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27306. this.updateExtend();
  27307. }
  27308. this.applyToMesh(mesh);
  27309. mesh.computeWorldMatrix(true);
  27310. }
  27311. }
  27312. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27313. /**
  27314. * 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
  27315. * @returns The Bias Vector
  27316. */
  27317. get: function () {
  27318. return this._boundingBias;
  27319. },
  27320. set: function (value) {
  27321. if (this._boundingBias && this._boundingBias.equals(value)) {
  27322. return;
  27323. }
  27324. this._boundingBias = value.clone();
  27325. this.updateBoundingInfo(true, null);
  27326. },
  27327. enumerable: true,
  27328. configurable: true
  27329. });
  27330. Object.defineProperty(Geometry.prototype, "extend", {
  27331. get: function () {
  27332. return this._extend;
  27333. },
  27334. enumerable: true,
  27335. configurable: true
  27336. });
  27337. Geometry.prototype.getScene = function () {
  27338. return this._scene;
  27339. };
  27340. Geometry.prototype.getEngine = function () {
  27341. return this._engine;
  27342. };
  27343. Geometry.prototype.isReady = function () {
  27344. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27345. };
  27346. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27347. get: function () {
  27348. for (var index = 0; index < this._meshes.length; index++) {
  27349. if (!this._meshes[index].doNotSerialize) {
  27350. return false;
  27351. }
  27352. }
  27353. return true;
  27354. },
  27355. enumerable: true,
  27356. configurable: true
  27357. });
  27358. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27359. vertexData.applyToGeometry(this, updatable);
  27360. this.notifyUpdate();
  27361. };
  27362. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27363. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27364. this.setVerticesBuffer(buffer);
  27365. };
  27366. Geometry.prototype.removeVerticesData = function (kind) {
  27367. if (this._vertexBuffers[kind]) {
  27368. this._vertexBuffers[kind].dispose();
  27369. delete this._vertexBuffers[kind];
  27370. }
  27371. };
  27372. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27373. var kind = buffer.getKind();
  27374. if (this._vertexBuffers[kind]) {
  27375. this._vertexBuffers[kind].dispose();
  27376. }
  27377. this._vertexBuffers[kind] = buffer;
  27378. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27379. var data = buffer.getData();
  27380. var stride = buffer.getStrideSize();
  27381. this._totalVertices = data.length / stride;
  27382. this.updateExtend(data, stride);
  27383. this._resetPointsArrayCache();
  27384. var meshes = this._meshes;
  27385. var numOfMeshes = meshes.length;
  27386. for (var index = 0; index < numOfMeshes; index++) {
  27387. var mesh = meshes[index];
  27388. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27389. mesh._createGlobalSubMesh();
  27390. mesh.computeWorldMatrix(true);
  27391. }
  27392. }
  27393. this.notifyUpdate(kind);
  27394. if (this._vertexArrayObjects) {
  27395. this._disposeVertexArrayObjects();
  27396. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27397. }
  27398. };
  27399. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27400. var vertexBuffer = this.getVertexBuffer(kind);
  27401. if (!vertexBuffer) {
  27402. return;
  27403. }
  27404. vertexBuffer.updateDirectly(data, offset);
  27405. this.notifyUpdate(kind);
  27406. };
  27407. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27408. var vertexBuffer = this.getVertexBuffer(kind);
  27409. if (!vertexBuffer) {
  27410. return;
  27411. }
  27412. vertexBuffer.update(data);
  27413. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27414. var stride = vertexBuffer.getStrideSize();
  27415. this._totalVertices = data.length / stride;
  27416. this.updateBoundingInfo(updateExtends, data);
  27417. }
  27418. this.notifyUpdate(kind);
  27419. };
  27420. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27421. if (updateExtends) {
  27422. this.updateExtend(data);
  27423. }
  27424. var meshes = this._meshes;
  27425. var numOfMeshes = meshes.length;
  27426. this._resetPointsArrayCache();
  27427. for (var index = 0; index < numOfMeshes; index++) {
  27428. var mesh = meshes[index];
  27429. if (updateExtends) {
  27430. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27431. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27432. var subMesh = mesh.subMeshes[subIndex];
  27433. subMesh.refreshBoundingInfo();
  27434. }
  27435. }
  27436. }
  27437. };
  27438. Geometry.prototype._bind = function (effect, indexToBind) {
  27439. if (indexToBind === void 0) { indexToBind = undefined; }
  27440. if (indexToBind === undefined) {
  27441. indexToBind = this._indexBuffer;
  27442. }
  27443. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27444. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27445. return;
  27446. }
  27447. // Using VAO
  27448. if (!this._vertexArrayObjects[effect.key]) {
  27449. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27450. }
  27451. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27452. };
  27453. Geometry.prototype.getTotalVertices = function () {
  27454. if (!this.isReady()) {
  27455. return 0;
  27456. }
  27457. return this._totalVertices;
  27458. };
  27459. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27460. var vertexBuffer = this.getVertexBuffer(kind);
  27461. if (!vertexBuffer) {
  27462. return null;
  27463. }
  27464. var orig = vertexBuffer.getData();
  27465. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27466. return orig;
  27467. }
  27468. else {
  27469. var len = orig.length;
  27470. var copy = [];
  27471. for (var i = 0; i < len; i++) {
  27472. copy.push(orig[i]);
  27473. }
  27474. return copy;
  27475. }
  27476. };
  27477. Geometry.prototype.getVertexBuffer = function (kind) {
  27478. if (!this.isReady()) {
  27479. return null;
  27480. }
  27481. return this._vertexBuffers[kind];
  27482. };
  27483. Geometry.prototype.getVertexBuffers = function () {
  27484. if (!this.isReady()) {
  27485. return null;
  27486. }
  27487. return this._vertexBuffers;
  27488. };
  27489. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27490. if (!this._vertexBuffers) {
  27491. if (this._delayInfo) {
  27492. return this._delayInfo.indexOf(kind) !== -1;
  27493. }
  27494. return false;
  27495. }
  27496. return this._vertexBuffers[kind] !== undefined;
  27497. };
  27498. Geometry.prototype.getVerticesDataKinds = function () {
  27499. var result = [];
  27500. var kind;
  27501. if (!this._vertexBuffers && this._delayInfo) {
  27502. for (kind in this._delayInfo) {
  27503. result.push(kind);
  27504. }
  27505. }
  27506. else {
  27507. for (kind in this._vertexBuffers) {
  27508. result.push(kind);
  27509. }
  27510. }
  27511. return result;
  27512. };
  27513. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27514. if (this._indexBuffer) {
  27515. this._engine._releaseBuffer(this._indexBuffer);
  27516. }
  27517. this._disposeVertexArrayObjects();
  27518. this._indices = indices;
  27519. if (this._meshes.length !== 0 && this._indices) {
  27520. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27521. }
  27522. if (totalVertices !== undefined) {
  27523. this._totalVertices = totalVertices;
  27524. }
  27525. var meshes = this._meshes;
  27526. var numOfMeshes = meshes.length;
  27527. for (var index = 0; index < numOfMeshes; index++) {
  27528. meshes[index]._createGlobalSubMesh();
  27529. }
  27530. this.notifyUpdate();
  27531. };
  27532. Geometry.prototype.getTotalIndices = function () {
  27533. if (!this.isReady()) {
  27534. return 0;
  27535. }
  27536. return this._indices.length;
  27537. };
  27538. Geometry.prototype.getIndices = function (copyWhenShared) {
  27539. if (!this.isReady()) {
  27540. return null;
  27541. }
  27542. var orig = this._indices;
  27543. if (!copyWhenShared || this._meshes.length === 1) {
  27544. return orig;
  27545. }
  27546. else {
  27547. var len = orig.length;
  27548. var copy = [];
  27549. for (var i = 0; i < len; i++) {
  27550. copy.push(orig[i]);
  27551. }
  27552. return copy;
  27553. }
  27554. };
  27555. Geometry.prototype.getIndexBuffer = function () {
  27556. if (!this.isReady()) {
  27557. return null;
  27558. }
  27559. return this._indexBuffer;
  27560. };
  27561. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27562. if (!effect || !this._vertexArrayObjects) {
  27563. return;
  27564. }
  27565. if (this._vertexArrayObjects[effect.key]) {
  27566. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27567. delete this._vertexArrayObjects[effect.key];
  27568. }
  27569. };
  27570. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27571. var meshes = this._meshes;
  27572. var index = meshes.indexOf(mesh);
  27573. if (index === -1) {
  27574. return;
  27575. }
  27576. meshes.splice(index, 1);
  27577. mesh._geometry = null;
  27578. if (meshes.length === 0 && shouldDispose) {
  27579. this.dispose();
  27580. }
  27581. };
  27582. Geometry.prototype.applyToMesh = function (mesh) {
  27583. if (mesh._geometry === this) {
  27584. return;
  27585. }
  27586. var previousGeometry = mesh._geometry;
  27587. if (previousGeometry) {
  27588. previousGeometry.releaseForMesh(mesh);
  27589. }
  27590. var meshes = this._meshes;
  27591. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27592. mesh._geometry = this;
  27593. this._scene.pushGeometry(this);
  27594. meshes.push(mesh);
  27595. if (this.isReady()) {
  27596. this._applyToMesh(mesh);
  27597. }
  27598. else {
  27599. mesh._boundingInfo = this._boundingInfo;
  27600. }
  27601. };
  27602. Geometry.prototype.updateExtend = function (data, stride) {
  27603. if (data === void 0) { data = null; }
  27604. if (!data) {
  27605. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27606. }
  27607. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27608. };
  27609. Geometry.prototype._applyToMesh = function (mesh) {
  27610. var numOfMeshes = this._meshes.length;
  27611. // vertexBuffers
  27612. for (var kind in this._vertexBuffers) {
  27613. if (numOfMeshes === 1) {
  27614. this._vertexBuffers[kind].create();
  27615. }
  27616. var buffer = this._vertexBuffers[kind].getBuffer();
  27617. if (buffer)
  27618. buffer.references = numOfMeshes;
  27619. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27620. if (!this._extend) {
  27621. this.updateExtend(this._vertexBuffers[kind].getData());
  27622. }
  27623. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27624. mesh._createGlobalSubMesh();
  27625. //bounding info was just created again, world matrix should be applied again.
  27626. mesh._updateBoundingInfo();
  27627. }
  27628. }
  27629. // indexBuffer
  27630. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27631. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27632. }
  27633. if (this._indexBuffer) {
  27634. this._indexBuffer.references = numOfMeshes;
  27635. }
  27636. };
  27637. Geometry.prototype.notifyUpdate = function (kind) {
  27638. if (this.onGeometryUpdated) {
  27639. this.onGeometryUpdated(this, kind);
  27640. }
  27641. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27642. var mesh = _a[_i];
  27643. mesh._markSubMeshesAsAttributesDirty();
  27644. }
  27645. };
  27646. Geometry.prototype.load = function (scene, onLoaded) {
  27647. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27648. return;
  27649. }
  27650. if (this.isReady()) {
  27651. if (onLoaded) {
  27652. onLoaded();
  27653. }
  27654. return;
  27655. }
  27656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27657. this._queueLoad(scene, onLoaded);
  27658. };
  27659. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27660. var _this = this;
  27661. scene._addPendingData(this);
  27662. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27663. _this._delayLoadingFunction(JSON.parse(data), _this);
  27664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27665. _this._delayInfo = [];
  27666. scene._removePendingData(_this);
  27667. var meshes = _this._meshes;
  27668. var numOfMeshes = meshes.length;
  27669. for (var index = 0; index < numOfMeshes; index++) {
  27670. _this._applyToMesh(meshes[index]);
  27671. }
  27672. if (onLoaded) {
  27673. onLoaded();
  27674. }
  27675. }, function () { }, scene.database);
  27676. };
  27677. /**
  27678. * Invert the geometry to move from a right handed system to a left handed one.
  27679. */
  27680. Geometry.prototype.toLeftHanded = function () {
  27681. // Flip faces
  27682. var tIndices = this.getIndices(false);
  27683. if (tIndices != null && tIndices.length > 0) {
  27684. for (var i = 0; i < tIndices.length; i += 3) {
  27685. var tTemp = tIndices[i + 0];
  27686. tIndices[i + 0] = tIndices[i + 2];
  27687. tIndices[i + 2] = tTemp;
  27688. }
  27689. this.setIndices(tIndices);
  27690. }
  27691. // Negate position.z
  27692. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27693. if (tPositions != null && tPositions.length > 0) {
  27694. for (var i = 0; i < tPositions.length; i += 3) {
  27695. tPositions[i + 2] = -tPositions[i + 2];
  27696. }
  27697. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27698. }
  27699. // Negate normal.z
  27700. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27701. if (tNormals != null && tNormals.length > 0) {
  27702. for (var i = 0; i < tNormals.length; i += 3) {
  27703. tNormals[i + 2] = -tNormals[i + 2];
  27704. }
  27705. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27706. }
  27707. };
  27708. // Cache
  27709. Geometry.prototype._resetPointsArrayCache = function () {
  27710. this._positions = null;
  27711. };
  27712. Geometry.prototype._generatePointsArray = function () {
  27713. if (this._positions)
  27714. return true;
  27715. this._positions = [];
  27716. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27717. if (!data) {
  27718. return false;
  27719. }
  27720. for (var index = 0; index < data.length; index += 3) {
  27721. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27722. }
  27723. return true;
  27724. };
  27725. Geometry.prototype.isDisposed = function () {
  27726. return this._isDisposed;
  27727. };
  27728. Geometry.prototype._disposeVertexArrayObjects = function () {
  27729. if (this._vertexArrayObjects) {
  27730. for (var kind in this._vertexArrayObjects) {
  27731. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27732. }
  27733. this._vertexArrayObjects = {};
  27734. }
  27735. };
  27736. Geometry.prototype.dispose = function () {
  27737. var meshes = this._meshes;
  27738. var numOfMeshes = meshes.length;
  27739. var index;
  27740. for (index = 0; index < numOfMeshes; index++) {
  27741. this.releaseForMesh(meshes[index]);
  27742. }
  27743. this._meshes = [];
  27744. this._disposeVertexArrayObjects();
  27745. for (var kind in this._vertexBuffers) {
  27746. this._vertexBuffers[kind].dispose();
  27747. }
  27748. this._vertexBuffers = {};
  27749. this._totalVertices = 0;
  27750. if (this._indexBuffer) {
  27751. this._engine._releaseBuffer(this._indexBuffer);
  27752. }
  27753. this._indexBuffer = null;
  27754. this._indices = [];
  27755. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27756. this.delayLoadingFile = null;
  27757. this._delayLoadingFunction = null;
  27758. this._delayInfo = [];
  27759. this._boundingInfo = null;
  27760. this._scene.removeGeometry(this);
  27761. this._isDisposed = true;
  27762. };
  27763. Geometry.prototype.copy = function (id) {
  27764. var vertexData = new BABYLON.VertexData();
  27765. vertexData.indices = [];
  27766. var indices = this.getIndices();
  27767. for (var index = 0; index < indices.length; index++) {
  27768. vertexData.indices.push(indices[index]);
  27769. }
  27770. var updatable = false;
  27771. var stopChecking = false;
  27772. var kind;
  27773. for (kind in this._vertexBuffers) {
  27774. // using slice() to make a copy of the array and not just reference it
  27775. var data = this.getVerticesData(kind);
  27776. if (data instanceof Float32Array) {
  27777. vertexData.set(new Float32Array(data), kind);
  27778. }
  27779. else {
  27780. vertexData.set(data.slice(0), kind);
  27781. }
  27782. if (!stopChecking) {
  27783. updatable = this.getVertexBuffer(kind).isUpdatable();
  27784. stopChecking = !updatable;
  27785. }
  27786. }
  27787. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27788. geometry.delayLoadState = this.delayLoadState;
  27789. geometry.delayLoadingFile = this.delayLoadingFile;
  27790. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27791. for (kind in this._delayInfo) {
  27792. geometry._delayInfo = geometry._delayInfo || [];
  27793. geometry._delayInfo.push(kind);
  27794. }
  27795. // Bounding info
  27796. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27797. return geometry;
  27798. };
  27799. Geometry.prototype.serialize = function () {
  27800. var serializationObject = {};
  27801. serializationObject.id = this.id;
  27802. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27803. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27804. }
  27805. return serializationObject;
  27806. };
  27807. Geometry.prototype.toNumberArray = function (origin) {
  27808. if (Array.isArray(origin)) {
  27809. return origin;
  27810. }
  27811. else {
  27812. return Array.prototype.slice.call(origin);
  27813. }
  27814. };
  27815. Geometry.prototype.serializeVerticeData = function () {
  27816. var serializationObject = this.serialize();
  27817. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27818. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27819. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27820. serializationObject.positions._updatable = true;
  27821. }
  27822. }
  27823. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27824. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27825. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27826. serializationObject.normals._updatable = true;
  27827. }
  27828. }
  27829. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27830. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27831. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27832. serializationObject.uvs._updatable = true;
  27833. }
  27834. }
  27835. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27836. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27837. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27838. serializationObject.uv2s._updatable = true;
  27839. }
  27840. }
  27841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27842. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27843. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27844. serializationObject.uv3s._updatable = true;
  27845. }
  27846. }
  27847. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27848. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27849. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27850. serializationObject.uv4s._updatable = true;
  27851. }
  27852. }
  27853. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27854. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27855. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27856. serializationObject.uv5s._updatable = true;
  27857. }
  27858. }
  27859. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27860. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27861. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27862. serializationObject.uv6s._updatable = true;
  27863. }
  27864. }
  27865. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27866. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27867. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27868. serializationObject.colors._updatable = true;
  27869. }
  27870. }
  27871. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27872. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27873. serializationObject.matricesIndices._isExpanded = true;
  27874. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27875. serializationObject.matricesIndices._updatable = true;
  27876. }
  27877. }
  27878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27879. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27880. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27881. serializationObject.matricesWeights._updatable = true;
  27882. }
  27883. }
  27884. serializationObject.indices = this.toNumberArray(this.getIndices());
  27885. return serializationObject;
  27886. };
  27887. // Statics
  27888. Geometry.ExtractFromMesh = function (mesh, id) {
  27889. var geometry = mesh._geometry;
  27890. if (!geometry) {
  27891. return null;
  27892. }
  27893. return geometry.copy(id);
  27894. };
  27895. /**
  27896. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27897. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27898. * Be aware Math.random() could cause collisions, but:
  27899. * "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"
  27900. */
  27901. Geometry.RandomId = function () {
  27902. return BABYLON.Tools.RandomId();
  27903. };
  27904. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27905. var scene = mesh.getScene();
  27906. // Geometry
  27907. var geometryId = parsedGeometry.geometryId;
  27908. if (geometryId) {
  27909. var geometry = scene.getGeometryByID(geometryId);
  27910. if (geometry) {
  27911. geometry.applyToMesh(mesh);
  27912. }
  27913. }
  27914. else if (parsedGeometry instanceof ArrayBuffer) {
  27915. var binaryInfo = mesh._binaryInfo;
  27916. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27917. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27918. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27919. }
  27920. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27921. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27922. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27923. }
  27924. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27925. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27926. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27927. }
  27928. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27929. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27930. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27931. }
  27932. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27933. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27934. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27935. }
  27936. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27937. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27938. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27939. }
  27940. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27941. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27942. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27943. }
  27944. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27945. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27946. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27947. }
  27948. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27949. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27950. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27951. }
  27952. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27953. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27954. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27955. }
  27956. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27957. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27958. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27959. }
  27960. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27961. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27962. mesh.setIndices(indicesData);
  27963. }
  27964. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27965. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27966. mesh.subMeshes = [];
  27967. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27968. var materialIndex = subMeshesData[(i * 5) + 0];
  27969. var verticesStart = subMeshesData[(i * 5) + 1];
  27970. var verticesCount = subMeshesData[(i * 5) + 2];
  27971. var indexStart = subMeshesData[(i * 5) + 3];
  27972. var indexCount = subMeshesData[(i * 5) + 4];
  27973. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27974. }
  27975. }
  27976. }
  27977. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27978. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27979. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27980. if (parsedGeometry.uvs) {
  27981. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27982. }
  27983. if (parsedGeometry.uvs2) {
  27984. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27985. }
  27986. if (parsedGeometry.uvs3) {
  27987. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27988. }
  27989. if (parsedGeometry.uvs4) {
  27990. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27991. }
  27992. if (parsedGeometry.uvs5) {
  27993. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27994. }
  27995. if (parsedGeometry.uvs6) {
  27996. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27997. }
  27998. if (parsedGeometry.colors) {
  27999. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  28000. }
  28001. if (parsedGeometry.matricesIndices) {
  28002. if (!parsedGeometry.matricesIndices._isExpanded) {
  28003. var floatIndices = [];
  28004. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  28005. var matricesIndex = parsedGeometry.matricesIndices[i];
  28006. floatIndices.push(matricesIndex & 0x000000FF);
  28007. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28008. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28009. floatIndices.push(matricesIndex >> 24);
  28010. }
  28011. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  28012. }
  28013. else {
  28014. delete parsedGeometry.matricesIndices._isExpanded;
  28015. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  28016. }
  28017. }
  28018. if (parsedGeometry.matricesIndicesExtra) {
  28019. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  28020. var floatIndices = [];
  28021. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  28022. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  28023. floatIndices.push(matricesIndex & 0x000000FF);
  28024. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  28025. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  28026. floatIndices.push(matricesIndex >> 24);
  28027. }
  28028. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  28029. }
  28030. else {
  28031. delete parsedGeometry.matricesIndices._isExpanded;
  28032. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  28033. }
  28034. }
  28035. if (parsedGeometry.matricesWeights) {
  28036. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  28037. }
  28038. if (parsedGeometry.matricesWeightsExtra) {
  28039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  28040. }
  28041. mesh.setIndices(parsedGeometry.indices);
  28042. }
  28043. // SubMeshes
  28044. if (parsedGeometry.subMeshes) {
  28045. mesh.subMeshes = [];
  28046. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  28047. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  28048. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  28049. }
  28050. }
  28051. // Flat shading
  28052. if (mesh._shouldGenerateFlatShading) {
  28053. mesh.convertToFlatShadedMesh();
  28054. delete mesh._shouldGenerateFlatShading;
  28055. }
  28056. // Update
  28057. mesh.computeWorldMatrix(true);
  28058. // Octree
  28059. if (scene['_selectionOctree']) {
  28060. scene['_selectionOctree'].addMesh(mesh);
  28061. }
  28062. };
  28063. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  28064. if (scene.getGeometryByID(parsedVertexData.id)) {
  28065. return null; // null since geometry could be something else than a box...
  28066. }
  28067. var geometry = new Geometry(parsedVertexData.id, scene);
  28068. if (BABYLON.Tags) {
  28069. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  28070. }
  28071. if (parsedVertexData.delayLoadingFile) {
  28072. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28073. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  28074. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  28075. geometry._delayInfo = [];
  28076. if (parsedVertexData.hasUVs) {
  28077. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28078. }
  28079. if (parsedVertexData.hasUVs2) {
  28080. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28081. }
  28082. if (parsedVertexData.hasUVs3) {
  28083. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28084. }
  28085. if (parsedVertexData.hasUVs4) {
  28086. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28087. }
  28088. if (parsedVertexData.hasUVs5) {
  28089. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28090. }
  28091. if (parsedVertexData.hasUVs6) {
  28092. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28093. }
  28094. if (parsedVertexData.hasColors) {
  28095. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28096. }
  28097. if (parsedVertexData.hasMatricesIndices) {
  28098. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28099. }
  28100. if (parsedVertexData.hasMatricesWeights) {
  28101. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28102. }
  28103. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  28104. }
  28105. else {
  28106. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  28107. }
  28108. scene.pushGeometry(geometry, true);
  28109. return geometry;
  28110. };
  28111. return Geometry;
  28112. }());
  28113. BABYLON.Geometry = Geometry;
  28114. /////// Primitives //////////////////////////////////////////////
  28115. (function (Geometry) {
  28116. var Primitives;
  28117. (function (Primitives) {
  28118. /// Abstract class
  28119. var _Primitive = (function (_super) {
  28120. __extends(_Primitive, _super);
  28121. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  28122. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  28123. _this._canBeRegenerated = _canBeRegenerated;
  28124. _this._beingRegenerated = true;
  28125. _this.regenerate();
  28126. _this._beingRegenerated = false;
  28127. return _this;
  28128. }
  28129. _Primitive.prototype.canBeRegenerated = function () {
  28130. return this._canBeRegenerated;
  28131. };
  28132. _Primitive.prototype.regenerate = function () {
  28133. if (!this._canBeRegenerated) {
  28134. return;
  28135. }
  28136. this._beingRegenerated = true;
  28137. this.setAllVerticesData(this._regenerateVertexData(), false);
  28138. this._beingRegenerated = false;
  28139. };
  28140. _Primitive.prototype.asNewGeometry = function (id) {
  28141. return _super.prototype.copy.call(this, id);
  28142. };
  28143. // overrides
  28144. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28145. if (!this._beingRegenerated) {
  28146. return;
  28147. }
  28148. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28149. };
  28150. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28151. if (!this._beingRegenerated) {
  28152. return;
  28153. }
  28154. _super.prototype.setVerticesData.call(this, kind, data, false);
  28155. };
  28156. // to override
  28157. // protected
  28158. _Primitive.prototype._regenerateVertexData = function () {
  28159. throw new Error("Abstract method");
  28160. };
  28161. _Primitive.prototype.copy = function (id) {
  28162. throw new Error("Must be overriden in sub-classes.");
  28163. };
  28164. _Primitive.prototype.serialize = function () {
  28165. var serializationObject = _super.prototype.serialize.call(this);
  28166. serializationObject.canBeRegenerated = this.canBeRegenerated();
  28167. return serializationObject;
  28168. };
  28169. return _Primitive;
  28170. }(Geometry));
  28171. Primitives._Primitive = _Primitive;
  28172. var Ribbon = (function (_super) {
  28173. __extends(Ribbon, _super);
  28174. // Members
  28175. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28176. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28177. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28178. _this.pathArray = pathArray;
  28179. _this.closeArray = closeArray;
  28180. _this.closePath = closePath;
  28181. _this.offset = offset;
  28182. _this.side = side;
  28183. return _this;
  28184. }
  28185. Ribbon.prototype._regenerateVertexData = function () {
  28186. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  28187. };
  28188. Ribbon.prototype.copy = function (id) {
  28189. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28190. };
  28191. return Ribbon;
  28192. }(_Primitive));
  28193. Primitives.Ribbon = Ribbon;
  28194. var Box = (function (_super) {
  28195. __extends(Box, _super);
  28196. // Members
  28197. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28198. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28199. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28200. _this.size = size;
  28201. _this.side = side;
  28202. return _this;
  28203. }
  28204. Box.prototype._regenerateVertexData = function () {
  28205. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28206. };
  28207. Box.prototype.copy = function (id) {
  28208. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28209. };
  28210. Box.prototype.serialize = function () {
  28211. var serializationObject = _super.prototype.serialize.call(this);
  28212. serializationObject.size = this.size;
  28213. return serializationObject;
  28214. };
  28215. Box.Parse = function (parsedBox, scene) {
  28216. if (scene.getGeometryByID(parsedBox.id)) {
  28217. return null; // null since geometry could be something else than a box...
  28218. }
  28219. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28220. if (BABYLON.Tags) {
  28221. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28222. }
  28223. scene.pushGeometry(box, true);
  28224. return box;
  28225. };
  28226. return Box;
  28227. }(_Primitive));
  28228. Primitives.Box = Box;
  28229. var Sphere = (function (_super) {
  28230. __extends(Sphere, _super);
  28231. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28232. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28233. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28234. _this.segments = segments;
  28235. _this.diameter = diameter;
  28236. _this.side = side;
  28237. return _this;
  28238. }
  28239. Sphere.prototype._regenerateVertexData = function () {
  28240. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28241. };
  28242. Sphere.prototype.copy = function (id) {
  28243. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28244. };
  28245. Sphere.prototype.serialize = function () {
  28246. var serializationObject = _super.prototype.serialize.call(this);
  28247. serializationObject.segments = this.segments;
  28248. serializationObject.diameter = this.diameter;
  28249. return serializationObject;
  28250. };
  28251. Sphere.Parse = function (parsedSphere, scene) {
  28252. if (scene.getGeometryByID(parsedSphere.id)) {
  28253. return null; // null since geometry could be something else than a sphere...
  28254. }
  28255. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28256. if (BABYLON.Tags) {
  28257. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28258. }
  28259. scene.pushGeometry(sphere, true);
  28260. return sphere;
  28261. };
  28262. return Sphere;
  28263. }(_Primitive));
  28264. Primitives.Sphere = Sphere;
  28265. var Disc = (function (_super) {
  28266. __extends(Disc, _super);
  28267. // Members
  28268. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28269. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28270. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28271. _this.radius = radius;
  28272. _this.tessellation = tessellation;
  28273. _this.side = side;
  28274. return _this;
  28275. }
  28276. Disc.prototype._regenerateVertexData = function () {
  28277. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28278. };
  28279. Disc.prototype.copy = function (id) {
  28280. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28281. };
  28282. return Disc;
  28283. }(_Primitive));
  28284. Primitives.Disc = Disc;
  28285. var Cylinder = (function (_super) {
  28286. __extends(Cylinder, _super);
  28287. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28288. if (subdivisions === void 0) { subdivisions = 1; }
  28289. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28290. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28291. _this.height = height;
  28292. _this.diameterTop = diameterTop;
  28293. _this.diameterBottom = diameterBottom;
  28294. _this.tessellation = tessellation;
  28295. _this.subdivisions = subdivisions;
  28296. _this.side = side;
  28297. return _this;
  28298. }
  28299. Cylinder.prototype._regenerateVertexData = function () {
  28300. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28301. };
  28302. Cylinder.prototype.copy = function (id) {
  28303. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28304. };
  28305. Cylinder.prototype.serialize = function () {
  28306. var serializationObject = _super.prototype.serialize.call(this);
  28307. serializationObject.height = this.height;
  28308. serializationObject.diameterTop = this.diameterTop;
  28309. serializationObject.diameterBottom = this.diameterBottom;
  28310. serializationObject.tessellation = this.tessellation;
  28311. return serializationObject;
  28312. };
  28313. Cylinder.Parse = function (parsedCylinder, scene) {
  28314. if (scene.getGeometryByID(parsedCylinder.id)) {
  28315. return null; // null since geometry could be something else than a cylinder...
  28316. }
  28317. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28318. if (BABYLON.Tags) {
  28319. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28320. }
  28321. scene.pushGeometry(cylinder, true);
  28322. return cylinder;
  28323. };
  28324. return Cylinder;
  28325. }(_Primitive));
  28326. Primitives.Cylinder = Cylinder;
  28327. var Torus = (function (_super) {
  28328. __extends(Torus, _super);
  28329. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28332. _this.diameter = diameter;
  28333. _this.thickness = thickness;
  28334. _this.tessellation = tessellation;
  28335. _this.side = side;
  28336. return _this;
  28337. }
  28338. Torus.prototype._regenerateVertexData = function () {
  28339. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28340. };
  28341. Torus.prototype.copy = function (id) {
  28342. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28343. };
  28344. Torus.prototype.serialize = function () {
  28345. var serializationObject = _super.prototype.serialize.call(this);
  28346. serializationObject.diameter = this.diameter;
  28347. serializationObject.thickness = this.thickness;
  28348. serializationObject.tessellation = this.tessellation;
  28349. return serializationObject;
  28350. };
  28351. Torus.Parse = function (parsedTorus, scene) {
  28352. if (scene.getGeometryByID(parsedTorus.id)) {
  28353. return null; // null since geometry could be something else than a torus...
  28354. }
  28355. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28356. if (BABYLON.Tags) {
  28357. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28358. }
  28359. scene.pushGeometry(torus, true);
  28360. return torus;
  28361. };
  28362. return Torus;
  28363. }(_Primitive));
  28364. Primitives.Torus = Torus;
  28365. var Ground = (function (_super) {
  28366. __extends(Ground, _super);
  28367. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28368. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28369. _this.width = width;
  28370. _this.height = height;
  28371. _this.subdivisions = subdivisions;
  28372. return _this;
  28373. }
  28374. Ground.prototype._regenerateVertexData = function () {
  28375. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28376. };
  28377. Ground.prototype.copy = function (id) {
  28378. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28379. };
  28380. Ground.prototype.serialize = function () {
  28381. var serializationObject = _super.prototype.serialize.call(this);
  28382. serializationObject.width = this.width;
  28383. serializationObject.height = this.height;
  28384. serializationObject.subdivisions = this.subdivisions;
  28385. return serializationObject;
  28386. };
  28387. Ground.Parse = function (parsedGround, scene) {
  28388. if (scene.getGeometryByID(parsedGround.id)) {
  28389. return null; // null since geometry could be something else than a ground...
  28390. }
  28391. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28392. if (BABYLON.Tags) {
  28393. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28394. }
  28395. scene.pushGeometry(ground, true);
  28396. return ground;
  28397. };
  28398. return Ground;
  28399. }(_Primitive));
  28400. Primitives.Ground = Ground;
  28401. var TiledGround = (function (_super) {
  28402. __extends(TiledGround, _super);
  28403. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28404. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28405. _this.xmin = xmin;
  28406. _this.zmin = zmin;
  28407. _this.xmax = xmax;
  28408. _this.zmax = zmax;
  28409. _this.subdivisions = subdivisions;
  28410. _this.precision = precision;
  28411. return _this;
  28412. }
  28413. TiledGround.prototype._regenerateVertexData = function () {
  28414. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28415. };
  28416. TiledGround.prototype.copy = function (id) {
  28417. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28418. };
  28419. return TiledGround;
  28420. }(_Primitive));
  28421. Primitives.TiledGround = TiledGround;
  28422. var Plane = (function (_super) {
  28423. __extends(Plane, _super);
  28424. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28425. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28426. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28427. _this.size = size;
  28428. _this.side = side;
  28429. return _this;
  28430. }
  28431. Plane.prototype._regenerateVertexData = function () {
  28432. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28433. };
  28434. Plane.prototype.copy = function (id) {
  28435. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28436. };
  28437. Plane.prototype.serialize = function () {
  28438. var serializationObject = _super.prototype.serialize.call(this);
  28439. serializationObject.size = this.size;
  28440. return serializationObject;
  28441. };
  28442. Plane.Parse = function (parsedPlane, scene) {
  28443. if (scene.getGeometryByID(parsedPlane.id)) {
  28444. return null; // null since geometry could be something else than a ground...
  28445. }
  28446. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28447. if (BABYLON.Tags) {
  28448. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28449. }
  28450. scene.pushGeometry(plane, true);
  28451. return plane;
  28452. };
  28453. return Plane;
  28454. }(_Primitive));
  28455. Primitives.Plane = Plane;
  28456. var TorusKnot = (function (_super) {
  28457. __extends(TorusKnot, _super);
  28458. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28459. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28460. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28461. _this.radius = radius;
  28462. _this.tube = tube;
  28463. _this.radialSegments = radialSegments;
  28464. _this.tubularSegments = tubularSegments;
  28465. _this.p = p;
  28466. _this.q = q;
  28467. _this.side = side;
  28468. return _this;
  28469. }
  28470. TorusKnot.prototype._regenerateVertexData = function () {
  28471. 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 });
  28472. };
  28473. TorusKnot.prototype.copy = function (id) {
  28474. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28475. };
  28476. TorusKnot.prototype.serialize = function () {
  28477. var serializationObject = _super.prototype.serialize.call(this);
  28478. serializationObject.radius = this.radius;
  28479. serializationObject.tube = this.tube;
  28480. serializationObject.radialSegments = this.radialSegments;
  28481. serializationObject.tubularSegments = this.tubularSegments;
  28482. serializationObject.p = this.p;
  28483. serializationObject.q = this.q;
  28484. return serializationObject;
  28485. };
  28486. ;
  28487. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28488. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28489. return null; // null since geometry could be something else than a ground...
  28490. }
  28491. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28492. if (BABYLON.Tags) {
  28493. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28494. }
  28495. scene.pushGeometry(torusKnot, true);
  28496. return torusKnot;
  28497. };
  28498. return TorusKnot;
  28499. }(_Primitive));
  28500. Primitives.TorusKnot = TorusKnot;
  28501. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28502. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28503. })(BABYLON || (BABYLON = {}));
  28504. //# sourceMappingURL=babylon.geometry.js.map
  28505. var BABYLON;
  28506. (function (BABYLON) {
  28507. var PostProcessManager = (function () {
  28508. function PostProcessManager(scene) {
  28509. this._vertexBuffers = {};
  28510. this._scene = scene;
  28511. }
  28512. PostProcessManager.prototype._prepareBuffers = function () {
  28513. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28514. return;
  28515. }
  28516. // VBO
  28517. var vertices = [];
  28518. vertices.push(1, 1);
  28519. vertices.push(-1, 1);
  28520. vertices.push(-1, -1);
  28521. vertices.push(1, -1);
  28522. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28523. // Indices
  28524. var indices = [];
  28525. indices.push(0);
  28526. indices.push(1);
  28527. indices.push(2);
  28528. indices.push(0);
  28529. indices.push(2);
  28530. indices.push(3);
  28531. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28532. };
  28533. // Methods
  28534. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28535. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28536. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28537. return false;
  28538. }
  28539. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28540. return true;
  28541. };
  28542. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28543. var engine = this._scene.getEngine();
  28544. for (var index = 0; index < postProcesses.length; index++) {
  28545. if (index < postProcesses.length - 1) {
  28546. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28547. }
  28548. else {
  28549. if (targetTexture) {
  28550. engine.bindFramebuffer(targetTexture);
  28551. }
  28552. else {
  28553. engine.restoreDefaultFramebuffer();
  28554. }
  28555. }
  28556. var pp = postProcesses[index];
  28557. var effect = pp.apply();
  28558. if (effect) {
  28559. pp.onBeforeRenderObservable.notifyObservers(effect);
  28560. // VBOs
  28561. this._prepareBuffers();
  28562. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28563. // Draw order
  28564. engine.draw(true, 0, 6);
  28565. pp.onAfterRenderObservable.notifyObservers(effect);
  28566. }
  28567. }
  28568. // Restore depth buffer
  28569. engine.setDepthBuffer(true);
  28570. engine.setDepthWrite(true);
  28571. };
  28572. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28573. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28574. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28575. return;
  28576. }
  28577. var engine = this._scene.getEngine();
  28578. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28579. if (index < len - 1) {
  28580. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28581. }
  28582. else {
  28583. if (targetTexture) {
  28584. engine.bindFramebuffer(targetTexture, faceIndex);
  28585. }
  28586. else {
  28587. engine.restoreDefaultFramebuffer();
  28588. }
  28589. }
  28590. if (doNotPresent) {
  28591. break;
  28592. }
  28593. var pp = postProcesses[index];
  28594. var effect = pp.apply();
  28595. if (effect) {
  28596. pp.onBeforeRenderObservable.notifyObservers(effect);
  28597. // VBOs
  28598. this._prepareBuffers();
  28599. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28600. // Draw order
  28601. engine.draw(true, 0, 6);
  28602. pp.onAfterRenderObservable.notifyObservers(effect);
  28603. }
  28604. }
  28605. // Restore states
  28606. engine.setDepthBuffer(true);
  28607. engine.setDepthWrite(true);
  28608. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28609. };
  28610. PostProcessManager.prototype.dispose = function () {
  28611. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28612. if (buffer) {
  28613. buffer.dispose();
  28614. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28615. }
  28616. if (this._indexBuffer) {
  28617. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28618. this._indexBuffer = null;
  28619. }
  28620. };
  28621. return PostProcessManager;
  28622. }());
  28623. BABYLON.PostProcessManager = PostProcessManager;
  28624. })(BABYLON || (BABYLON = {}));
  28625. //# sourceMappingURL=babylon.postProcessManager.js.map
  28626. var BABYLON;
  28627. (function (BABYLON) {
  28628. var AnimationRange = (function () {
  28629. function AnimationRange(name, from, to) {
  28630. this.name = name;
  28631. this.from = from;
  28632. this.to = to;
  28633. }
  28634. AnimationRange.prototype.clone = function () {
  28635. return new AnimationRange(this.name, this.from, this.to);
  28636. };
  28637. return AnimationRange;
  28638. }());
  28639. BABYLON.AnimationRange = AnimationRange;
  28640. /**
  28641. * Composed of a frame, and an action function
  28642. */
  28643. var AnimationEvent = (function () {
  28644. function AnimationEvent(frame, action, onlyOnce) {
  28645. this.frame = frame;
  28646. this.action = action;
  28647. this.onlyOnce = onlyOnce;
  28648. this.isDone = false;
  28649. }
  28650. return AnimationEvent;
  28651. }());
  28652. BABYLON.AnimationEvent = AnimationEvent;
  28653. var PathCursor = (function () {
  28654. function PathCursor(path) {
  28655. this.path = path;
  28656. this._onchange = new Array();
  28657. this.value = 0;
  28658. this.animations = new Array();
  28659. }
  28660. PathCursor.prototype.getPoint = function () {
  28661. var point = this.path.getPointAtLengthPosition(this.value);
  28662. return new BABYLON.Vector3(point.x, 0, point.y);
  28663. };
  28664. PathCursor.prototype.moveAhead = function (step) {
  28665. if (step === void 0) { step = 0.002; }
  28666. this.move(step);
  28667. return this;
  28668. };
  28669. PathCursor.prototype.moveBack = function (step) {
  28670. if (step === void 0) { step = 0.002; }
  28671. this.move(-step);
  28672. return this;
  28673. };
  28674. PathCursor.prototype.move = function (step) {
  28675. if (Math.abs(step) > 1) {
  28676. throw "step size should be less than 1.";
  28677. }
  28678. this.value += step;
  28679. this.ensureLimits();
  28680. this.raiseOnChange();
  28681. return this;
  28682. };
  28683. PathCursor.prototype.ensureLimits = function () {
  28684. while (this.value > 1) {
  28685. this.value -= 1;
  28686. }
  28687. while (this.value < 0) {
  28688. this.value += 1;
  28689. }
  28690. return this;
  28691. };
  28692. // used by animation engine
  28693. PathCursor.prototype.markAsDirty = function (propertyName) {
  28694. this.ensureLimits();
  28695. this.raiseOnChange();
  28696. return this;
  28697. };
  28698. PathCursor.prototype.raiseOnChange = function () {
  28699. var _this = this;
  28700. this._onchange.forEach(function (f) { return f(_this); });
  28701. return this;
  28702. };
  28703. PathCursor.prototype.onchange = function (f) {
  28704. this._onchange.push(f);
  28705. return this;
  28706. };
  28707. return PathCursor;
  28708. }());
  28709. BABYLON.PathCursor = PathCursor;
  28710. var Animation = (function () {
  28711. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28712. this.name = name;
  28713. this.targetProperty = targetProperty;
  28714. this.framePerSecond = framePerSecond;
  28715. this.dataType = dataType;
  28716. this.loopMode = loopMode;
  28717. this.enableBlending = enableBlending;
  28718. this._offsetsCache = {};
  28719. this._highLimitsCache = {};
  28720. this._stopped = false;
  28721. this._blendingFactor = 0;
  28722. // The set of event that will be linked to this animation
  28723. this._events = new Array();
  28724. this.allowMatricesInterpolation = false;
  28725. this.blendingSpeed = 0.01;
  28726. this._ranges = {};
  28727. this.targetPropertyPath = targetProperty.split(".");
  28728. this.dataType = dataType;
  28729. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28730. }
  28731. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28732. var dataType = undefined;
  28733. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28734. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28735. }
  28736. else if (from instanceof BABYLON.Quaternion) {
  28737. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28738. }
  28739. else if (from instanceof BABYLON.Vector3) {
  28740. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28741. }
  28742. else if (from instanceof BABYLON.Vector2) {
  28743. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28744. }
  28745. else if (from instanceof BABYLON.Color3) {
  28746. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28747. }
  28748. else if (from instanceof BABYLON.Size) {
  28749. dataType = Animation.ANIMATIONTYPE_SIZE;
  28750. }
  28751. if (dataType == undefined) {
  28752. return null;
  28753. }
  28754. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28755. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28756. animation.setKeys(keys);
  28757. if (easingFunction !== undefined) {
  28758. animation.setEasingFunction(easingFunction);
  28759. }
  28760. return animation;
  28761. };
  28762. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28763. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28764. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28765. };
  28766. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28767. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28768. node.animations.push(animation);
  28769. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28770. };
  28771. // Methods
  28772. /**
  28773. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28774. */
  28775. Animation.prototype.toString = function (fullDetails) {
  28776. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28777. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28778. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28779. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28780. if (fullDetails) {
  28781. ret += ", Ranges: {";
  28782. var first = true;
  28783. for (var name in this._ranges) {
  28784. if (first) {
  28785. ret += ", ";
  28786. first = false;
  28787. }
  28788. ret += name;
  28789. }
  28790. ret += "}";
  28791. }
  28792. return ret;
  28793. };
  28794. /**
  28795. * Add an event to this animation.
  28796. */
  28797. Animation.prototype.addEvent = function (event) {
  28798. this._events.push(event);
  28799. };
  28800. /**
  28801. * Remove all events found at the given frame
  28802. * @param frame
  28803. */
  28804. Animation.prototype.removeEvents = function (frame) {
  28805. for (var index = 0; index < this._events.length; index++) {
  28806. if (this._events[index].frame === frame) {
  28807. this._events.splice(index, 1);
  28808. index--;
  28809. }
  28810. }
  28811. };
  28812. Animation.prototype.createRange = function (name, from, to) {
  28813. // check name not already in use; could happen for bones after serialized
  28814. if (!this._ranges[name]) {
  28815. this._ranges[name] = new AnimationRange(name, from, to);
  28816. }
  28817. };
  28818. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28819. if (deleteFrames === void 0) { deleteFrames = true; }
  28820. if (this._ranges[name]) {
  28821. if (deleteFrames) {
  28822. var from = this._ranges[name].from;
  28823. var to = this._ranges[name].to;
  28824. // this loop MUST go high to low for multiple splices to work
  28825. for (var key = this._keys.length - 1; key >= 0; key--) {
  28826. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28827. this._keys.splice(key, 1);
  28828. }
  28829. }
  28830. }
  28831. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28832. }
  28833. };
  28834. Animation.prototype.getRange = function (name) {
  28835. return this._ranges[name];
  28836. };
  28837. Animation.prototype.reset = function () {
  28838. this._offsetsCache = {};
  28839. this._highLimitsCache = {};
  28840. this.currentFrame = 0;
  28841. this._blendingFactor = 0;
  28842. this._originalBlendValue = null;
  28843. };
  28844. Animation.prototype.isStopped = function () {
  28845. return this._stopped;
  28846. };
  28847. Animation.prototype.getKeys = function () {
  28848. return this._keys;
  28849. };
  28850. Animation.prototype.getHighestFrame = function () {
  28851. var ret = 0;
  28852. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28853. if (ret < this._keys[key].frame) {
  28854. ret = this._keys[key].frame;
  28855. }
  28856. }
  28857. return ret;
  28858. };
  28859. Animation.prototype.getEasingFunction = function () {
  28860. return this._easingFunction;
  28861. };
  28862. Animation.prototype.setEasingFunction = function (easingFunction) {
  28863. this._easingFunction = easingFunction;
  28864. };
  28865. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28866. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28867. };
  28868. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28869. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28870. };
  28871. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28872. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28873. };
  28874. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28875. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28876. };
  28877. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28878. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28879. };
  28880. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28881. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28882. };
  28883. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28884. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28885. };
  28886. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28887. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28888. };
  28889. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28890. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28891. };
  28892. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28893. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28894. };
  28895. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28896. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28897. };
  28898. Animation.prototype.clone = function () {
  28899. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28900. clone.enableBlending = this.enableBlending;
  28901. clone.blendingSpeed = this.blendingSpeed;
  28902. if (this._keys) {
  28903. clone.setKeys(this._keys);
  28904. }
  28905. if (this._ranges) {
  28906. clone._ranges = {};
  28907. for (var name in this._ranges) {
  28908. clone._ranges[name] = this._ranges[name].clone();
  28909. }
  28910. }
  28911. return clone;
  28912. };
  28913. Animation.prototype.setKeys = function (values) {
  28914. this._keys = values.slice(0);
  28915. this._offsetsCache = {};
  28916. this._highLimitsCache = {};
  28917. };
  28918. Animation.prototype._getKeyValue = function (value) {
  28919. if (typeof value === "function") {
  28920. return value();
  28921. }
  28922. return value;
  28923. };
  28924. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28925. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28926. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28927. }
  28928. this.currentFrame = currentFrame;
  28929. // Try to get a hash to find the right key
  28930. var startKeyIndex = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  28931. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28932. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28933. startKeyIndex--;
  28934. }
  28935. }
  28936. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28937. var endKey = this._keys[key + 1];
  28938. if (endKey.frame >= currentFrame) {
  28939. var startKey = this._keys[key];
  28940. var startValue = this._getKeyValue(startKey.value);
  28941. var endValue = this._getKeyValue(endKey.value);
  28942. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28943. var frameDelta = endKey.frame - startKey.frame;
  28944. // gradient : percent of currentFrame between the frame inf and the frame sup
  28945. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28946. // check for easingFunction and correction of gradient
  28947. if (this._easingFunction != null) {
  28948. gradient = this._easingFunction.ease(gradient);
  28949. }
  28950. switch (this.dataType) {
  28951. // Float
  28952. case Animation.ANIMATIONTYPE_FLOAT:
  28953. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28954. switch (loopMode) {
  28955. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28956. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28957. return floatValue;
  28958. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28959. return offsetValue * repeatCount + floatValue;
  28960. }
  28961. break;
  28962. // Quaternion
  28963. case Animation.ANIMATIONTYPE_QUATERNION:
  28964. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28965. switch (loopMode) {
  28966. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28967. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28968. return quatValue;
  28969. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28970. return quatValue.add(offsetValue.scale(repeatCount));
  28971. }
  28972. return quatValue;
  28973. // Vector3
  28974. case Animation.ANIMATIONTYPE_VECTOR3:
  28975. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28976. switch (loopMode) {
  28977. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28978. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28979. return vec3Value;
  28980. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28981. return vec3Value.add(offsetValue.scale(repeatCount));
  28982. }
  28983. // Vector2
  28984. case Animation.ANIMATIONTYPE_VECTOR2:
  28985. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28986. switch (loopMode) {
  28987. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28988. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28989. return vec2Value;
  28990. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28991. return vec2Value.add(offsetValue.scale(repeatCount));
  28992. }
  28993. // Size
  28994. case Animation.ANIMATIONTYPE_SIZE:
  28995. switch (loopMode) {
  28996. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28997. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28998. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28999. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29000. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29001. }
  29002. // Color3
  29003. case Animation.ANIMATIONTYPE_COLOR3:
  29004. switch (loopMode) {
  29005. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29006. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29007. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29008. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29009. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29010. }
  29011. // Matrix
  29012. case Animation.ANIMATIONTYPE_MATRIX:
  29013. switch (loopMode) {
  29014. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29015. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29016. if (this.allowMatricesInterpolation) {
  29017. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29018. }
  29019. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29020. return startValue;
  29021. }
  29022. default:
  29023. break;
  29024. }
  29025. break;
  29026. }
  29027. }
  29028. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29029. };
  29030. Animation.prototype.setValue = function (currentValue, blend) {
  29031. if (blend === void 0) { blend = false; }
  29032. // Set value
  29033. var path;
  29034. var destination;
  29035. if (this.targetPropertyPath.length > 1) {
  29036. var property = this._target[this.targetPropertyPath[0]];
  29037. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29038. property = property[this.targetPropertyPath[index]];
  29039. }
  29040. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29041. destination = property;
  29042. }
  29043. else {
  29044. path = this.targetPropertyPath[0];
  29045. destination = this._target;
  29046. }
  29047. // Blending
  29048. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29049. if (!this._originalBlendValue) {
  29050. if (destination[path].clone) {
  29051. this._originalBlendValue = destination[path].clone();
  29052. }
  29053. else {
  29054. this._originalBlendValue = destination[path];
  29055. }
  29056. }
  29057. if (this._originalBlendValue.prototype) {
  29058. if (this._originalBlendValue.prototype.Lerp) {
  29059. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29060. }
  29061. else {
  29062. destination[path] = currentValue;
  29063. }
  29064. }
  29065. else if (this._originalBlendValue.m) {
  29066. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29067. }
  29068. else {
  29069. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29070. }
  29071. this._blendingFactor += this.blendingSpeed;
  29072. }
  29073. else {
  29074. destination[path] = currentValue;
  29075. }
  29076. if (this._target.markAsDirty) {
  29077. this._target.markAsDirty(this.targetProperty);
  29078. }
  29079. };
  29080. Animation.prototype.goToFrame = function (frame) {
  29081. if (frame < this._keys[0].frame) {
  29082. frame = this._keys[0].frame;
  29083. }
  29084. else if (frame > this._keys[this._keys.length - 1].frame) {
  29085. frame = this._keys[this._keys.length - 1].frame;
  29086. }
  29087. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29088. this.setValue(currentValue);
  29089. };
  29090. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29091. if (blend === void 0) { blend = false; }
  29092. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29093. this._stopped = true;
  29094. return false;
  29095. }
  29096. var returnValue = true;
  29097. // Adding a start key at frame 0 if missing
  29098. if (this._keys[0].frame !== 0) {
  29099. var newKey = { frame: 0, value: this._keys[0].value };
  29100. this._keys.splice(0, 0, newKey);
  29101. }
  29102. // Check limits
  29103. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29104. from = this._keys[0].frame;
  29105. }
  29106. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29107. to = this._keys[this._keys.length - 1].frame;
  29108. }
  29109. //to and from cannot be the same key
  29110. if (from === to) {
  29111. from++;
  29112. }
  29113. // Compute ratio
  29114. var range = to - from;
  29115. var offsetValue;
  29116. // ratio represents the frame delta between from and to
  29117. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29118. var highLimitValue = 0;
  29119. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  29120. returnValue = false;
  29121. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29122. }
  29123. else {
  29124. // Get max value if required
  29125. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29126. var keyOffset = to.toString() + from.toString();
  29127. if (!this._offsetsCache[keyOffset]) {
  29128. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29129. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29130. switch (this.dataType) {
  29131. // Float
  29132. case Animation.ANIMATIONTYPE_FLOAT:
  29133. this._offsetsCache[keyOffset] = toValue - fromValue;
  29134. break;
  29135. // Quaternion
  29136. case Animation.ANIMATIONTYPE_QUATERNION:
  29137. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29138. break;
  29139. // Vector3
  29140. case Animation.ANIMATIONTYPE_VECTOR3:
  29141. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29142. // Vector2
  29143. case Animation.ANIMATIONTYPE_VECTOR2:
  29144. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29145. // Size
  29146. case Animation.ANIMATIONTYPE_SIZE:
  29147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29148. // Color3
  29149. case Animation.ANIMATIONTYPE_COLOR3:
  29150. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29151. default:
  29152. break;
  29153. }
  29154. this._highLimitsCache[keyOffset] = toValue;
  29155. }
  29156. highLimitValue = this._highLimitsCache[keyOffset];
  29157. offsetValue = this._offsetsCache[keyOffset];
  29158. }
  29159. }
  29160. if (offsetValue === undefined) {
  29161. switch (this.dataType) {
  29162. // Float
  29163. case Animation.ANIMATIONTYPE_FLOAT:
  29164. offsetValue = 0;
  29165. break;
  29166. // Quaternion
  29167. case Animation.ANIMATIONTYPE_QUATERNION:
  29168. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29169. break;
  29170. // Vector3
  29171. case Animation.ANIMATIONTYPE_VECTOR3:
  29172. offsetValue = BABYLON.Vector3.Zero();
  29173. break;
  29174. // Vector2
  29175. case Animation.ANIMATIONTYPE_VECTOR2:
  29176. offsetValue = BABYLON.Vector2.Zero();
  29177. break;
  29178. // Size
  29179. case Animation.ANIMATIONTYPE_SIZE:
  29180. offsetValue = BABYLON.Size.Zero();
  29181. break;
  29182. // Color3
  29183. case Animation.ANIMATIONTYPE_COLOR3:
  29184. offsetValue = BABYLON.Color3.Black();
  29185. }
  29186. }
  29187. // Compute value
  29188. var repeatCount = (ratio / range) >> 0;
  29189. var currentFrame = returnValue ? from + ratio % range : to;
  29190. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29191. // Set value
  29192. this.setValue(currentValue);
  29193. // Check events
  29194. for (var index = 0; index < this._events.length; index++) {
  29195. // Make sure current frame has passed event frame and that event frame is within the current range
  29196. // Also, handle both forward and reverse animations
  29197. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  29198. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  29199. var event = this._events[index];
  29200. if (!event.isDone) {
  29201. // If event should be done only once, remove it.
  29202. if (event.onlyOnce) {
  29203. this._events.splice(index, 1);
  29204. index--;
  29205. }
  29206. event.isDone = true;
  29207. event.action();
  29208. } // Don't do anything if the event has already be done.
  29209. }
  29210. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29211. // reset event, the animation is looping
  29212. this._events[index].isDone = false;
  29213. }
  29214. }
  29215. if (!returnValue) {
  29216. this._stopped = true;
  29217. }
  29218. return returnValue;
  29219. };
  29220. Animation.prototype.serialize = function () {
  29221. var serializationObject = {};
  29222. serializationObject.name = this.name;
  29223. serializationObject.property = this.targetProperty;
  29224. serializationObject.framePerSecond = this.framePerSecond;
  29225. serializationObject.dataType = this.dataType;
  29226. serializationObject.loopBehavior = this.loopMode;
  29227. serializationObject.enableBlending = this.enableBlending;
  29228. serializationObject.blendingSpeed = this.blendingSpeed;
  29229. var dataType = this.dataType;
  29230. serializationObject.keys = [];
  29231. var keys = this.getKeys();
  29232. for (var index = 0; index < keys.length; index++) {
  29233. var animationKey = keys[index];
  29234. var key = {};
  29235. key.frame = animationKey.frame;
  29236. switch (dataType) {
  29237. case Animation.ANIMATIONTYPE_FLOAT:
  29238. key.values = [animationKey.value];
  29239. break;
  29240. case Animation.ANIMATIONTYPE_QUATERNION:
  29241. case Animation.ANIMATIONTYPE_MATRIX:
  29242. case Animation.ANIMATIONTYPE_VECTOR3:
  29243. case Animation.ANIMATIONTYPE_COLOR3:
  29244. key.values = animationKey.value.asArray();
  29245. break;
  29246. }
  29247. serializationObject.keys.push(key);
  29248. }
  29249. serializationObject.ranges = [];
  29250. for (var name in this._ranges) {
  29251. var range = {};
  29252. range.name = name;
  29253. range.from = this._ranges[name].from;
  29254. range.to = this._ranges[name].to;
  29255. serializationObject.ranges.push(range);
  29256. }
  29257. return serializationObject;
  29258. };
  29259. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29260. get: function () {
  29261. return Animation._ANIMATIONTYPE_FLOAT;
  29262. },
  29263. enumerable: true,
  29264. configurable: true
  29265. });
  29266. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29267. get: function () {
  29268. return Animation._ANIMATIONTYPE_VECTOR3;
  29269. },
  29270. enumerable: true,
  29271. configurable: true
  29272. });
  29273. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29274. get: function () {
  29275. return Animation._ANIMATIONTYPE_VECTOR2;
  29276. },
  29277. enumerable: true,
  29278. configurable: true
  29279. });
  29280. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29281. get: function () {
  29282. return Animation._ANIMATIONTYPE_SIZE;
  29283. },
  29284. enumerable: true,
  29285. configurable: true
  29286. });
  29287. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29288. get: function () {
  29289. return Animation._ANIMATIONTYPE_QUATERNION;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29295. get: function () {
  29296. return Animation._ANIMATIONTYPE_MATRIX;
  29297. },
  29298. enumerable: true,
  29299. configurable: true
  29300. });
  29301. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29302. get: function () {
  29303. return Animation._ANIMATIONTYPE_COLOR3;
  29304. },
  29305. enumerable: true,
  29306. configurable: true
  29307. });
  29308. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29309. get: function () {
  29310. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29311. },
  29312. enumerable: true,
  29313. configurable: true
  29314. });
  29315. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29316. get: function () {
  29317. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29318. },
  29319. enumerable: true,
  29320. configurable: true
  29321. });
  29322. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29323. get: function () {
  29324. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29325. },
  29326. enumerable: true,
  29327. configurable: true
  29328. });
  29329. Animation.Parse = function (parsedAnimation) {
  29330. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29331. var dataType = parsedAnimation.dataType;
  29332. var keys = [];
  29333. var data;
  29334. var index;
  29335. if (parsedAnimation.enableBlending) {
  29336. animation.enableBlending = parsedAnimation.enableBlending;
  29337. }
  29338. if (parsedAnimation.blendingSpeed) {
  29339. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  29340. }
  29341. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29342. var key = parsedAnimation.keys[index];
  29343. switch (dataType) {
  29344. case Animation.ANIMATIONTYPE_FLOAT:
  29345. data = key.values[0];
  29346. break;
  29347. case Animation.ANIMATIONTYPE_QUATERNION:
  29348. data = BABYLON.Quaternion.FromArray(key.values);
  29349. break;
  29350. case Animation.ANIMATIONTYPE_MATRIX:
  29351. data = BABYLON.Matrix.FromArray(key.values);
  29352. break;
  29353. case Animation.ANIMATIONTYPE_COLOR3:
  29354. data = BABYLON.Color3.FromArray(key.values);
  29355. break;
  29356. case Animation.ANIMATIONTYPE_VECTOR3:
  29357. default:
  29358. data = BABYLON.Vector3.FromArray(key.values);
  29359. break;
  29360. }
  29361. keys.push({
  29362. frame: key.frame,
  29363. value: data
  29364. });
  29365. }
  29366. animation.setKeys(keys);
  29367. if (parsedAnimation.ranges) {
  29368. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29369. data = parsedAnimation.ranges[index];
  29370. animation.createRange(data.name, data.from, data.to);
  29371. }
  29372. }
  29373. return animation;
  29374. };
  29375. Animation.AppendSerializedAnimations = function (source, destination) {
  29376. if (source.animations) {
  29377. destination.animations = [];
  29378. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29379. var animation = source.animations[animationIndex];
  29380. destination.animations.push(animation.serialize());
  29381. }
  29382. }
  29383. };
  29384. return Animation;
  29385. }());
  29386. // Statics
  29387. Animation._ANIMATIONTYPE_FLOAT = 0;
  29388. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29389. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29390. Animation._ANIMATIONTYPE_MATRIX = 3;
  29391. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29392. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29393. Animation._ANIMATIONTYPE_SIZE = 6;
  29394. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29395. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29396. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29397. BABYLON.Animation = Animation;
  29398. })(BABYLON || (BABYLON = {}));
  29399. //# sourceMappingURL=babylon.animation.js.map
  29400. var BABYLON;
  29401. (function (BABYLON) {
  29402. var Animatable = (function () {
  29403. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29404. if (fromFrame === void 0) { fromFrame = 0; }
  29405. if (toFrame === void 0) { toFrame = 100; }
  29406. if (loopAnimation === void 0) { loopAnimation = false; }
  29407. if (speedRatio === void 0) { speedRatio = 1.0; }
  29408. this.target = target;
  29409. this.fromFrame = fromFrame;
  29410. this.toFrame = toFrame;
  29411. this.loopAnimation = loopAnimation;
  29412. this.speedRatio = speedRatio;
  29413. this.onAnimationEnd = onAnimationEnd;
  29414. this._localDelayOffset = null;
  29415. this._pausedDelay = null;
  29416. this._animations = new Array();
  29417. this._paused = false;
  29418. this.animationStarted = false;
  29419. if (animations) {
  29420. this.appendAnimations(target, animations);
  29421. }
  29422. this._scene = scene;
  29423. scene._activeAnimatables.push(this);
  29424. }
  29425. // Methods
  29426. Animatable.prototype.getAnimations = function () {
  29427. return this._animations;
  29428. };
  29429. Animatable.prototype.appendAnimations = function (target, animations) {
  29430. for (var index = 0; index < animations.length; index++) {
  29431. var animation = animations[index];
  29432. animation._target = target;
  29433. this._animations.push(animation);
  29434. }
  29435. };
  29436. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29437. var animations = this._animations;
  29438. for (var index = 0; index < animations.length; index++) {
  29439. if (animations[index].targetProperty === property) {
  29440. return animations[index];
  29441. }
  29442. }
  29443. return null;
  29444. };
  29445. Animatable.prototype.reset = function () {
  29446. var animations = this._animations;
  29447. for (var index = 0; index < animations.length; index++) {
  29448. animations[index].reset();
  29449. }
  29450. this._localDelayOffset = null;
  29451. this._pausedDelay = null;
  29452. };
  29453. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29454. var animations = this._animations;
  29455. for (var index = 0; index < animations.length; index++) {
  29456. animations[index].enableBlending = true;
  29457. animations[index].blendingSpeed = blendingSpeed;
  29458. }
  29459. };
  29460. Animatable.prototype.disableBlending = function () {
  29461. var animations = this._animations;
  29462. for (var index = 0; index < animations.length; index++) {
  29463. animations[index].enableBlending = false;
  29464. }
  29465. };
  29466. Animatable.prototype.goToFrame = function (frame) {
  29467. var animations = this._animations;
  29468. if (animations[0]) {
  29469. var fps = animations[0].framePerSecond;
  29470. var currentFrame = animations[0].currentFrame;
  29471. var adjustTime = frame - currentFrame;
  29472. var delay = adjustTime * 1000 / fps;
  29473. this._localDelayOffset -= delay;
  29474. }
  29475. for (var index = 0; index < animations.length; index++) {
  29476. animations[index].goToFrame(frame);
  29477. }
  29478. };
  29479. Animatable.prototype.pause = function () {
  29480. if (this._paused) {
  29481. return;
  29482. }
  29483. this._paused = true;
  29484. };
  29485. Animatable.prototype.restart = function () {
  29486. this._paused = false;
  29487. };
  29488. Animatable.prototype.stop = function (animationName) {
  29489. if (animationName) {
  29490. var idx = this._scene._activeAnimatables.indexOf(this);
  29491. if (idx > -1) {
  29492. var animations = this._animations;
  29493. for (var index = animations.length - 1; index >= 0; index--) {
  29494. if (typeof animationName === "string" && animations[index].name != animationName) {
  29495. continue;
  29496. }
  29497. animations[index].reset();
  29498. animations.splice(index, 1);
  29499. }
  29500. if (animations.length == 0) {
  29501. this._scene._activeAnimatables.splice(idx, 1);
  29502. if (this.onAnimationEnd) {
  29503. this.onAnimationEnd();
  29504. }
  29505. }
  29506. }
  29507. }
  29508. else {
  29509. var index = this._scene._activeAnimatables.indexOf(this);
  29510. if (index > -1) {
  29511. this._scene._activeAnimatables.splice(index, 1);
  29512. var animations = this._animations;
  29513. for (var index = 0; index < animations.length; index++) {
  29514. animations[index].reset();
  29515. }
  29516. if (this.onAnimationEnd) {
  29517. this.onAnimationEnd();
  29518. }
  29519. }
  29520. }
  29521. };
  29522. Animatable.prototype._animate = function (delay) {
  29523. if (this._paused) {
  29524. this.animationStarted = false;
  29525. if (this._pausedDelay === null) {
  29526. this._pausedDelay = delay;
  29527. }
  29528. return true;
  29529. }
  29530. if (this._localDelayOffset === null) {
  29531. this._localDelayOffset = delay;
  29532. }
  29533. else if (this._pausedDelay !== null) {
  29534. this._localDelayOffset += delay - this._pausedDelay;
  29535. this._pausedDelay = null;
  29536. }
  29537. // Animating
  29538. var running = false;
  29539. var animations = this._animations;
  29540. var index;
  29541. for (index = 0; index < animations.length; index++) {
  29542. var animation = animations[index];
  29543. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29544. running = running || isRunning;
  29545. }
  29546. this.animationStarted = running;
  29547. if (!running) {
  29548. // Remove from active animatables
  29549. index = this._scene._activeAnimatables.indexOf(this);
  29550. this._scene._activeAnimatables.splice(index, 1);
  29551. }
  29552. if (!running && this.onAnimationEnd) {
  29553. this.onAnimationEnd();
  29554. this.onAnimationEnd = null;
  29555. }
  29556. return running;
  29557. };
  29558. return Animatable;
  29559. }());
  29560. BABYLON.Animatable = Animatable;
  29561. })(BABYLON || (BABYLON = {}));
  29562. //# sourceMappingURL=babylon.animatable.js.map
  29563. var BABYLON;
  29564. (function (BABYLON) {
  29565. var EasingFunction = (function () {
  29566. function EasingFunction() {
  29567. // Properties
  29568. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29569. }
  29570. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29571. get: function () {
  29572. return EasingFunction._EASINGMODE_EASEIN;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29578. get: function () {
  29579. return EasingFunction._EASINGMODE_EASEOUT;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29585. get: function () {
  29586. return EasingFunction._EASINGMODE_EASEINOUT;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29592. var n = Math.min(Math.max(easingMode, 0), 2);
  29593. this._easingMode = n;
  29594. };
  29595. EasingFunction.prototype.getEasingMode = function () {
  29596. return this._easingMode;
  29597. };
  29598. EasingFunction.prototype.easeInCore = function (gradient) {
  29599. throw new Error('You must implement this method');
  29600. };
  29601. EasingFunction.prototype.ease = function (gradient) {
  29602. switch (this._easingMode) {
  29603. case EasingFunction.EASINGMODE_EASEIN:
  29604. return this.easeInCore(gradient);
  29605. case EasingFunction.EASINGMODE_EASEOUT:
  29606. return (1 - this.easeInCore(1 - gradient));
  29607. }
  29608. if (gradient >= 0.5) {
  29609. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29610. }
  29611. return (this.easeInCore(gradient * 2) * 0.5);
  29612. };
  29613. return EasingFunction;
  29614. }());
  29615. //Statics
  29616. EasingFunction._EASINGMODE_EASEIN = 0;
  29617. EasingFunction._EASINGMODE_EASEOUT = 1;
  29618. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29619. BABYLON.EasingFunction = EasingFunction;
  29620. var CircleEase = (function (_super) {
  29621. __extends(CircleEase, _super);
  29622. function CircleEase() {
  29623. return _super !== null && _super.apply(this, arguments) || this;
  29624. }
  29625. CircleEase.prototype.easeInCore = function (gradient) {
  29626. gradient = Math.max(0, Math.min(1, gradient));
  29627. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29628. };
  29629. return CircleEase;
  29630. }(EasingFunction));
  29631. BABYLON.CircleEase = CircleEase;
  29632. var BackEase = (function (_super) {
  29633. __extends(BackEase, _super);
  29634. function BackEase(amplitude) {
  29635. if (amplitude === void 0) { amplitude = 1; }
  29636. var _this = _super.call(this) || this;
  29637. _this.amplitude = amplitude;
  29638. return _this;
  29639. }
  29640. BackEase.prototype.easeInCore = function (gradient) {
  29641. var num = Math.max(0, this.amplitude);
  29642. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29643. };
  29644. return BackEase;
  29645. }(EasingFunction));
  29646. BABYLON.BackEase = BackEase;
  29647. var BounceEase = (function (_super) {
  29648. __extends(BounceEase, _super);
  29649. function BounceEase(bounces, bounciness) {
  29650. if (bounces === void 0) { bounces = 3; }
  29651. if (bounciness === void 0) { bounciness = 2; }
  29652. var _this = _super.call(this) || this;
  29653. _this.bounces = bounces;
  29654. _this.bounciness = bounciness;
  29655. return _this;
  29656. }
  29657. BounceEase.prototype.easeInCore = function (gradient) {
  29658. var y = Math.max(0.0, this.bounces);
  29659. var bounciness = this.bounciness;
  29660. if (bounciness <= 1.0) {
  29661. bounciness = 1.001;
  29662. }
  29663. var num9 = Math.pow(bounciness, y);
  29664. var num5 = 1.0 - bounciness;
  29665. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29666. var num15 = gradient * num4;
  29667. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29668. var num3 = Math.floor(num65);
  29669. var num13 = num3 + 1.0;
  29670. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29671. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29672. var num7 = (num8 + num12) * 0.5;
  29673. var num6 = gradient - num7;
  29674. var num2 = num7 - num8;
  29675. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29676. };
  29677. return BounceEase;
  29678. }(EasingFunction));
  29679. BABYLON.BounceEase = BounceEase;
  29680. var CubicEase = (function (_super) {
  29681. __extends(CubicEase, _super);
  29682. function CubicEase() {
  29683. return _super !== null && _super.apply(this, arguments) || this;
  29684. }
  29685. CubicEase.prototype.easeInCore = function (gradient) {
  29686. return (gradient * gradient * gradient);
  29687. };
  29688. return CubicEase;
  29689. }(EasingFunction));
  29690. BABYLON.CubicEase = CubicEase;
  29691. var ElasticEase = (function (_super) {
  29692. __extends(ElasticEase, _super);
  29693. function ElasticEase(oscillations, springiness) {
  29694. if (oscillations === void 0) { oscillations = 3; }
  29695. if (springiness === void 0) { springiness = 3; }
  29696. var _this = _super.call(this) || this;
  29697. _this.oscillations = oscillations;
  29698. _this.springiness = springiness;
  29699. return _this;
  29700. }
  29701. ElasticEase.prototype.easeInCore = function (gradient) {
  29702. var num2;
  29703. var num3 = Math.max(0.0, this.oscillations);
  29704. var num = Math.max(0.0, this.springiness);
  29705. if (num == 0) {
  29706. num2 = gradient;
  29707. }
  29708. else {
  29709. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29710. }
  29711. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29712. };
  29713. return ElasticEase;
  29714. }(EasingFunction));
  29715. BABYLON.ElasticEase = ElasticEase;
  29716. var ExponentialEase = (function (_super) {
  29717. __extends(ExponentialEase, _super);
  29718. function ExponentialEase(exponent) {
  29719. if (exponent === void 0) { exponent = 2; }
  29720. var _this = _super.call(this) || this;
  29721. _this.exponent = exponent;
  29722. return _this;
  29723. }
  29724. ExponentialEase.prototype.easeInCore = function (gradient) {
  29725. if (this.exponent <= 0) {
  29726. return gradient;
  29727. }
  29728. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29729. };
  29730. return ExponentialEase;
  29731. }(EasingFunction));
  29732. BABYLON.ExponentialEase = ExponentialEase;
  29733. var PowerEase = (function (_super) {
  29734. __extends(PowerEase, _super);
  29735. function PowerEase(power) {
  29736. if (power === void 0) { power = 2; }
  29737. var _this = _super.call(this) || this;
  29738. _this.power = power;
  29739. return _this;
  29740. }
  29741. PowerEase.prototype.easeInCore = function (gradient) {
  29742. var y = Math.max(0.0, this.power);
  29743. return Math.pow(gradient, y);
  29744. };
  29745. return PowerEase;
  29746. }(EasingFunction));
  29747. BABYLON.PowerEase = PowerEase;
  29748. var QuadraticEase = (function (_super) {
  29749. __extends(QuadraticEase, _super);
  29750. function QuadraticEase() {
  29751. return _super !== null && _super.apply(this, arguments) || this;
  29752. }
  29753. QuadraticEase.prototype.easeInCore = function (gradient) {
  29754. return (gradient * gradient);
  29755. };
  29756. return QuadraticEase;
  29757. }(EasingFunction));
  29758. BABYLON.QuadraticEase = QuadraticEase;
  29759. var QuarticEase = (function (_super) {
  29760. __extends(QuarticEase, _super);
  29761. function QuarticEase() {
  29762. return _super !== null && _super.apply(this, arguments) || this;
  29763. }
  29764. QuarticEase.prototype.easeInCore = function (gradient) {
  29765. return (gradient * gradient * gradient * gradient);
  29766. };
  29767. return QuarticEase;
  29768. }(EasingFunction));
  29769. BABYLON.QuarticEase = QuarticEase;
  29770. var QuinticEase = (function (_super) {
  29771. __extends(QuinticEase, _super);
  29772. function QuinticEase() {
  29773. return _super !== null && _super.apply(this, arguments) || this;
  29774. }
  29775. QuinticEase.prototype.easeInCore = function (gradient) {
  29776. return (gradient * gradient * gradient * gradient * gradient);
  29777. };
  29778. return QuinticEase;
  29779. }(EasingFunction));
  29780. BABYLON.QuinticEase = QuinticEase;
  29781. var SineEase = (function (_super) {
  29782. __extends(SineEase, _super);
  29783. function SineEase() {
  29784. return _super !== null && _super.apply(this, arguments) || this;
  29785. }
  29786. SineEase.prototype.easeInCore = function (gradient) {
  29787. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29788. };
  29789. return SineEase;
  29790. }(EasingFunction));
  29791. BABYLON.SineEase = SineEase;
  29792. var BezierCurveEase = (function (_super) {
  29793. __extends(BezierCurveEase, _super);
  29794. function BezierCurveEase(x1, y1, x2, y2) {
  29795. if (x1 === void 0) { x1 = 0; }
  29796. if (y1 === void 0) { y1 = 0; }
  29797. if (x2 === void 0) { x2 = 1; }
  29798. if (y2 === void 0) { y2 = 1; }
  29799. var _this = _super.call(this) || this;
  29800. _this.x1 = x1;
  29801. _this.y1 = y1;
  29802. _this.x2 = x2;
  29803. _this.y2 = y2;
  29804. return _this;
  29805. }
  29806. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29807. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29808. };
  29809. return BezierCurveEase;
  29810. }(EasingFunction));
  29811. BABYLON.BezierCurveEase = BezierCurveEase;
  29812. })(BABYLON || (BABYLON = {}));
  29813. //# sourceMappingURL=babylon.easing.js.map
  29814. var BABYLON;
  29815. (function (BABYLON) {
  29816. BABYLON.CameraInputTypes = {};
  29817. var CameraInputsManager = (function () {
  29818. function CameraInputsManager(camera) {
  29819. this.attached = {};
  29820. this.camera = camera;
  29821. this.checkInputs = function () { };
  29822. }
  29823. CameraInputsManager.prototype.add = function (input) {
  29824. var type = input.getSimpleName();
  29825. if (this.attached[type]) {
  29826. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29827. return;
  29828. }
  29829. this.attached[type] = input;
  29830. input.camera = this.camera;
  29831. //for checkInputs, we are dynamically creating a function
  29832. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29833. if (input.checkInputs) {
  29834. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29835. }
  29836. if (this.attachedElement) {
  29837. input.attachControl(this.attachedElement);
  29838. }
  29839. };
  29840. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29841. for (var cam in this.attached) {
  29842. var input = this.attached[cam];
  29843. if (input === inputToRemove) {
  29844. input.detachControl(this.attachedElement);
  29845. delete this.attached[cam];
  29846. this.rebuildInputCheck();
  29847. }
  29848. }
  29849. };
  29850. CameraInputsManager.prototype.removeByType = function (inputType) {
  29851. for (var cam in this.attached) {
  29852. var input = this.attached[cam];
  29853. if (input.getTypeName() === inputType) {
  29854. input.detachControl(this.attachedElement);
  29855. delete this.attached[cam];
  29856. this.rebuildInputCheck();
  29857. }
  29858. }
  29859. };
  29860. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29861. var current = this.checkInputs;
  29862. return function () {
  29863. current();
  29864. fn();
  29865. };
  29866. };
  29867. CameraInputsManager.prototype.attachInput = function (input) {
  29868. input.attachControl(this.attachedElement, this.noPreventDefault);
  29869. };
  29870. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29871. if (this.attachedElement) {
  29872. return;
  29873. }
  29874. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29875. this.attachedElement = element;
  29876. this.noPreventDefault = noPreventDefault;
  29877. for (var cam in this.attached) {
  29878. var input = this.attached[cam];
  29879. this.attached[cam].attachControl(element, noPreventDefault);
  29880. }
  29881. };
  29882. CameraInputsManager.prototype.detachElement = function (element) {
  29883. if (this.attachedElement !== element) {
  29884. return;
  29885. }
  29886. for (var cam in this.attached) {
  29887. var input = this.attached[cam];
  29888. this.attached[cam].detachControl(element);
  29889. }
  29890. this.attachedElement = null;
  29891. };
  29892. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29893. this.checkInputs = function () { };
  29894. for (var cam in this.attached) {
  29895. var input = this.attached[cam];
  29896. if (input.checkInputs) {
  29897. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29898. }
  29899. }
  29900. };
  29901. CameraInputsManager.prototype.clear = function () {
  29902. if (this.attachedElement) {
  29903. this.detachElement(this.attachedElement);
  29904. }
  29905. this.attached = {};
  29906. this.attachedElement = null;
  29907. this.checkInputs = function () { };
  29908. };
  29909. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29910. var inputs = {};
  29911. for (var cam in this.attached) {
  29912. var input = this.attached[cam];
  29913. var res = BABYLON.SerializationHelper.Serialize(input);
  29914. inputs[input.getTypeName()] = res;
  29915. }
  29916. serializedCamera.inputsmgr = inputs;
  29917. };
  29918. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29919. var parsedInputs = parsedCamera.inputsmgr;
  29920. if (parsedInputs) {
  29921. this.clear();
  29922. for (var n in parsedInputs) {
  29923. var construct = BABYLON.CameraInputTypes[n];
  29924. if (construct) {
  29925. var parsedinput = parsedInputs[n];
  29926. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29927. this.add(input);
  29928. }
  29929. }
  29930. }
  29931. else {
  29932. //2016-03-08 this part is for managing backward compatibility
  29933. for (var n in this.attached) {
  29934. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29935. if (construct) {
  29936. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29937. this.remove(this.attached[n]);
  29938. this.add(input);
  29939. }
  29940. }
  29941. }
  29942. };
  29943. return CameraInputsManager;
  29944. }());
  29945. BABYLON.CameraInputsManager = CameraInputsManager;
  29946. })(BABYLON || (BABYLON = {}));
  29947. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29948. /// <reference path="babylon.camera.ts" />
  29949. var BABYLON;
  29950. (function (BABYLON) {
  29951. var TargetCamera = (function (_super) {
  29952. __extends(TargetCamera, _super);
  29953. function TargetCamera(name, position, scene) {
  29954. var _this = _super.call(this, name, position, scene) || this;
  29955. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29956. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29957. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29958. _this.speed = 2.0;
  29959. _this.noRotationConstraint = false;
  29960. _this.lockedTarget = null;
  29961. _this._currentTarget = BABYLON.Vector3.Zero();
  29962. _this._viewMatrix = BABYLON.Matrix.Zero();
  29963. _this._camMatrix = BABYLON.Matrix.Zero();
  29964. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29965. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29966. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29967. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29968. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29969. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29970. _this._tempMatrix = BABYLON.Matrix.Zero();
  29971. return _this;
  29972. }
  29973. TargetCamera.prototype.getFrontPosition = function (distance) {
  29974. var direction = this.getTarget().subtract(this.position);
  29975. direction.normalize();
  29976. direction.scaleInPlace(distance);
  29977. return this.globalPosition.add(direction);
  29978. };
  29979. TargetCamera.prototype._getLockedTargetPosition = function () {
  29980. if (!this.lockedTarget) {
  29981. return null;
  29982. }
  29983. if (this.lockedTarget.absolutePosition) {
  29984. this.lockedTarget.computeWorldMatrix();
  29985. }
  29986. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29987. };
  29988. // Cache
  29989. TargetCamera.prototype._initCache = function () {
  29990. _super.prototype._initCache.call(this);
  29991. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29992. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29993. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29994. };
  29995. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29996. if (!ignoreParentClass) {
  29997. _super.prototype._updateCache.call(this);
  29998. }
  29999. var lockedTargetPosition = this._getLockedTargetPosition();
  30000. if (!lockedTargetPosition) {
  30001. this._cache.lockedTarget = null;
  30002. }
  30003. else {
  30004. if (!this._cache.lockedTarget) {
  30005. this._cache.lockedTarget = lockedTargetPosition.clone();
  30006. }
  30007. else {
  30008. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30009. }
  30010. }
  30011. this._cache.rotation.copyFrom(this.rotation);
  30012. if (this.rotationQuaternion)
  30013. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30014. };
  30015. // Synchronized
  30016. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30017. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30018. return false;
  30019. }
  30020. var lockedTargetPosition = this._getLockedTargetPosition();
  30021. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30022. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30023. };
  30024. // Methods
  30025. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30026. var engine = this.getEngine();
  30027. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30028. };
  30029. // Target
  30030. TargetCamera.prototype.setTarget = function (target) {
  30031. this.upVector.normalize();
  30032. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30033. this._camMatrix.invert();
  30034. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30035. var vDir = target.subtract(this.position);
  30036. if (vDir.x >= 0.0) {
  30037. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30038. }
  30039. else {
  30040. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30041. }
  30042. this.rotation.z = 0;
  30043. if (isNaN(this.rotation.x)) {
  30044. this.rotation.x = 0;
  30045. }
  30046. if (isNaN(this.rotation.y)) {
  30047. this.rotation.y = 0;
  30048. }
  30049. if (isNaN(this.rotation.z)) {
  30050. this.rotation.z = 0;
  30051. }
  30052. if (this.rotationQuaternion) {
  30053. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30054. }
  30055. };
  30056. /**
  30057. * Return the current target position of the camera. This value is expressed in local space.
  30058. */
  30059. TargetCamera.prototype.getTarget = function () {
  30060. return this._currentTarget;
  30061. };
  30062. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30063. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30064. };
  30065. TargetCamera.prototype._updatePosition = function () {
  30066. if (this.parent) {
  30067. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30068. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30069. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30070. return;
  30071. }
  30072. this.position.addInPlace(this.cameraDirection);
  30073. };
  30074. TargetCamera.prototype._checkInputs = function () {
  30075. var needToMove = this._decideIfNeedsToMove();
  30076. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30077. // Move
  30078. if (needToMove) {
  30079. this._updatePosition();
  30080. }
  30081. // Rotate
  30082. if (needToRotate) {
  30083. this.rotation.x += this.cameraRotation.x;
  30084. this.rotation.y += this.cameraRotation.y;
  30085. //rotate, if quaternion is set and rotation was used
  30086. if (this.rotationQuaternion) {
  30087. var len = this.rotation.lengthSquared();
  30088. if (len) {
  30089. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30090. }
  30091. }
  30092. if (!this.noRotationConstraint) {
  30093. var limit = (Math.PI / 2) * 0.95;
  30094. if (this.rotation.x > limit)
  30095. this.rotation.x = limit;
  30096. if (this.rotation.x < -limit)
  30097. this.rotation.x = -limit;
  30098. }
  30099. }
  30100. // Inertia
  30101. if (needToMove) {
  30102. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  30103. this.cameraDirection.x = 0;
  30104. }
  30105. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  30106. this.cameraDirection.y = 0;
  30107. }
  30108. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  30109. this.cameraDirection.z = 0;
  30110. }
  30111. this.cameraDirection.scaleInPlace(this.inertia);
  30112. }
  30113. if (needToRotate) {
  30114. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  30115. this.cameraRotation.x = 0;
  30116. }
  30117. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  30118. this.cameraRotation.y = 0;
  30119. }
  30120. this.cameraRotation.scaleInPlace(this.inertia);
  30121. }
  30122. _super.prototype._checkInputs.call(this);
  30123. };
  30124. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30125. if (this.rotationQuaternion) {
  30126. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30127. //update the up vector!
  30128. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30129. }
  30130. else {
  30131. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30132. }
  30133. };
  30134. TargetCamera.prototype._getViewMatrix = function () {
  30135. if (!this.lockedTarget) {
  30136. // Compute
  30137. this._updateCameraRotationMatrix();
  30138. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30139. // Computing target and final matrix
  30140. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30141. }
  30142. else {
  30143. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30144. }
  30145. if (this.getScene().useRightHandedSystem) {
  30146. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30147. }
  30148. else {
  30149. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30150. }
  30151. return this._viewMatrix;
  30152. };
  30153. /**
  30154. * @override
  30155. * Override Camera.createRigCamera
  30156. */
  30157. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30158. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30159. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30160. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30161. if (!this.rotationQuaternion) {
  30162. this.rotationQuaternion = new BABYLON.Quaternion();
  30163. }
  30164. rigCamera._cameraRigParams = {};
  30165. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30166. }
  30167. return rigCamera;
  30168. }
  30169. return null;
  30170. };
  30171. /**
  30172. * @override
  30173. * Override Camera._updateRigCameras
  30174. */
  30175. TargetCamera.prototype._updateRigCameras = function () {
  30176. var camLeft = this._rigCameras[0];
  30177. var camRight = this._rigCameras[1];
  30178. switch (this.cameraRigMode) {
  30179. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30183. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30184. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30185. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30186. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30187. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30188. camLeft.setTarget(this.getTarget());
  30189. camRight.setTarget(this.getTarget());
  30190. break;
  30191. case BABYLON.Camera.RIG_MODE_VR:
  30192. if (camLeft.rotationQuaternion) {
  30193. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30194. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30195. }
  30196. else {
  30197. camLeft.rotation.copyFrom(this.rotation);
  30198. camRight.rotation.copyFrom(this.rotation);
  30199. }
  30200. camLeft.position.copyFrom(this.position);
  30201. camRight.position.copyFrom(this.position);
  30202. break;
  30203. }
  30204. _super.prototype._updateRigCameras.call(this);
  30205. };
  30206. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30207. if (!this._rigCamTransformMatrix) {
  30208. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30209. }
  30210. var target = this.getTarget();
  30211. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30212. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30213. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30214. };
  30215. TargetCamera.prototype.getClassName = function () {
  30216. return "TargetCamera";
  30217. };
  30218. return TargetCamera;
  30219. }(BABYLON.Camera));
  30220. __decorate([
  30221. BABYLON.serializeAsVector3()
  30222. ], TargetCamera.prototype, "rotation", void 0);
  30223. __decorate([
  30224. BABYLON.serialize()
  30225. ], TargetCamera.prototype, "speed", void 0);
  30226. __decorate([
  30227. BABYLON.serializeAsMeshReference("lockedTargetId")
  30228. ], TargetCamera.prototype, "lockedTarget", void 0);
  30229. BABYLON.TargetCamera = TargetCamera;
  30230. })(BABYLON || (BABYLON = {}));
  30231. //# sourceMappingURL=babylon.targetCamera.js.map
  30232. var BABYLON;
  30233. (function (BABYLON) {
  30234. var ArcRotateCameraKeyboardMoveInput = (function () {
  30235. function ArcRotateCameraKeyboardMoveInput() {
  30236. this._keys = [];
  30237. this.keysUp = [38];
  30238. this.keysDown = [40];
  30239. this.keysLeft = [37];
  30240. this.keysRight = [39];
  30241. }
  30242. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30243. var _this = this;
  30244. element.tabIndex = 1;
  30245. this._onKeyDown = function (evt) {
  30246. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30247. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30248. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30249. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30250. var index = _this._keys.indexOf(evt.keyCode);
  30251. if (index === -1) {
  30252. _this._keys.push(evt.keyCode);
  30253. }
  30254. if (evt.preventDefault) {
  30255. if (!noPreventDefault) {
  30256. evt.preventDefault();
  30257. }
  30258. }
  30259. }
  30260. };
  30261. this._onKeyUp = function (evt) {
  30262. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30263. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30264. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30265. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30266. var index = _this._keys.indexOf(evt.keyCode);
  30267. if (index >= 0) {
  30268. _this._keys.splice(index, 1);
  30269. }
  30270. if (evt.preventDefault) {
  30271. if (!noPreventDefault) {
  30272. evt.preventDefault();
  30273. }
  30274. }
  30275. }
  30276. };
  30277. this._onLostFocus = function () {
  30278. _this._keys = [];
  30279. };
  30280. element.addEventListener("keydown", this._onKeyDown, false);
  30281. element.addEventListener("keyup", this._onKeyUp, false);
  30282. BABYLON.Tools.RegisterTopRootEvents([
  30283. { name: "blur", handler: this._onLostFocus }
  30284. ]);
  30285. };
  30286. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30287. if (element) {
  30288. element.removeEventListener("keydown", this._onKeyDown);
  30289. element.removeEventListener("keyup", this._onKeyUp);
  30290. }
  30291. BABYLON.Tools.UnregisterTopRootEvents([
  30292. { name: "blur", handler: this._onLostFocus }
  30293. ]);
  30294. this._keys = [];
  30295. this._onKeyDown = null;
  30296. this._onKeyUp = null;
  30297. this._onLostFocus = null;
  30298. };
  30299. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30300. if (this._onKeyDown) {
  30301. var camera = this.camera;
  30302. for (var index = 0; index < this._keys.length; index++) {
  30303. var keyCode = this._keys[index];
  30304. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30305. camera.inertialAlphaOffset -= 0.01;
  30306. }
  30307. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30308. camera.inertialBetaOffset -= 0.01;
  30309. }
  30310. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30311. camera.inertialAlphaOffset += 0.01;
  30312. }
  30313. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30314. camera.inertialBetaOffset += 0.01;
  30315. }
  30316. }
  30317. }
  30318. };
  30319. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30320. return "ArcRotateCameraKeyboardMoveInput";
  30321. };
  30322. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30323. return "keyboard";
  30324. };
  30325. return ArcRotateCameraKeyboardMoveInput;
  30326. }());
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30330. __decorate([
  30331. BABYLON.serialize()
  30332. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30333. __decorate([
  30334. BABYLON.serialize()
  30335. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30336. __decorate([
  30337. BABYLON.serialize()
  30338. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30339. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30340. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30341. })(BABYLON || (BABYLON = {}));
  30342. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30343. var BABYLON;
  30344. (function (BABYLON) {
  30345. var ArcRotateCameraMouseWheelInput = (function () {
  30346. function ArcRotateCameraMouseWheelInput() {
  30347. this.wheelPrecision = 3.0;
  30348. }
  30349. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30350. var _this = this;
  30351. this._wheel = function (p, s) {
  30352. //sanity check - this should be a PointerWheel event.
  30353. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30354. return;
  30355. var event = p.event;
  30356. var delta = 0;
  30357. if (event.wheelDelta) {
  30358. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30359. }
  30360. else if (event.detail) {
  30361. delta = -event.detail / _this.wheelPrecision;
  30362. }
  30363. if (delta)
  30364. _this.camera.inertialRadiusOffset += delta;
  30365. if (event.preventDefault) {
  30366. if (!noPreventDefault) {
  30367. event.preventDefault();
  30368. }
  30369. }
  30370. };
  30371. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30372. };
  30373. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30374. if (this._observer && element) {
  30375. this.camera.getScene().onPointerObservable.remove(this._observer);
  30376. this._observer = null;
  30377. this._wheel = null;
  30378. }
  30379. };
  30380. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30381. return "ArcRotateCameraMouseWheelInput";
  30382. };
  30383. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30384. return "mousewheel";
  30385. };
  30386. return ArcRotateCameraMouseWheelInput;
  30387. }());
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30391. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30392. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30393. })(BABYLON || (BABYLON = {}));
  30394. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30395. var BABYLON;
  30396. (function (BABYLON) {
  30397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30398. var ArcRotateCameraPointersInput = (function () {
  30399. function ArcRotateCameraPointersInput() {
  30400. this.buttons = [0, 1, 2];
  30401. this.angularSensibilityX = 1000.0;
  30402. this.angularSensibilityY = 1000.0;
  30403. this.pinchPrecision = 6.0;
  30404. this.panningSensibility = 50.0;
  30405. this._isPanClick = false;
  30406. this.pinchInwards = true;
  30407. }
  30408. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30409. var _this = this;
  30410. var engine = this.camera.getEngine();
  30411. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30412. var pointA, pointB;
  30413. var previousPinchDistance = 0;
  30414. this._pointerInput = function (p, s) {
  30415. var evt = p.event;
  30416. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30417. return;
  30418. }
  30419. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30420. try {
  30421. evt.srcElement.setPointerCapture(evt.pointerId);
  30422. }
  30423. catch (e) {
  30424. //Nothing to do with the error. Execution will continue.
  30425. }
  30426. // Manage panning with pan button click
  30427. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30428. // manage pointers
  30429. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30430. if (pointA === undefined) {
  30431. pointA = cacheSoloPointer;
  30432. }
  30433. else if (pointB === undefined) {
  30434. pointB = cacheSoloPointer;
  30435. }
  30436. if (!noPreventDefault) {
  30437. evt.preventDefault();
  30438. element.focus();
  30439. }
  30440. }
  30441. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30442. try {
  30443. evt.srcElement.releasePointerCapture(evt.pointerId);
  30444. }
  30445. catch (e) {
  30446. //Nothing to do with the error.
  30447. }
  30448. cacheSoloPointer = null;
  30449. previousPinchDistance = 0;
  30450. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30451. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30452. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30453. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30454. pointA = pointB = undefined;
  30455. if (!noPreventDefault) {
  30456. evt.preventDefault();
  30457. }
  30458. }
  30459. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30460. if (!noPreventDefault) {
  30461. evt.preventDefault();
  30462. }
  30463. // One button down
  30464. if (pointA && pointB === undefined) {
  30465. if (_this.panningSensibility !== 0 &&
  30466. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30467. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30468. _this.camera
  30469. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30470. _this.camera
  30471. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30472. }
  30473. else {
  30474. var offsetX = evt.clientX - cacheSoloPointer.x;
  30475. var offsetY = evt.clientY - cacheSoloPointer.y;
  30476. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30477. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30478. }
  30479. cacheSoloPointer.x = evt.clientX;
  30480. cacheSoloPointer.y = evt.clientY;
  30481. }
  30482. else if (pointA && pointB) {
  30483. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30484. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30485. ed.x = evt.clientX;
  30486. ed.y = evt.clientY;
  30487. var direction = _this.pinchInwards ? 1 : -1;
  30488. var distX = pointA.x - pointB.x;
  30489. var distY = pointA.y - pointB.y;
  30490. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30491. if (previousPinchDistance === 0) {
  30492. previousPinchDistance = pinchSquaredDistance;
  30493. return;
  30494. }
  30495. if (pinchSquaredDistance !== previousPinchDistance) {
  30496. _this.camera
  30497. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30498. (_this.pinchPrecision *
  30499. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30500. direction);
  30501. previousPinchDistance = pinchSquaredDistance;
  30502. }
  30503. }
  30504. }
  30505. };
  30506. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30507. this._onContextMenu = function (evt) {
  30508. evt.preventDefault();
  30509. };
  30510. if (!this.camera._useCtrlForPanning) {
  30511. element.addEventListener("contextmenu", this._onContextMenu, false);
  30512. }
  30513. this._onLostFocus = function () {
  30514. //this._keys = [];
  30515. pointA = pointB = undefined;
  30516. previousPinchDistance = 0;
  30517. cacheSoloPointer = null;
  30518. };
  30519. this._onMouseMove = function (evt) {
  30520. if (!engine.isPointerLock) {
  30521. return;
  30522. }
  30523. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30524. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30525. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30526. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30527. if (!noPreventDefault) {
  30528. evt.preventDefault();
  30529. }
  30530. };
  30531. this._onGestureStart = function (e) {
  30532. if (window.MSGesture === undefined) {
  30533. return;
  30534. }
  30535. if (!_this._MSGestureHandler) {
  30536. _this._MSGestureHandler = new MSGesture();
  30537. _this._MSGestureHandler.target = element;
  30538. }
  30539. _this._MSGestureHandler.addPointer(e.pointerId);
  30540. };
  30541. this._onGesture = function (e) {
  30542. _this.camera.radius *= e.scale;
  30543. if (e.preventDefault) {
  30544. if (!noPreventDefault) {
  30545. e.stopPropagation();
  30546. e.preventDefault();
  30547. }
  30548. }
  30549. };
  30550. element.addEventListener("mousemove", this._onMouseMove, false);
  30551. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30552. element.addEventListener("MSGestureChange", this._onGesture, false);
  30553. BABYLON.Tools.RegisterTopRootEvents([
  30554. { name: "blur", handler: this._onLostFocus }
  30555. ]);
  30556. };
  30557. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30558. if (element && this._observer) {
  30559. this.camera.getScene().onPointerObservable.remove(this._observer);
  30560. this._observer = null;
  30561. element.removeEventListener("contextmenu", this._onContextMenu);
  30562. element.removeEventListener("mousemove", this._onMouseMove);
  30563. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30564. element.removeEventListener("MSGestureChange", this._onGesture);
  30565. this._isPanClick = false;
  30566. this.pinchInwards = true;
  30567. this._onMouseMove = null;
  30568. this._onGestureStart = null;
  30569. this._onGesture = null;
  30570. this._MSGestureHandler = null;
  30571. this._onLostFocus = null;
  30572. this._onContextMenu = null;
  30573. }
  30574. BABYLON.Tools.UnregisterTopRootEvents([
  30575. { name: "blur", handler: this._onLostFocus }
  30576. ]);
  30577. };
  30578. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30579. return "ArcRotateCameraPointersInput";
  30580. };
  30581. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30582. return "pointers";
  30583. };
  30584. return ArcRotateCameraPointersInput;
  30585. }());
  30586. __decorate([
  30587. BABYLON.serialize()
  30588. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30598. __decorate([
  30599. BABYLON.serialize()
  30600. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30601. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30602. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30603. })(BABYLON || (BABYLON = {}));
  30604. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30605. /// <reference path="babylon.targetCamera.ts" />
  30606. /// <reference path="..\Tools\babylon.tools.ts" />
  30607. var BABYLON;
  30608. (function (BABYLON) {
  30609. var ArcRotateCamera = (function (_super) {
  30610. __extends(ArcRotateCamera, _super);
  30611. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30612. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30613. _this.inertialAlphaOffset = 0;
  30614. _this.inertialBetaOffset = 0;
  30615. _this.inertialRadiusOffset = 0;
  30616. _this.lowerAlphaLimit = null;
  30617. _this.upperAlphaLimit = null;
  30618. _this.lowerBetaLimit = 0.01;
  30619. _this.upperBetaLimit = Math.PI;
  30620. _this.lowerRadiusLimit = null;
  30621. _this.upperRadiusLimit = null;
  30622. _this.inertialPanningX = 0;
  30623. _this.inertialPanningY = 0;
  30624. _this.panningInertia = 0.9;
  30625. //-- end properties for backward compatibility for inputs
  30626. _this.zoomOnFactor = 1;
  30627. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30628. _this.allowUpsideDown = true;
  30629. _this._viewMatrix = new BABYLON.Matrix();
  30630. // Panning
  30631. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30632. _this.checkCollisions = false;
  30633. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30634. _this._previousPosition = BABYLON.Vector3.Zero();
  30635. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30636. _this._newPosition = BABYLON.Vector3.Zero();
  30637. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30638. if (collidedMesh === void 0) { collidedMesh = null; }
  30639. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30640. newPosition.multiplyInPlace(_this._collider.radius);
  30641. }
  30642. if (!collidedMesh) {
  30643. _this._previousPosition.copyFrom(_this.position);
  30644. }
  30645. else {
  30646. _this.setPosition(newPosition);
  30647. if (_this.onCollide) {
  30648. _this.onCollide(collidedMesh);
  30649. }
  30650. }
  30651. // Recompute because of constraints
  30652. var cosa = Math.cos(_this.alpha);
  30653. var sina = Math.sin(_this.alpha);
  30654. var cosb = Math.cos(_this.beta);
  30655. var sinb = Math.sin(_this.beta);
  30656. if (sinb === 0) {
  30657. sinb = 0.0001;
  30658. }
  30659. var target = _this._getTargetPosition();
  30660. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30661. _this.position.copyFrom(_this._newPosition);
  30662. var up = _this.upVector;
  30663. if (_this.allowUpsideDown && _this.beta < 0) {
  30664. up = up.clone();
  30665. up = up.negate();
  30666. }
  30667. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30668. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30669. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30670. _this._collisionTriggered = false;
  30671. };
  30672. _this._target = BABYLON.Vector3.Zero();
  30673. if (target) {
  30674. _this.setTarget(target);
  30675. }
  30676. _this.alpha = alpha;
  30677. _this.beta = beta;
  30678. _this.radius = radius;
  30679. _this.getViewMatrix();
  30680. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30681. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30682. return _this;
  30683. }
  30684. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30685. get: function () {
  30686. return this._target;
  30687. },
  30688. set: function (value) {
  30689. this.setTarget(value);
  30690. },
  30691. enumerable: true,
  30692. configurable: true
  30693. });
  30694. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30695. //-- begin properties for backward compatibility for inputs
  30696. get: function () {
  30697. var pointers = this.inputs.attached["pointers"];
  30698. if (pointers)
  30699. return pointers.angularSensibilityX;
  30700. },
  30701. set: function (value) {
  30702. var pointers = this.inputs.attached["pointers"];
  30703. if (pointers) {
  30704. pointers.angularSensibilityX = value;
  30705. }
  30706. },
  30707. enumerable: true,
  30708. configurable: true
  30709. });
  30710. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30711. get: function () {
  30712. var pointers = this.inputs.attached["pointers"];
  30713. if (pointers)
  30714. return pointers.angularSensibilityY;
  30715. },
  30716. set: function (value) {
  30717. var pointers = this.inputs.attached["pointers"];
  30718. if (pointers) {
  30719. pointers.angularSensibilityY = value;
  30720. }
  30721. },
  30722. enumerable: true,
  30723. configurable: true
  30724. });
  30725. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30726. get: function () {
  30727. var pointers = this.inputs.attached["pointers"];
  30728. if (pointers)
  30729. return pointers.pinchPrecision;
  30730. },
  30731. set: function (value) {
  30732. var pointers = this.inputs.attached["pointers"];
  30733. if (pointers) {
  30734. pointers.pinchPrecision = value;
  30735. }
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30741. get: function () {
  30742. var pointers = this.inputs.attached["pointers"];
  30743. if (pointers)
  30744. return pointers.panningSensibility;
  30745. },
  30746. set: function (value) {
  30747. var pointers = this.inputs.attached["pointers"];
  30748. if (pointers) {
  30749. pointers.panningSensibility = value;
  30750. }
  30751. },
  30752. enumerable: true,
  30753. configurable: true
  30754. });
  30755. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30756. get: function () {
  30757. var keyboard = this.inputs.attached["keyboard"];
  30758. if (keyboard)
  30759. return keyboard.keysUp;
  30760. },
  30761. set: function (value) {
  30762. var keyboard = this.inputs.attached["keyboard"];
  30763. if (keyboard)
  30764. keyboard.keysUp = value;
  30765. },
  30766. enumerable: true,
  30767. configurable: true
  30768. });
  30769. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30770. get: function () {
  30771. var keyboard = this.inputs.attached["keyboard"];
  30772. if (keyboard)
  30773. return keyboard.keysDown;
  30774. },
  30775. set: function (value) {
  30776. var keyboard = this.inputs.attached["keyboard"];
  30777. if (keyboard)
  30778. keyboard.keysDown = value;
  30779. },
  30780. enumerable: true,
  30781. configurable: true
  30782. });
  30783. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30784. get: function () {
  30785. var keyboard = this.inputs.attached["keyboard"];
  30786. if (keyboard)
  30787. return keyboard.keysLeft;
  30788. },
  30789. set: function (value) {
  30790. var keyboard = this.inputs.attached["keyboard"];
  30791. if (keyboard)
  30792. keyboard.keysLeft = value;
  30793. },
  30794. enumerable: true,
  30795. configurable: true
  30796. });
  30797. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30798. get: function () {
  30799. var keyboard = this.inputs.attached["keyboard"];
  30800. if (keyboard)
  30801. return keyboard.keysRight;
  30802. },
  30803. set: function (value) {
  30804. var keyboard = this.inputs.attached["keyboard"];
  30805. if (keyboard)
  30806. keyboard.keysRight = value;
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30812. get: function () {
  30813. var mousewheel = this.inputs.attached["mousewheel"];
  30814. if (mousewheel)
  30815. return mousewheel.wheelPrecision;
  30816. },
  30817. set: function (value) {
  30818. var mousewheel = this.inputs.attached["mousewheel"];
  30819. if (mousewheel)
  30820. mousewheel.wheelPrecision = value;
  30821. },
  30822. enumerable: true,
  30823. configurable: true
  30824. });
  30825. // Cache
  30826. ArcRotateCamera.prototype._initCache = function () {
  30827. _super.prototype._initCache.call(this);
  30828. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30829. this._cache.alpha = undefined;
  30830. this._cache.beta = undefined;
  30831. this._cache.radius = undefined;
  30832. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30833. };
  30834. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30835. if (!ignoreParentClass) {
  30836. _super.prototype._updateCache.call(this);
  30837. }
  30838. this._cache._target.copyFrom(this._getTargetPosition());
  30839. this._cache.alpha = this.alpha;
  30840. this._cache.beta = this.beta;
  30841. this._cache.radius = this.radius;
  30842. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30843. };
  30844. ArcRotateCamera.prototype._getTargetPosition = function () {
  30845. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30846. var pos = this._targetHost.getAbsolutePosition();
  30847. if (this._targetBoundingCenter) {
  30848. pos.addToRef(this._targetBoundingCenter, this._target);
  30849. }
  30850. else {
  30851. this._target.copyFrom(pos);
  30852. }
  30853. }
  30854. var lockedTargetPosition = this._getLockedTargetPosition();
  30855. if (lockedTargetPosition) {
  30856. return lockedTargetPosition;
  30857. }
  30858. return this._target;
  30859. };
  30860. // Synchronized
  30861. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30862. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30863. return false;
  30864. return this._cache._target.equals(this._getTargetPosition())
  30865. && this._cache.alpha === this.alpha
  30866. && this._cache.beta === this.beta
  30867. && this._cache.radius === this.radius
  30868. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30869. };
  30870. // Methods
  30871. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30872. var _this = this;
  30873. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30874. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30875. this._useCtrlForPanning = useCtrlForPanning;
  30876. this._panningMouseButton = panningMouseButton;
  30877. this.inputs.attachElement(element, noPreventDefault);
  30878. this._reset = function () {
  30879. _this.inertialAlphaOffset = 0;
  30880. _this.inertialBetaOffset = 0;
  30881. _this.inertialRadiusOffset = 0;
  30882. };
  30883. };
  30884. ArcRotateCamera.prototype.detachControl = function (element) {
  30885. this.inputs.detachElement(element);
  30886. if (this._reset) {
  30887. this._reset();
  30888. }
  30889. };
  30890. ArcRotateCamera.prototype._checkInputs = function () {
  30891. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30892. if (this._collisionTriggered) {
  30893. return;
  30894. }
  30895. this.inputs.checkInputs();
  30896. // Inertia
  30897. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30898. if (this.getScene().useRightHandedSystem) {
  30899. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30900. }
  30901. else {
  30902. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30903. }
  30904. this.beta += this.inertialBetaOffset;
  30905. this.radius -= this.inertialRadiusOffset;
  30906. this.inertialAlphaOffset *= this.inertia;
  30907. this.inertialBetaOffset *= this.inertia;
  30908. this.inertialRadiusOffset *= this.inertia;
  30909. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30910. this.inertialAlphaOffset = 0;
  30911. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30912. this.inertialBetaOffset = 0;
  30913. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30914. this.inertialRadiusOffset = 0;
  30915. }
  30916. // Panning inertia
  30917. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30918. if (!this._localDirection) {
  30919. this._localDirection = BABYLON.Vector3.Zero();
  30920. this._transformedDirection = BABYLON.Vector3.Zero();
  30921. }
  30922. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30923. this._localDirection.multiplyInPlace(this.panningAxis);
  30924. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30925. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30926. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30927. if (!this.panningAxis.y) {
  30928. this._transformedDirection.y = 0;
  30929. }
  30930. if (!this._targetHost) {
  30931. this._target.addInPlace(this._transformedDirection);
  30932. }
  30933. this.inertialPanningX *= this.panningInertia;
  30934. this.inertialPanningY *= this.panningInertia;
  30935. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30936. this.inertialPanningX = 0;
  30937. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30938. this.inertialPanningY = 0;
  30939. }
  30940. // Limits
  30941. this._checkLimits();
  30942. _super.prototype._checkInputs.call(this);
  30943. };
  30944. ArcRotateCamera.prototype._checkLimits = function () {
  30945. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30946. if (this.allowUpsideDown && this.beta > Math.PI) {
  30947. this.beta = this.beta - (2 * Math.PI);
  30948. }
  30949. }
  30950. else {
  30951. if (this.beta < this.lowerBetaLimit) {
  30952. this.beta = this.lowerBetaLimit;
  30953. }
  30954. }
  30955. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30956. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30957. this.beta = this.beta + (2 * Math.PI);
  30958. }
  30959. }
  30960. else {
  30961. if (this.beta > this.upperBetaLimit) {
  30962. this.beta = this.upperBetaLimit;
  30963. }
  30964. }
  30965. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30966. this.alpha = this.lowerAlphaLimit;
  30967. }
  30968. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30969. this.alpha = this.upperAlphaLimit;
  30970. }
  30971. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30972. this.radius = this.lowerRadiusLimit;
  30973. }
  30974. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30975. this.radius = this.upperRadiusLimit;
  30976. }
  30977. };
  30978. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30979. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30980. this.radius = radiusv3.length();
  30981. // Alpha
  30982. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30983. if (radiusv3.z < 0) {
  30984. this.alpha = 2 * Math.PI - this.alpha;
  30985. }
  30986. // Beta
  30987. this.beta = Math.acos(radiusv3.y / this.radius);
  30988. this._checkLimits();
  30989. };
  30990. ArcRotateCamera.prototype.setPosition = function (position) {
  30991. if (this.position.equals(position)) {
  30992. return;
  30993. }
  30994. this.position.copyFrom(position);
  30995. this.rebuildAnglesAndRadius();
  30996. };
  30997. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30998. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30999. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31000. if (target.getBoundingInfo) {
  31001. if (toBoundingCenter) {
  31002. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31003. }
  31004. else {
  31005. this._targetBoundingCenter = null;
  31006. }
  31007. this._targetHost = target;
  31008. this._target = this._getTargetPosition();
  31009. }
  31010. else {
  31011. var newTarget = target;
  31012. var currentTarget = this._getTargetPosition();
  31013. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31014. return;
  31015. }
  31016. this._target = newTarget;
  31017. this._targetBoundingCenter = null;
  31018. }
  31019. this.rebuildAnglesAndRadius();
  31020. };
  31021. ArcRotateCamera.prototype._getViewMatrix = function () {
  31022. // Compute
  31023. var cosa = Math.cos(this.alpha);
  31024. var sina = Math.sin(this.alpha);
  31025. var cosb = Math.cos(this.beta);
  31026. var sinb = Math.sin(this.beta);
  31027. if (sinb === 0) {
  31028. sinb = 0.0001;
  31029. }
  31030. var target = this._getTargetPosition();
  31031. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31032. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31033. if (!this._collider) {
  31034. this._collider = new BABYLON.Collider();
  31035. }
  31036. this._collider.radius = this.collisionRadius;
  31037. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31038. this._collisionTriggered = true;
  31039. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31040. }
  31041. else {
  31042. this.position.copyFrom(this._newPosition);
  31043. var up = this.upVector;
  31044. if (this.allowUpsideDown && sinb < 0) {
  31045. up = up.clone();
  31046. up = up.negate();
  31047. }
  31048. if (this.getScene().useRightHandedSystem) {
  31049. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31050. }
  31051. else {
  31052. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31053. }
  31054. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31055. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31056. }
  31057. this._currentTarget = target;
  31058. return this._viewMatrix;
  31059. };
  31060. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31061. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31062. meshes = meshes || this.getScene().meshes;
  31063. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31064. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31065. this.radius = distance * this.zoomOnFactor;
  31066. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31067. };
  31068. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31069. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31070. var meshesOrMinMaxVector;
  31071. var distance;
  31072. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31073. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31074. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31075. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31076. }
  31077. else {
  31078. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31079. distance = meshesOrMinMaxVectorAndDistance.distance;
  31080. }
  31081. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31082. if (!doNotUpdateMaxZ) {
  31083. this.maxZ = distance * 2;
  31084. }
  31085. };
  31086. /**
  31087. * @override
  31088. * Override Camera.createRigCamera
  31089. */
  31090. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31091. var alphaShift;
  31092. switch (this.cameraRigMode) {
  31093. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31094. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31095. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31096. case BABYLON.Camera.RIG_MODE_VR:
  31097. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31098. break;
  31099. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31100. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31101. break;
  31102. }
  31103. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31104. rigCam._cameraRigParams = {};
  31105. return rigCam;
  31106. };
  31107. /**
  31108. * @override
  31109. * Override Camera._updateRigCameras
  31110. */
  31111. ArcRotateCamera.prototype._updateRigCameras = function () {
  31112. var camLeft = this._rigCameras[0];
  31113. var camRight = this._rigCameras[1];
  31114. camLeft.beta = camRight.beta = this.beta;
  31115. camLeft.radius = camRight.radius = this.radius;
  31116. switch (this.cameraRigMode) {
  31117. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31118. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31119. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31120. case BABYLON.Camera.RIG_MODE_VR:
  31121. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31122. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31123. break;
  31124. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31125. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31126. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31127. break;
  31128. }
  31129. _super.prototype._updateRigCameras.call(this);
  31130. };
  31131. ArcRotateCamera.prototype.dispose = function () {
  31132. this.inputs.clear();
  31133. _super.prototype.dispose.call(this);
  31134. };
  31135. ArcRotateCamera.prototype.getClassName = function () {
  31136. return "ArcRotateCamera";
  31137. };
  31138. return ArcRotateCamera;
  31139. }(BABYLON.TargetCamera));
  31140. __decorate([
  31141. BABYLON.serialize()
  31142. ], ArcRotateCamera.prototype, "alpha", void 0);
  31143. __decorate([
  31144. BABYLON.serialize()
  31145. ], ArcRotateCamera.prototype, "beta", void 0);
  31146. __decorate([
  31147. BABYLON.serialize()
  31148. ], ArcRotateCamera.prototype, "radius", void 0);
  31149. __decorate([
  31150. BABYLON.serializeAsVector3("target")
  31151. ], ArcRotateCamera.prototype, "_target", void 0);
  31152. __decorate([
  31153. BABYLON.serialize()
  31154. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31155. __decorate([
  31156. BABYLON.serialize()
  31157. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31158. __decorate([
  31159. BABYLON.serialize()
  31160. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31161. __decorate([
  31162. BABYLON.serialize()
  31163. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31164. __decorate([
  31165. BABYLON.serialize()
  31166. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31167. __decorate([
  31168. BABYLON.serialize()
  31169. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31170. __decorate([
  31171. BABYLON.serialize()
  31172. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31173. __decorate([
  31174. BABYLON.serialize()
  31175. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31176. __decorate([
  31177. BABYLON.serialize()
  31178. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31179. __decorate([
  31180. BABYLON.serialize()
  31181. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31182. __decorate([
  31183. BABYLON.serialize()
  31184. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31185. __decorate([
  31186. BABYLON.serialize()
  31187. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  31188. __decorate([
  31189. BABYLON.serialize()
  31190. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31191. __decorate([
  31192. BABYLON.serialize()
  31193. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31194. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31195. })(BABYLON || (BABYLON = {}));
  31196. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31197. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31198. var BABYLON;
  31199. (function (BABYLON) {
  31200. var ArcRotateCameraInputsManager = (function (_super) {
  31201. __extends(ArcRotateCameraInputsManager, _super);
  31202. function ArcRotateCameraInputsManager(camera) {
  31203. return _super.call(this, camera) || this;
  31204. }
  31205. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31206. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31207. return this;
  31208. };
  31209. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31210. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31211. return this;
  31212. };
  31213. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31214. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31215. return this;
  31216. };
  31217. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31218. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31219. return this;
  31220. };
  31221. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31222. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31223. return this;
  31224. };
  31225. return ArcRotateCameraInputsManager;
  31226. }(BABYLON.CameraInputsManager));
  31227. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31228. })(BABYLON || (BABYLON = {}));
  31229. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31230. var BABYLON;
  31231. (function (BABYLON) {
  31232. var CubeTexture = (function (_super) {
  31233. __extends(CubeTexture, _super);
  31234. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered) {
  31235. if (onLoad === void 0) { onLoad = null; }
  31236. if (onError === void 0) { onError = null; }
  31237. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31238. if (prefiltered === void 0) { prefiltered = false; }
  31239. var _this = _super.call(this, scene) || this;
  31240. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  31241. _this.name = rootUrl;
  31242. _this.url = rootUrl;
  31243. _this._noMipmap = noMipmap;
  31244. _this.hasAlpha = false;
  31245. _this._format = format;
  31246. _this._prefiltered = prefiltered;
  31247. if (!rootUrl && !files) {
  31248. return _this;
  31249. }
  31250. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  31251. if (!files) {
  31252. if (!extensions) {
  31253. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  31254. }
  31255. files = [];
  31256. for (var index = 0; index < extensions.length; index++) {
  31257. files.push(rootUrl + extensions[index]);
  31258. }
  31259. _this._extensions = extensions;
  31260. }
  31261. _this._files = files;
  31262. if (!_this._texture) {
  31263. if (!scene.useDelayedTextureLoading) {
  31264. if (prefiltered) {
  31265. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format);
  31266. }
  31267. else {
  31268. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  31269. }
  31270. }
  31271. else {
  31272. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31273. }
  31274. }
  31275. else if (onLoad) {
  31276. if (_this._texture.isReady) {
  31277. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  31278. }
  31279. else {
  31280. _this._texture.onLoadedCallbacks.push(onLoad);
  31281. }
  31282. }
  31283. _this.isCube = true;
  31284. _this._textureMatrix = BABYLON.Matrix.Identity();
  31285. if (prefiltered) {
  31286. _this.gammaSpace = false;
  31287. }
  31288. return _this;
  31289. }
  31290. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  31291. return new CubeTexture("", scene, null, noMipmap, files);
  31292. };
  31293. CubeTexture.CreateFromPrefilteredData = function (url, scene) {
  31294. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true);
  31295. };
  31296. // Methods
  31297. CubeTexture.prototype.delayLoad = function () {
  31298. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31299. return;
  31300. }
  31301. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31302. this._texture = this._getFromCache(this.url, this._noMipmap);
  31303. if (!this._texture) {
  31304. if (this._prefiltered) {
  31305. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  31306. }
  31307. else {
  31308. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  31309. }
  31310. }
  31311. };
  31312. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  31313. return this._textureMatrix;
  31314. };
  31315. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  31316. this._textureMatrix = value;
  31317. };
  31318. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31319. var texture = BABYLON.SerializationHelper.Parse(function () {
  31320. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  31321. }, parsedTexture, scene);
  31322. // Animations
  31323. if (parsedTexture.animations) {
  31324. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31325. var parsedAnimation = parsedTexture.animations[animationIndex];
  31326. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31327. }
  31328. }
  31329. return texture;
  31330. };
  31331. CubeTexture.prototype.clone = function () {
  31332. var _this = this;
  31333. return BABYLON.SerializationHelper.Clone(function () {
  31334. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  31335. }, this);
  31336. };
  31337. return CubeTexture;
  31338. }(BABYLON.BaseTexture));
  31339. BABYLON.CubeTexture = CubeTexture;
  31340. })(BABYLON || (BABYLON = {}));
  31341. //# sourceMappingURL=babylon.cubeTexture.js.map
  31342. var BABYLON;
  31343. (function (BABYLON) {
  31344. var RenderTargetTexture = (function (_super) {
  31345. __extends(RenderTargetTexture, _super);
  31346. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  31347. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  31348. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31349. if (isCube === void 0) { isCube = false; }
  31350. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31351. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31352. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  31353. if (isMulti === void 0) { isMulti = false; }
  31354. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  31355. _this.isCube = isCube;
  31356. /**
  31357. * Use this list to define the list of mesh you want to render.
  31358. */
  31359. _this.renderList = new Array();
  31360. _this.renderParticles = true;
  31361. _this.renderSprites = false;
  31362. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  31363. // Events
  31364. /**
  31365. * An event triggered when the texture is unbind.
  31366. * @type {BABYLON.Observable}
  31367. */
  31368. _this.onAfterUnbindObservable = new BABYLON.Observable();
  31369. /**
  31370. * An event triggered before rendering the texture
  31371. * @type {BABYLON.Observable}
  31372. */
  31373. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31374. /**
  31375. * An event triggered after rendering the texture
  31376. * @type {BABYLON.Observable}
  31377. */
  31378. _this.onAfterRenderObservable = new BABYLON.Observable();
  31379. /**
  31380. * An event triggered after the texture clear
  31381. * @type {BABYLON.Observable}
  31382. */
  31383. _this.onClearObservable = new BABYLON.Observable();
  31384. _this._currentRefreshId = -1;
  31385. _this._refreshRate = 1;
  31386. _this._samples = 1;
  31387. scene = _this.getScene();
  31388. _this.name = name;
  31389. _this.isRenderTarget = true;
  31390. _this._size = size;
  31391. _this._generateMipMaps = generateMipMaps;
  31392. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  31393. // Rendering groups
  31394. _this._renderingManager = new BABYLON.RenderingManager(scene);
  31395. if (isMulti) {
  31396. return _this;
  31397. }
  31398. _this._renderTargetOptions = {
  31399. generateMipMaps: generateMipMaps,
  31400. type: type,
  31401. samplingMode: samplingMode,
  31402. generateDepthBuffer: generateDepthBuffer,
  31403. generateStencilBuffer: generateStencilBuffer
  31404. };
  31405. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31406. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31407. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31408. }
  31409. if (isCube) {
  31410. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  31411. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  31412. _this._textureMatrix = BABYLON.Matrix.Identity();
  31413. }
  31414. else {
  31415. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  31416. }
  31417. return _this;
  31418. }
  31419. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  31420. get: function () {
  31421. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  31422. },
  31423. enumerable: true,
  31424. configurable: true
  31425. });
  31426. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  31427. get: function () {
  31428. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  31429. },
  31430. enumerable: true,
  31431. configurable: true
  31432. });
  31433. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  31434. get: function () {
  31435. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  31436. },
  31437. enumerable: true,
  31438. configurable: true
  31439. });
  31440. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  31441. set: function (callback) {
  31442. if (this._onAfterUnbindObserver) {
  31443. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  31444. }
  31445. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  31446. },
  31447. enumerable: true,
  31448. configurable: true
  31449. });
  31450. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  31451. set: function (callback) {
  31452. if (this._onBeforeRenderObserver) {
  31453. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31454. }
  31455. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31456. },
  31457. enumerable: true,
  31458. configurable: true
  31459. });
  31460. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  31461. set: function (callback) {
  31462. if (this._onAfterRenderObserver) {
  31463. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31464. }
  31465. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31466. },
  31467. enumerable: true,
  31468. configurable: true
  31469. });
  31470. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31471. set: function (callback) {
  31472. if (this._onClearObserver) {
  31473. this.onClearObservable.remove(this._onClearObserver);
  31474. }
  31475. this._onClearObserver = this.onClearObservable.add(callback);
  31476. },
  31477. enumerable: true,
  31478. configurable: true
  31479. });
  31480. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31481. get: function () {
  31482. return this._renderTargetOptions;
  31483. },
  31484. enumerable: true,
  31485. configurable: true
  31486. });
  31487. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31488. get: function () {
  31489. return this._samples;
  31490. },
  31491. set: function (value) {
  31492. if (this._samples === value) {
  31493. return;
  31494. }
  31495. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31496. },
  31497. enumerable: true,
  31498. configurable: true
  31499. });
  31500. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31501. this._currentRefreshId = -1;
  31502. };
  31503. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31504. get: function () {
  31505. return this._refreshRate;
  31506. },
  31507. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31508. set: function (value) {
  31509. this._refreshRate = value;
  31510. this.resetRefreshCounter();
  31511. },
  31512. enumerable: true,
  31513. configurable: true
  31514. });
  31515. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31516. if (!this._postProcessManager) {
  31517. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31518. this._postProcesses = new Array();
  31519. }
  31520. this._postProcesses.push(postProcess);
  31521. this._postProcesses[0].autoClear = false;
  31522. };
  31523. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31524. if (!this._postProcesses) {
  31525. return;
  31526. }
  31527. if (dispose) {
  31528. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31529. var postProcess = _a[_i];
  31530. postProcess.dispose();
  31531. postProcess = null;
  31532. }
  31533. }
  31534. this._postProcesses = [];
  31535. };
  31536. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31537. if (!this._postProcesses) {
  31538. return;
  31539. }
  31540. var index = this._postProcesses.indexOf(postProcess);
  31541. if (index === -1) {
  31542. return;
  31543. }
  31544. this._postProcesses.splice(index, 1);
  31545. if (this._postProcesses.length > 0) {
  31546. this._postProcesses[0].autoClear = false;
  31547. }
  31548. };
  31549. RenderTargetTexture.prototype._shouldRender = function () {
  31550. if (this._currentRefreshId === -1) {
  31551. this._currentRefreshId = 1;
  31552. return true;
  31553. }
  31554. if (this.refreshRate === this._currentRefreshId) {
  31555. this._currentRefreshId = 1;
  31556. return true;
  31557. }
  31558. this._currentRefreshId++;
  31559. return false;
  31560. };
  31561. RenderTargetTexture.prototype.isReady = function () {
  31562. if (!this.getScene().renderTargetsEnabled) {
  31563. return false;
  31564. }
  31565. return _super.prototype.isReady.call(this);
  31566. };
  31567. RenderTargetTexture.prototype.getRenderSize = function () {
  31568. return this._size;
  31569. };
  31570. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31571. get: function () {
  31572. return true;
  31573. },
  31574. enumerable: true,
  31575. configurable: true
  31576. });
  31577. RenderTargetTexture.prototype.scale = function (ratio) {
  31578. var newSize = this._size * ratio;
  31579. this.resize(newSize);
  31580. };
  31581. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31582. if (this.isCube) {
  31583. return this._textureMatrix;
  31584. }
  31585. return _super.prototype.getReflectionTextureMatrix.call(this);
  31586. };
  31587. RenderTargetTexture.prototype.resize = function (size) {
  31588. this.releaseInternalTexture();
  31589. if (this.isCube) {
  31590. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31591. }
  31592. else {
  31593. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31594. }
  31595. };
  31596. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31597. var scene = this.getScene();
  31598. var engine = scene.getEngine();
  31599. if (this.useCameraPostProcesses !== undefined) {
  31600. useCameraPostProcess = this.useCameraPostProcesses;
  31601. }
  31602. if (this._waitingRenderList) {
  31603. this.renderList = [];
  31604. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31605. var id = this._waitingRenderList[index];
  31606. this.renderList.push(scene.getMeshByID(id));
  31607. }
  31608. delete this._waitingRenderList;
  31609. }
  31610. // Is predicate defined?
  31611. if (this.renderListPredicate) {
  31612. this.renderList.splice(0); // Clear previous renderList
  31613. var sceneMeshes = this.getScene().meshes;
  31614. for (var index = 0; index < sceneMeshes.length; index++) {
  31615. var mesh = sceneMeshes[index];
  31616. if (this.renderListPredicate(mesh)) {
  31617. this.renderList.push(mesh);
  31618. }
  31619. }
  31620. }
  31621. if (this.renderList && this.renderList.length === 0) {
  31622. return;
  31623. }
  31624. // Set custom projection.
  31625. // Needs to be before binding to prevent changing the aspect ratio.
  31626. var camera;
  31627. if (this.activeCamera) {
  31628. camera = this.activeCamera;
  31629. engine.setViewport(this.activeCamera.viewport);
  31630. if (this.activeCamera !== scene.activeCamera) {
  31631. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31632. }
  31633. }
  31634. else {
  31635. camera = scene.activeCamera;
  31636. engine.setViewport(scene.activeCamera.viewport);
  31637. }
  31638. // Prepare renderingManager
  31639. this._renderingManager.reset();
  31640. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31641. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31642. var sceneRenderId = scene.getRenderId();
  31643. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31644. var mesh = currentRenderList[meshIndex];
  31645. if (mesh) {
  31646. if (!mesh.isReady()) {
  31647. // Reset _currentRefreshId
  31648. this.resetRefreshCounter();
  31649. continue;
  31650. }
  31651. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31652. var isMasked = void 0;
  31653. if (!this.renderList) {
  31654. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31655. }
  31656. else {
  31657. isMasked = false;
  31658. }
  31659. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31660. mesh._activate(sceneRenderId);
  31661. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31662. var subMesh = mesh.subMeshes[subIndex];
  31663. scene._activeIndices.addCount(subMesh.indexCount, false);
  31664. this._renderingManager.dispatch(subMesh);
  31665. }
  31666. }
  31667. }
  31668. }
  31669. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31670. var particleSystem = scene.particleSystems[particleIndex];
  31671. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31672. continue;
  31673. }
  31674. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31675. this._renderingManager.dispatchParticles(particleSystem);
  31676. }
  31677. }
  31678. if (this.isCube) {
  31679. for (var face = 0; face < 6; face++) {
  31680. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31681. scene.incrementRenderId();
  31682. scene.resetCachedMaterial();
  31683. }
  31684. }
  31685. else {
  31686. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31687. }
  31688. this.onAfterUnbindObservable.notifyObservers(this);
  31689. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31690. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31691. }
  31692. engine.setViewport(scene.activeCamera.viewport);
  31693. scene.resetCachedMaterial();
  31694. };
  31695. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31696. var _this = this;
  31697. var scene = this.getScene();
  31698. var engine = scene.getEngine();
  31699. // Bind
  31700. if (this._postProcessManager) {
  31701. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31702. }
  31703. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31704. if (this.isCube) {
  31705. engine.bindFramebuffer(this._texture, faceIndex);
  31706. }
  31707. else {
  31708. engine.bindFramebuffer(this._texture);
  31709. }
  31710. }
  31711. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31712. // Clear
  31713. if (this.onClearObservable.hasObservers()) {
  31714. this.onClearObservable.notifyObservers(engine);
  31715. }
  31716. else {
  31717. engine.clear(scene.clearColor, true, true, true);
  31718. }
  31719. if (!this._doNotChangeAspectRatio) {
  31720. scene.updateTransformMatrix(true);
  31721. }
  31722. // Render
  31723. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31724. if (this._postProcessManager) {
  31725. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31726. }
  31727. else if (useCameraPostProcess) {
  31728. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31729. }
  31730. if (!this._doNotChangeAspectRatio) {
  31731. scene.updateTransformMatrix(true);
  31732. }
  31733. // Dump ?
  31734. if (dumpForDebug) {
  31735. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31736. }
  31737. // Unbind
  31738. if (!this.isCube || faceIndex === 5) {
  31739. if (this.isCube) {
  31740. if (faceIndex === 5) {
  31741. engine.generateMipMapsForCubemap(this._texture);
  31742. }
  31743. }
  31744. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31745. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31746. });
  31747. }
  31748. else {
  31749. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31750. }
  31751. };
  31752. /**
  31753. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31754. * This allowed control for front to back rendering or reversly depending of the special needs.
  31755. *
  31756. * @param renderingGroupId The rendering group id corresponding to its index
  31757. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31758. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31759. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31760. */
  31761. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31762. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31763. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31764. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31765. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31766. };
  31767. /**
  31768. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31769. *
  31770. * @param renderingGroupId The rendering group id corresponding to its index
  31771. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31772. */
  31773. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31774. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31775. };
  31776. RenderTargetTexture.prototype.clone = function () {
  31777. var textureSize = this.getSize();
  31778. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  31779. // Base texture
  31780. newTexture.hasAlpha = this.hasAlpha;
  31781. newTexture.level = this.level;
  31782. // RenderTarget Texture
  31783. newTexture.coordinatesMode = this.coordinatesMode;
  31784. newTexture.renderList = this.renderList.slice(0);
  31785. return newTexture;
  31786. };
  31787. RenderTargetTexture.prototype.serialize = function () {
  31788. if (!this.name) {
  31789. return null;
  31790. }
  31791. var serializationObject = _super.prototype.serialize.call(this);
  31792. serializationObject.renderTargetSize = this.getRenderSize();
  31793. serializationObject.renderList = [];
  31794. for (var index = 0; index < this.renderList.length; index++) {
  31795. serializationObject.renderList.push(this.renderList[index].id);
  31796. }
  31797. return serializationObject;
  31798. };
  31799. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  31800. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  31801. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  31802. };
  31803. RenderTargetTexture.prototype.dispose = function () {
  31804. if (this._postProcessManager) {
  31805. this._postProcessManager.dispose();
  31806. this._postProcessManager = null;
  31807. }
  31808. this.clearPostProcesses(true);
  31809. // Remove from custom render targets
  31810. var scene = this.getScene();
  31811. var index = scene.customRenderTargets.indexOf(this);
  31812. if (index >= 0) {
  31813. scene.customRenderTargets.splice(index, 1);
  31814. }
  31815. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  31816. var camera = _a[_i];
  31817. index = camera.customRenderTargets.indexOf(this);
  31818. if (index >= 0) {
  31819. camera.customRenderTargets.splice(index, 1);
  31820. }
  31821. }
  31822. _super.prototype.dispose.call(this);
  31823. };
  31824. return RenderTargetTexture;
  31825. }(BABYLON.Texture));
  31826. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31827. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31828. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31829. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31830. })(BABYLON || (BABYLON = {}));
  31831. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31832. var BABYLON;
  31833. (function (BABYLON) {
  31834. ;
  31835. var MultiRenderTarget = (function (_super) {
  31836. __extends(MultiRenderTarget, _super);
  31837. function MultiRenderTarget(name, size, count, scene, options) {
  31838. var _this = this;
  31839. options = options || {};
  31840. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31841. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31842. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31843. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31844. if (!_this.isSupported) {
  31845. _this.dispose();
  31846. return;
  31847. }
  31848. var types = [];
  31849. var samplingModes = [];
  31850. for (var i = 0; i < count; i++) {
  31851. if (options.types && options.types[i]) {
  31852. types.push(options.types[i]);
  31853. }
  31854. else {
  31855. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31856. }
  31857. if (options.samplingModes && options.samplingModes[i]) {
  31858. samplingModes.push(options.samplingModes[i]);
  31859. }
  31860. else {
  31861. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31862. }
  31863. }
  31864. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31865. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31866. _this._count = count;
  31867. _this._size = size;
  31868. _this._multiRenderTargetOptions = {
  31869. samplingModes: samplingModes,
  31870. generateMipMaps: generateMipMaps,
  31871. generateDepthBuffer: generateDepthBuffer,
  31872. generateStencilBuffer: generateStencilBuffer,
  31873. generateDepthTexture: generateDepthTexture,
  31874. types: types,
  31875. textureCount: count
  31876. };
  31877. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31878. _this._createInternalTextures();
  31879. return _this;
  31880. }
  31881. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31882. get: function () {
  31883. var engine = this.getScene().getEngine();
  31884. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31885. },
  31886. enumerable: true,
  31887. configurable: true
  31888. });
  31889. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31890. get: function () {
  31891. return this._textures;
  31892. },
  31893. enumerable: true,
  31894. configurable: true
  31895. });
  31896. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31897. get: function () {
  31898. return this._textures[this._textures.length - 1];
  31899. },
  31900. enumerable: true,
  31901. configurable: true
  31902. });
  31903. MultiRenderTarget.prototype._createInternalTextures = function () {
  31904. this._textures = [];
  31905. for (var i = 0; i < this._webGLTextures.length; i++) {
  31906. var texture = new BABYLON.Texture(null, this.getScene());
  31907. texture._texture = this._webGLTextures[i];
  31908. this._textures.push(texture);
  31909. }
  31910. // Keeps references to frame buffer and stencil/depth buffer
  31911. this._texture = this._webGLTextures[0];
  31912. };
  31913. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31914. get: function () {
  31915. return this._samples;
  31916. },
  31917. set: function (value) {
  31918. if (this._samples === value) {
  31919. return;
  31920. }
  31921. for (var i = 0; i < this._webGLTextures.length; i++) {
  31922. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31923. }
  31924. },
  31925. enumerable: true,
  31926. configurable: true
  31927. });
  31928. MultiRenderTarget.prototype.resize = function (size) {
  31929. this.releaseInternalTextures();
  31930. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31931. this._createInternalTextures();
  31932. };
  31933. MultiRenderTarget.prototype.dispose = function () {
  31934. this.releaseInternalTextures();
  31935. _super.prototype.dispose.call(this);
  31936. };
  31937. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31938. if (!this._webGLTextures) {
  31939. return;
  31940. }
  31941. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31942. if (this._webGLTextures[i] !== undefined) {
  31943. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31944. this._webGLTextures.splice(i, 1);
  31945. }
  31946. }
  31947. };
  31948. return MultiRenderTarget;
  31949. }(BABYLON.RenderTargetTexture));
  31950. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31951. })(BABYLON || (BABYLON = {}));
  31952. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31953. /// <reference path="babylon.renderTargetTexture.ts" />
  31954. var BABYLON;
  31955. (function (BABYLON) {
  31956. var MirrorTexture = (function (_super) {
  31957. __extends(MirrorTexture, _super);
  31958. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31959. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31960. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31961. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31962. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31963. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31964. _this._transformMatrix = BABYLON.Matrix.Zero();
  31965. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31966. _this._blurKernelX = 0;
  31967. _this._blurKernelY = 0;
  31968. _this._blurRatio = 1.0;
  31969. _this.onBeforeRenderObservable.add(function () {
  31970. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31971. _this._savedViewMatrix = scene.getViewMatrix();
  31972. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31973. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31974. scene.clipPlane = _this.mirrorPlane;
  31975. scene.getEngine().cullBackFaces = false;
  31976. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31977. });
  31978. _this.onAfterRenderObservable.add(function () {
  31979. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31980. scene.getEngine().cullBackFaces = true;
  31981. scene._mirroredCameraPosition = null;
  31982. delete scene.clipPlane;
  31983. });
  31984. return _this;
  31985. }
  31986. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31987. get: function () {
  31988. return this._blurRatio;
  31989. },
  31990. set: function (value) {
  31991. if (this._blurRatio === value) {
  31992. return;
  31993. }
  31994. this._blurRatio = value;
  31995. this._preparePostProcesses();
  31996. },
  31997. enumerable: true,
  31998. configurable: true
  31999. });
  32000. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  32001. set: function (value) {
  32002. this.blurKernelX = value;
  32003. this.blurKernelY = value;
  32004. },
  32005. enumerable: true,
  32006. configurable: true
  32007. });
  32008. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  32009. get: function () {
  32010. return this._blurKernelX;
  32011. },
  32012. set: function (value) {
  32013. if (this._blurKernelX === value) {
  32014. return;
  32015. }
  32016. this._blurKernelX = value;
  32017. this._preparePostProcesses();
  32018. },
  32019. enumerable: true,
  32020. configurable: true
  32021. });
  32022. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  32023. get: function () {
  32024. return this._blurKernelY;
  32025. },
  32026. set: function (value) {
  32027. if (this._blurKernelY === value) {
  32028. return;
  32029. }
  32030. this._blurKernelY = value;
  32031. this._preparePostProcesses();
  32032. },
  32033. enumerable: true,
  32034. configurable: true
  32035. });
  32036. MirrorTexture.prototype._preparePostProcesses = function () {
  32037. this.clearPostProcesses(true);
  32038. if (this._blurKernelX && this._blurKernelY) {
  32039. var engine = this.getScene().getEngine();
  32040. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32041. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  32042. this._blurX.autoClear = false;
  32043. if (this._blurRatio === 1 && this.samples < 2) {
  32044. this._blurX.outputTexture = this._texture;
  32045. }
  32046. else {
  32047. this._blurX.alwaysForcePOT = true;
  32048. }
  32049. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  32050. this._blurY.autoClear = false;
  32051. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  32052. this.addPostProcess(this._blurX);
  32053. this.addPostProcess(this._blurY);
  32054. }
  32055. };
  32056. MirrorTexture.prototype.clone = function () {
  32057. var textureSize = this.getSize();
  32058. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  32059. // Base texture
  32060. newTexture.hasAlpha = this.hasAlpha;
  32061. newTexture.level = this.level;
  32062. // Mirror Texture
  32063. newTexture.mirrorPlane = this.mirrorPlane.clone();
  32064. newTexture.renderList = this.renderList.slice(0);
  32065. return newTexture;
  32066. };
  32067. MirrorTexture.prototype.serialize = function () {
  32068. if (!this.name) {
  32069. return null;
  32070. }
  32071. var serializationObject = _super.prototype.serialize.call(this);
  32072. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  32073. return serializationObject;
  32074. };
  32075. return MirrorTexture;
  32076. }(BABYLON.RenderTargetTexture));
  32077. BABYLON.MirrorTexture = MirrorTexture;
  32078. })(BABYLON || (BABYLON = {}));
  32079. //# sourceMappingURL=babylon.mirrorTexture.js.map
  32080. /// <reference path="babylon.renderTargetTexture.ts" />
  32081. var BABYLON;
  32082. (function (BABYLON) {
  32083. /**
  32084. * Creates a refraction texture used by refraction channel of the standard material.
  32085. * @param name the texture name
  32086. * @param size size of the underlying texture
  32087. * @param scene root scene
  32088. */
  32089. var RefractionTexture = (function (_super) {
  32090. __extends(RefractionTexture, _super);
  32091. function RefractionTexture(name, size, scene, generateMipMaps) {
  32092. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  32093. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  32094. _this.depth = 2.0;
  32095. _this.onBeforeRenderObservable.add(function () {
  32096. scene.clipPlane = _this.refractionPlane;
  32097. });
  32098. _this.onAfterRenderObservable.add(function () {
  32099. delete scene.clipPlane;
  32100. });
  32101. return _this;
  32102. }
  32103. RefractionTexture.prototype.clone = function () {
  32104. var textureSize = this.getSize();
  32105. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  32106. // Base texture
  32107. newTexture.hasAlpha = this.hasAlpha;
  32108. newTexture.level = this.level;
  32109. // Refraction Texture
  32110. newTexture.refractionPlane = this.refractionPlane.clone();
  32111. newTexture.renderList = this.renderList.slice(0);
  32112. newTexture.depth = this.depth;
  32113. return newTexture;
  32114. };
  32115. RefractionTexture.prototype.serialize = function () {
  32116. if (!this.name) {
  32117. return null;
  32118. }
  32119. var serializationObject = _super.prototype.serialize.call(this);
  32120. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  32121. serializationObject.depth = this.depth;
  32122. return serializationObject;
  32123. };
  32124. return RefractionTexture;
  32125. }(BABYLON.RenderTargetTexture));
  32126. BABYLON.RefractionTexture = RefractionTexture;
  32127. })(BABYLON || (BABYLON = {}));
  32128. //# sourceMappingURL=babylon.refractionTexture.js.map
  32129. /// <reference path="babylon.texture.ts" />
  32130. var BABYLON;
  32131. (function (BABYLON) {
  32132. var DynamicTexture = (function (_super) {
  32133. __extends(DynamicTexture, _super);
  32134. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  32135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32136. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32137. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  32138. _this.name = name;
  32139. var engine = _this.getScene().getEngine();
  32140. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32141. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32142. _this._generateMipMaps = generateMipMaps;
  32143. if (options.getContext) {
  32144. _this._canvas = options;
  32145. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  32146. }
  32147. else {
  32148. _this._canvas = document.createElement("canvas");
  32149. if (options.width) {
  32150. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  32151. }
  32152. else {
  32153. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  32154. }
  32155. }
  32156. var textureSize = _this.getSize();
  32157. _this._canvas.width = textureSize.width;
  32158. _this._canvas.height = textureSize.height;
  32159. _this._context = _this._canvas.getContext("2d");
  32160. return _this;
  32161. }
  32162. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  32163. get: function () {
  32164. return true;
  32165. },
  32166. enumerable: true,
  32167. configurable: true
  32168. });
  32169. DynamicTexture.prototype._recreate = function (textureSize) {
  32170. this._canvas.width = textureSize.width;
  32171. this._canvas.height = textureSize.height;
  32172. this.releaseInternalTexture();
  32173. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  32174. };
  32175. DynamicTexture.prototype.scale = function (ratio) {
  32176. var textureSize = this.getSize();
  32177. textureSize.width *= ratio;
  32178. textureSize.height *= ratio;
  32179. this._recreate(textureSize);
  32180. };
  32181. DynamicTexture.prototype.scaleTo = function (width, height) {
  32182. var textureSize = this.getSize();
  32183. textureSize.width = width;
  32184. textureSize.height = height;
  32185. this._recreate(textureSize);
  32186. };
  32187. DynamicTexture.prototype.getContext = function () {
  32188. return this._context;
  32189. };
  32190. DynamicTexture.prototype.clear = function () {
  32191. var size = this.getSize();
  32192. this._context.fillRect(0, 0, size.width, size.height);
  32193. };
  32194. DynamicTexture.prototype.update = function (invertY) {
  32195. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  32196. };
  32197. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  32198. if (update === void 0) { update = true; }
  32199. var size = this.getSize();
  32200. if (clearColor) {
  32201. this._context.fillStyle = clearColor;
  32202. this._context.fillRect(0, 0, size.width, size.height);
  32203. }
  32204. this._context.font = font;
  32205. if (x === null || x === undefined) {
  32206. var textSize = this._context.measureText(text);
  32207. x = (size.width - textSize.width) / 2;
  32208. }
  32209. if (y === null || y === undefined) {
  32210. var fontSize = parseInt((font.replace(/\D/g, '')));
  32211. ;
  32212. y = (size.height / 2) + (fontSize / 3.65);
  32213. }
  32214. this._context.fillStyle = color;
  32215. this._context.fillText(text, x, y);
  32216. if (update) {
  32217. this.update(invertY);
  32218. }
  32219. };
  32220. DynamicTexture.prototype.clone = function () {
  32221. var textureSize = this.getSize();
  32222. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  32223. // Base texture
  32224. newTexture.hasAlpha = this.hasAlpha;
  32225. newTexture.level = this.level;
  32226. // Dynamic Texture
  32227. newTexture.wrapU = this.wrapU;
  32228. newTexture.wrapV = this.wrapV;
  32229. return newTexture;
  32230. };
  32231. return DynamicTexture;
  32232. }(BABYLON.Texture));
  32233. BABYLON.DynamicTexture = DynamicTexture;
  32234. })(BABYLON || (BABYLON = {}));
  32235. //# sourceMappingURL=babylon.dynamicTexture.js.map
  32236. var BABYLON;
  32237. (function (BABYLON) {
  32238. var VideoTexture = (function (_super) {
  32239. __extends(VideoTexture, _super);
  32240. /**
  32241. * Creates a video texture.
  32242. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  32243. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  32244. * @param {BABYLON.Scene} scene is obviously the current scene.
  32245. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  32246. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  32247. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  32248. */
  32249. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  32250. if (generateMipMaps === void 0) { generateMipMaps = false; }
  32251. if (invertY === void 0) { invertY = false; }
  32252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32253. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32254. _this._autoLaunch = true;
  32255. var urls;
  32256. _this.name = name;
  32257. if (urlsOrVideo instanceof HTMLVideoElement) {
  32258. _this.video = urlsOrVideo;
  32259. }
  32260. else {
  32261. urls = urlsOrVideo;
  32262. _this.video = document.createElement("video");
  32263. _this.video.autoplay = false;
  32264. _this.video.loop = true;
  32265. }
  32266. _this._generateMipMaps = generateMipMaps;
  32267. _this._samplingMode = samplingMode;
  32268. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  32269. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32270. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32271. }
  32272. else {
  32273. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32274. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32275. _this._generateMipMaps = false;
  32276. }
  32277. if (urls) {
  32278. _this.video.addEventListener("canplay", function () {
  32279. _this._createTexture();
  32280. });
  32281. urls.forEach(function (url) {
  32282. var source = document.createElement("source");
  32283. source.src = url;
  32284. _this.video.appendChild(source);
  32285. });
  32286. }
  32287. else {
  32288. _this._createTexture();
  32289. }
  32290. _this._lastUpdate = BABYLON.Tools.Now;
  32291. return _this;
  32292. }
  32293. VideoTexture.prototype.__setTextureReady = function () {
  32294. this._texture.isReady = true;
  32295. };
  32296. VideoTexture.prototype._createTexture = function () {
  32297. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  32298. if (this._autoLaunch) {
  32299. this._autoLaunch = false;
  32300. this.video.play();
  32301. }
  32302. this._setTextureReady = this.__setTextureReady.bind(this);
  32303. this.video.addEventListener("playing", this._setTextureReady);
  32304. };
  32305. VideoTexture.prototype.update = function () {
  32306. var now = BABYLON.Tools.Now;
  32307. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  32308. return false;
  32309. }
  32310. this._lastUpdate = now;
  32311. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  32312. return true;
  32313. };
  32314. VideoTexture.prototype.dispose = function () {
  32315. _super.prototype.dispose.call(this);
  32316. this.video.removeEventListener("playing", this._setTextureReady);
  32317. };
  32318. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  32319. var video = document.createElement("video");
  32320. var constraintsDeviceId;
  32321. if (constraints && constraints.deviceId) {
  32322. constraintsDeviceId = {
  32323. exact: constraints.deviceId
  32324. };
  32325. }
  32326. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  32327. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  32328. if (navigator.getUserMedia) {
  32329. navigator.getUserMedia({
  32330. video: {
  32331. deviceId: constraintsDeviceId,
  32332. width: {
  32333. min: (constraints && constraints.minWidth) || 256,
  32334. max: (constraints && constraints.maxWidth) || 640
  32335. },
  32336. height: {
  32337. min: (constraints && constraints.minHeight) || 256,
  32338. max: (constraints && constraints.maxHeight) || 480
  32339. }
  32340. }
  32341. }, function (stream) {
  32342. if (video.mozSrcObject !== undefined) {
  32343. video.mozSrcObject = stream;
  32344. }
  32345. else {
  32346. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  32347. }
  32348. video.play();
  32349. if (onReady) {
  32350. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  32351. }
  32352. }, function (e) {
  32353. BABYLON.Tools.Error(e.name);
  32354. });
  32355. }
  32356. };
  32357. return VideoTexture;
  32358. }(BABYLON.Texture));
  32359. BABYLON.VideoTexture = VideoTexture;
  32360. })(BABYLON || (BABYLON = {}));
  32361. //# sourceMappingURL=babylon.videoTexture.js.map
  32362. var BABYLON;
  32363. (function (BABYLON) {
  32364. var RawTexture = (function (_super) {
  32365. __extends(RawTexture, _super);
  32366. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32367. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32368. if (invertY === void 0) { invertY = false; }
  32369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32370. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32371. _this.format = format;
  32372. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32373. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32374. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32375. return _this;
  32376. }
  32377. RawTexture.prototype.update = function (data) {
  32378. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32379. };
  32380. // Statics
  32381. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32382. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32383. if (invertY === void 0) { invertY = false; }
  32384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32385. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32386. };
  32387. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32388. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32389. if (invertY === void 0) { invertY = false; }
  32390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32391. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32392. };
  32393. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32394. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32395. if (invertY === void 0) { invertY = false; }
  32396. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32397. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32398. };
  32399. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32400. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32401. if (invertY === void 0) { invertY = false; }
  32402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32403. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32404. };
  32405. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32406. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32407. if (invertY === void 0) { invertY = false; }
  32408. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32410. };
  32411. return RawTexture;
  32412. }(BABYLON.Texture));
  32413. BABYLON.RawTexture = RawTexture;
  32414. })(BABYLON || (BABYLON = {}));
  32415. //# sourceMappingURL=babylon.rawTexture.js.map
  32416. var BABYLON;
  32417. (function (BABYLON) {
  32418. var Internals;
  32419. (function (Internals) {
  32420. /*
  32421. * Based on jsTGALoader - Javascript loader for TGA file
  32422. * By Vincent Thibault
  32423. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  32424. */
  32425. var TGATools = (function () {
  32426. function TGATools() {
  32427. }
  32428. TGATools.GetTGAHeader = function (data) {
  32429. var offset = 0;
  32430. var header = {
  32431. id_length: data[offset++],
  32432. colormap_type: data[offset++],
  32433. image_type: data[offset++],
  32434. colormap_index: data[offset++] | data[offset++] << 8,
  32435. colormap_length: data[offset++] | data[offset++] << 8,
  32436. colormap_size: data[offset++],
  32437. origin: [
  32438. data[offset++] | data[offset++] << 8,
  32439. data[offset++] | data[offset++] << 8
  32440. ],
  32441. width: data[offset++] | data[offset++] << 8,
  32442. height: data[offset++] | data[offset++] << 8,
  32443. pixel_size: data[offset++],
  32444. flags: data[offset++]
  32445. };
  32446. return header;
  32447. };
  32448. TGATools.UploadContent = function (gl, data) {
  32449. // Not enough data to contain header ?
  32450. if (data.length < 19) {
  32451. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  32452. return;
  32453. }
  32454. // Read Header
  32455. var offset = 18;
  32456. var header = TGATools.GetTGAHeader(data);
  32457. // Assume it's a valid Targa file.
  32458. if (header.id_length + offset > data.length) {
  32459. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  32460. return;
  32461. }
  32462. // Skip not needed data
  32463. offset += header.id_length;
  32464. var use_rle = false;
  32465. var use_pal = false;
  32466. var use_rgb = false;
  32467. var use_grey = false;
  32468. // Get some informations.
  32469. switch (header.image_type) {
  32470. case TGATools._TYPE_RLE_INDEXED:
  32471. use_rle = true;
  32472. case TGATools._TYPE_INDEXED:
  32473. use_pal = true;
  32474. break;
  32475. case TGATools._TYPE_RLE_RGB:
  32476. use_rle = true;
  32477. case TGATools._TYPE_RGB:
  32478. use_rgb = true;
  32479. break;
  32480. case TGATools._TYPE_RLE_GREY:
  32481. use_rle = true;
  32482. case TGATools._TYPE_GREY:
  32483. use_grey = true;
  32484. break;
  32485. }
  32486. var pixel_data;
  32487. var numAlphaBits = header.flags & 0xf;
  32488. var pixel_size = header.pixel_size >> 3;
  32489. var pixel_total = header.width * header.height * pixel_size;
  32490. // Read palettes
  32491. var palettes;
  32492. if (use_pal) {
  32493. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32494. }
  32495. // Read LRE
  32496. if (use_rle) {
  32497. pixel_data = new Uint8Array(pixel_total);
  32498. var c, count, i;
  32499. var localOffset = 0;
  32500. var pixels = new Uint8Array(pixel_size);
  32501. while (offset < pixel_total && localOffset < pixel_total) {
  32502. c = data[offset++];
  32503. count = (c & 0x7f) + 1;
  32504. // RLE pixels
  32505. if (c & 0x80) {
  32506. // Bind pixel tmp array
  32507. for (i = 0; i < pixel_size; ++i) {
  32508. pixels[i] = data[offset++];
  32509. }
  32510. // Copy pixel array
  32511. for (i = 0; i < count; ++i) {
  32512. pixel_data.set(pixels, localOffset + i * pixel_size);
  32513. }
  32514. localOffset += pixel_size * count;
  32515. }
  32516. else {
  32517. count *= pixel_size;
  32518. for (i = 0; i < count; ++i) {
  32519. pixel_data[localOffset + i] = data[offset++];
  32520. }
  32521. localOffset += count;
  32522. }
  32523. }
  32524. }
  32525. else {
  32526. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32527. }
  32528. // Load to texture
  32529. var x_start, y_start, x_step, y_step, y_end, x_end;
  32530. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32531. default:
  32532. case TGATools._ORIGIN_UL:
  32533. x_start = 0;
  32534. x_step = 1;
  32535. x_end = header.width;
  32536. y_start = 0;
  32537. y_step = 1;
  32538. y_end = header.height;
  32539. break;
  32540. case TGATools._ORIGIN_BL:
  32541. x_start = 0;
  32542. x_step = 1;
  32543. x_end = header.width;
  32544. y_start = header.height - 1;
  32545. y_step = -1;
  32546. y_end = -1;
  32547. break;
  32548. case TGATools._ORIGIN_UR:
  32549. x_start = header.width - 1;
  32550. x_step = -1;
  32551. x_end = -1;
  32552. y_start = 0;
  32553. y_step = 1;
  32554. y_end = header.height;
  32555. break;
  32556. case TGATools._ORIGIN_BR:
  32557. x_start = header.width - 1;
  32558. x_step = -1;
  32559. x_end = -1;
  32560. y_start = header.height - 1;
  32561. y_step = -1;
  32562. y_end = -1;
  32563. break;
  32564. }
  32565. // Load the specify method
  32566. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32567. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32568. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32569. };
  32570. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32571. var image = pixel_data, colormap = palettes;
  32572. var width = header.width, height = header.height;
  32573. var color, i = 0, x, y;
  32574. var imageData = new Uint8Array(width * height * 4);
  32575. for (y = y_start; y !== y_end; y += y_step) {
  32576. for (x = x_start; x !== x_end; x += x_step, i++) {
  32577. color = image[i];
  32578. imageData[(x + width * y) * 4 + 3] = 255;
  32579. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32580. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32581. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32582. }
  32583. }
  32584. return imageData;
  32585. };
  32586. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32587. var image = pixel_data;
  32588. var width = header.width, height = header.height;
  32589. var color, i = 0, x, y;
  32590. var imageData = new Uint8Array(width * height * 4);
  32591. for (y = y_start; y !== y_end; y += y_step) {
  32592. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32593. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32594. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32595. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32596. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32597. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32598. }
  32599. }
  32600. return imageData;
  32601. };
  32602. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32603. var image = pixel_data;
  32604. var width = header.width, height = header.height;
  32605. var i = 0, x, y;
  32606. var imageData = new Uint8Array(width * height * 4);
  32607. for (y = y_start; y !== y_end; y += y_step) {
  32608. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32609. imageData[(x + width * y) * 4 + 3] = 255;
  32610. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32611. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32612. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32613. }
  32614. }
  32615. return imageData;
  32616. };
  32617. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32618. var image = pixel_data;
  32619. var width = header.width, height = header.height;
  32620. var i = 0, x, y;
  32621. var imageData = new Uint8Array(width * height * 4);
  32622. for (y = y_start; y !== y_end; y += y_step) {
  32623. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32624. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32625. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32626. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32627. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32628. }
  32629. }
  32630. return imageData;
  32631. };
  32632. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32633. var image = pixel_data;
  32634. var width = header.width, height = header.height;
  32635. var color, i = 0, x, y;
  32636. var imageData = new Uint8Array(width * height * 4);
  32637. for (y = y_start; y !== y_end; y += y_step) {
  32638. for (x = x_start; x !== x_end; x += x_step, i++) {
  32639. color = image[i];
  32640. imageData[(x + width * y) * 4 + 0] = color;
  32641. imageData[(x + width * y) * 4 + 1] = color;
  32642. imageData[(x + width * y) * 4 + 2] = color;
  32643. imageData[(x + width * y) * 4 + 3] = 255;
  32644. }
  32645. }
  32646. return imageData;
  32647. };
  32648. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32649. var image = pixel_data;
  32650. var width = header.width, height = header.height;
  32651. var i = 0, x, y;
  32652. var imageData = new Uint8Array(width * height * 4);
  32653. for (y = y_start; y !== y_end; y += y_step) {
  32654. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32655. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32656. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32657. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32658. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32659. }
  32660. }
  32661. return imageData;
  32662. };
  32663. return TGATools;
  32664. }());
  32665. TGATools._TYPE_NO_DATA = 0;
  32666. TGATools._TYPE_INDEXED = 1;
  32667. TGATools._TYPE_RGB = 2;
  32668. TGATools._TYPE_GREY = 3;
  32669. TGATools._TYPE_RLE_INDEXED = 9;
  32670. TGATools._TYPE_RLE_RGB = 10;
  32671. TGATools._TYPE_RLE_GREY = 11;
  32672. TGATools._ORIGIN_MASK = 0x30;
  32673. TGATools._ORIGIN_SHIFT = 0x04;
  32674. TGATools._ORIGIN_BL = 0x00;
  32675. TGATools._ORIGIN_BR = 0x01;
  32676. TGATools._ORIGIN_UL = 0x02;
  32677. TGATools._ORIGIN_UR = 0x03;
  32678. Internals.TGATools = TGATools;
  32679. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32680. })(BABYLON || (BABYLON = {}));
  32681. //# sourceMappingURL=babylon.tga.js.map
  32682. var BABYLON;
  32683. (function (BABYLON) {
  32684. var Internals;
  32685. (function (Internals) {
  32686. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32687. // All values and structures referenced from:
  32688. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32689. var DDS_MAGIC = 0x20534444;
  32690. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  32691. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32692. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  32693. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32694. function FourCCToInt32(value) {
  32695. return value.charCodeAt(0) +
  32696. (value.charCodeAt(1) << 8) +
  32697. (value.charCodeAt(2) << 16) +
  32698. (value.charCodeAt(3) << 24);
  32699. }
  32700. function Int32ToFourCC(value) {
  32701. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32702. }
  32703. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32704. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32705. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32706. var FOURCC_DX10 = FourCCToInt32("DX10");
  32707. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  32708. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  32709. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  32710. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  32711. var headerLengthInt = 31; // The header length in 32 bit ints
  32712. // Offsets into the header array
  32713. var off_magic = 0;
  32714. var off_size = 1;
  32715. var off_flags = 2;
  32716. var off_height = 3;
  32717. var off_width = 4;
  32718. var off_mipmapCount = 7;
  32719. var off_pfFlags = 20;
  32720. var off_pfFourCC = 21;
  32721. var off_RGBbpp = 22;
  32722. var off_RMask = 23;
  32723. var off_GMask = 24;
  32724. var off_BMask = 25;
  32725. var off_AMask = 26;
  32726. var off_caps1 = 27;
  32727. var off_caps2 = 28;
  32728. var off_caps3 = 29;
  32729. var off_caps4 = 30;
  32730. var off_dxgiFormat = 32;
  32731. ;
  32732. var DDSTools = (function () {
  32733. function DDSTools() {
  32734. }
  32735. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32736. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32737. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  32738. var mipmapCount = 1;
  32739. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32740. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32741. }
  32742. var fourCC = header[off_pfFourCC];
  32743. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  32744. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32745. switch (fourCC) {
  32746. case FOURCC_D3DFMT_R16G16B16A16F:
  32747. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32748. break;
  32749. case FOURCC_D3DFMT_R32G32B32A32F:
  32750. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32751. break;
  32752. case FOURCC_DX10:
  32753. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  32754. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32755. break;
  32756. }
  32757. }
  32758. return {
  32759. width: header[off_width],
  32760. height: header[off_height],
  32761. mipmapCount: mipmapCount,
  32762. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32763. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32764. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32765. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  32766. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  32767. dxgiFormat: dxgiFormat,
  32768. textureType: textureType
  32769. };
  32770. };
  32771. DDSTools._ToHalfFloat = function (value) {
  32772. if (!DDSTools._FloatView) {
  32773. DDSTools._FloatView = new Float32Array(1);
  32774. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  32775. }
  32776. DDSTools._FloatView[0] = value;
  32777. var x = DDSTools._Int32View[0];
  32778. var bits = (x >> 16) & 0x8000; /* Get the sign */
  32779. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  32780. var e = (x >> 23) & 0xff; /* Using int is faster here */
  32781. /* If zero, or denormal, or exponent underflows too much for a denormal
  32782. * half, return signed zero. */
  32783. if (e < 103) {
  32784. return bits;
  32785. }
  32786. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  32787. if (e > 142) {
  32788. bits |= 0x7c00;
  32789. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  32790. * not Inf, so make sure we set one mantissa bit too. */
  32791. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  32792. return bits;
  32793. }
  32794. /* If exponent underflows but not too much, return a denormal */
  32795. if (e < 113) {
  32796. m |= 0x0800;
  32797. /* Extra rounding may overflow and set mantissa to 0 and exponent
  32798. * to 1, which is OK. */
  32799. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  32800. return bits;
  32801. }
  32802. bits |= ((e - 112) << 10) | (m >> 1);
  32803. bits += m & 1;
  32804. return bits;
  32805. };
  32806. DDSTools._FromHalfFloat = function (value) {
  32807. var s = (value & 0x8000) >> 15;
  32808. var e = (value & 0x7C00) >> 10;
  32809. var f = value & 0x03FF;
  32810. if (e === 0) {
  32811. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  32812. }
  32813. else if (e == 0x1F) {
  32814. return f ? NaN : ((s ? -1 : 1) * Infinity);
  32815. }
  32816. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  32817. };
  32818. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  32819. var destArray = new Float32Array(dataLength);
  32820. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  32821. var index = 0;
  32822. for (var y = 0; y < height; y++) {
  32823. for (var x = 0; x < width; x++) {
  32824. var srcPos = (x + y * width) * 4;
  32825. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  32826. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  32827. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  32828. if (DDSTools.StoreLODInAlphaChannel) {
  32829. destArray[index + 3] = lod;
  32830. }
  32831. else {
  32832. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  32833. }
  32834. index += 4;
  32835. }
  32836. }
  32837. return destArray;
  32838. };
  32839. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  32840. if (DDSTools.StoreLODInAlphaChannel) {
  32841. var destArray = new Uint16Array(dataLength);
  32842. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  32843. var index = 0;
  32844. for (var y = 0; y < height; y++) {
  32845. for (var x = 0; x < width; x++) {
  32846. var srcPos = (x + y * width) * 4;
  32847. destArray[index] = srcData[srcPos];
  32848. destArray[index + 1] = srcData[srcPos + 1];
  32849. destArray[index + 2] = srcData[srcPos + 2];
  32850. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  32851. index += 4;
  32852. }
  32853. }
  32854. return destArray;
  32855. }
  32856. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  32857. };
  32858. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  32859. if (DDSTools.StoreLODInAlphaChannel) {
  32860. var destArray = new Float32Array(dataLength);
  32861. var srcData = new Float32Array(arrayBuffer, dataOffset);
  32862. var index = 0;
  32863. for (var y = 0; y < height; y++) {
  32864. for (var x = 0; x < width; x++) {
  32865. var srcPos = (x + y * width) * 4;
  32866. destArray[index] = srcData[srcPos];
  32867. destArray[index + 1] = srcData[srcPos + 1];
  32868. destArray[index + 2] = srcData[srcPos + 2];
  32869. destArray[index + 3] = lod;
  32870. index += 4;
  32871. }
  32872. }
  32873. return destArray;
  32874. }
  32875. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  32876. };
  32877. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  32878. var destArray = new Uint8Array(dataLength);
  32879. var srcData = new Float32Array(arrayBuffer, dataOffset);
  32880. var index = 0;
  32881. for (var y = 0; y < height; y++) {
  32882. for (var x = 0; x < width; x++) {
  32883. var srcPos = (x + y * width) * 4;
  32884. destArray[index] = BABYLON.MathTools.Clamp(srcData[srcPos]) * 255;
  32885. destArray[index + 1] = BABYLON.MathTools.Clamp(srcData[srcPos + 1]) * 255;
  32886. destArray[index + 2] = BABYLON.MathTools.Clamp(srcData[srcPos + 2]) * 255;
  32887. if (DDSTools.StoreLODInAlphaChannel) {
  32888. destArray[index + 3] = lod;
  32889. }
  32890. else {
  32891. destArray[index + 3] = BABYLON.MathTools.Clamp(srcData[srcPos + 3]) * 255;
  32892. }
  32893. index += 4;
  32894. }
  32895. }
  32896. return destArray;
  32897. };
  32898. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  32899. var destArray = new Uint8Array(dataLength);
  32900. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  32901. var index = 0;
  32902. for (var y = 0; y < height; y++) {
  32903. for (var x = 0; x < width; x++) {
  32904. var srcPos = (x + y * width) * 4;
  32905. destArray[index] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  32906. destArray[index + 1] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  32907. destArray[index + 2] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  32908. if (DDSTools.StoreLODInAlphaChannel) {
  32909. destArray[index + 3] = lod;
  32910. }
  32911. else {
  32912. destArray[index + 3] = BABYLON.MathTools.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  32913. }
  32914. index += 4;
  32915. }
  32916. }
  32917. return destArray;
  32918. };
  32919. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32920. var byteArray = new Uint8Array(dataLength);
  32921. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  32922. var index = 0;
  32923. for (var y = 0; y < height; y++) {
  32924. for (var x = 0; x < width; x++) {
  32925. var srcPos = (x + y * width) * 4;
  32926. byteArray[index] = srcData[srcPos + 2];
  32927. byteArray[index + 1] = srcData[srcPos + 1];
  32928. byteArray[index + 2] = srcData[srcPos];
  32929. byteArray[index + 3] = srcData[srcPos + 3];
  32930. index += 4;
  32931. }
  32932. }
  32933. return byteArray;
  32934. };
  32935. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32936. var byteArray = new Uint8Array(dataLength);
  32937. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  32938. var index = 0;
  32939. for (var y = 0; y < height; y++) {
  32940. for (var x = 0; x < width; x++) {
  32941. var srcPos = (x + y * width) * 3;
  32942. byteArray[index] = srcData[srcPos + 2];
  32943. byteArray[index + 1] = srcData[srcPos + 1];
  32944. byteArray[index + 2] = srcData[srcPos];
  32945. index += 3;
  32946. }
  32947. }
  32948. return byteArray;
  32949. };
  32950. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32951. var byteArray = new Uint8Array(dataLength);
  32952. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  32953. var index = 0;
  32954. for (var y = 0; y < height; y++) {
  32955. for (var x = 0; x < width; x++) {
  32956. var srcPos = (x + y * width);
  32957. byteArray[index] = srcData[srcPos];
  32958. index++;
  32959. }
  32960. }
  32961. return byteArray;
  32962. };
  32963. DDSTools.UploadDDSLevels = function (engine, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  32964. if (lodIndex === void 0) { lodIndex = -1; }
  32965. var gl = engine._gl;
  32966. var ext = engine.getCaps().s3tc;
  32967. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  32968. if (header[off_magic] != DDS_MAGIC) {
  32969. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32970. return;
  32971. }
  32972. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32973. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32974. return;
  32975. }
  32976. if (info.isCompressed && !ext) {
  32977. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  32978. return;
  32979. }
  32980. var bpp = header[off_RGBbpp];
  32981. dataOffset = header[off_size] + 4;
  32982. var computeFormats = false;
  32983. if (info.isFourCC) {
  32984. fourCC = header[off_pfFourCC];
  32985. switch (fourCC) {
  32986. case FOURCC_DXT1:
  32987. blockBytes = 8;
  32988. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32989. break;
  32990. case FOURCC_DXT3:
  32991. blockBytes = 16;
  32992. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32993. break;
  32994. case FOURCC_DXT5:
  32995. blockBytes = 16;
  32996. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32997. break;
  32998. case FOURCC_D3DFMT_R16G16B16A16F:
  32999. computeFormats = true;
  33000. break;
  33001. case FOURCC_D3DFMT_R32G32B32A32F:
  33002. computeFormats = true;
  33003. break;
  33004. case FOURCC_DX10:
  33005. // There is an additionnal header so dataOffset need to be changed
  33006. dataOffset += 5 * 4; // 5 uints
  33007. var supported = false;
  33008. switch (info.dxgiFormat) {
  33009. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  33010. computeFormats = true;
  33011. supported = true;
  33012. break;
  33013. case DXGI_FORMAT_B8G8R8X8_UNORM:
  33014. info.isRGB = true;
  33015. info.isFourCC = false;
  33016. bpp = 32;
  33017. supported = true;
  33018. break;
  33019. }
  33020. if (supported) {
  33021. break;
  33022. }
  33023. default:
  33024. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33025. return;
  33026. }
  33027. }
  33028. if (computeFormats) {
  33029. format = engine._getWebGLTextureType(info.textureType);
  33030. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  33031. }
  33032. mipmapCount = 1;
  33033. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33034. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33035. }
  33036. for (var face = 0; face < faces; face++) {
  33037. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33038. width = header[off_width];
  33039. height = header[off_height];
  33040. for (mip = 0; mip < mipmapCount; ++mip) {
  33041. if (lodIndex === -1 || lodIndex === mip) {
  33042. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  33043. var i = (lodIndex === -1) ? mip : 0;
  33044. if (!info.isCompressed && info.isFourCC) {
  33045. dataLength = width * height * 4;
  33046. var floatArray;
  33047. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  33048. if (bpp === 128) {
  33049. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  33050. }
  33051. else if (bpp === 64) {
  33052. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  33053. }
  33054. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33055. format = engine._getWebGLTextureType(info.textureType);
  33056. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  33057. }
  33058. else {
  33059. if (bpp === 128) {
  33060. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  33061. }
  33062. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  33063. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  33064. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33065. format = engine._getWebGLTextureType(info.textureType);
  33066. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  33067. }
  33068. else {
  33069. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  33070. }
  33071. }
  33072. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  33073. }
  33074. else if (info.isRGB) {
  33075. if (bpp === 24) {
  33076. dataLength = width * height * 3;
  33077. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33078. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33079. }
  33080. else {
  33081. dataLength = width * height * 4;
  33082. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33083. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33084. }
  33085. }
  33086. else if (info.isLuminance) {
  33087. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33088. var unpaddedRowSize = width;
  33089. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33090. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33091. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33092. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33093. }
  33094. else {
  33095. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33096. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33097. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  33098. }
  33099. }
  33100. dataOffset += width * height * (bpp / 8);
  33101. width *= 0.5;
  33102. height *= 0.5;
  33103. width = Math.max(1.0, width);
  33104. height = Math.max(1.0, height);
  33105. }
  33106. }
  33107. };
  33108. return DDSTools;
  33109. }());
  33110. DDSTools.StoreLODInAlphaChannel = false;
  33111. Internals.DDSTools = DDSTools;
  33112. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33113. })(BABYLON || (BABYLON = {}));
  33114. //# sourceMappingURL=babylon.dds.js.map
  33115. var BABYLON;
  33116. (function (BABYLON) {
  33117. var Internals;
  33118. (function (Internals) {
  33119. /**
  33120. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  33121. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  33122. */
  33123. var KhronosTextureContainer = (function () {
  33124. /**
  33125. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  33126. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  33127. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  33128. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  33129. */
  33130. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  33131. this.arrayBuffer = arrayBuffer;
  33132. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  33133. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  33134. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  33135. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  33136. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  33137. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  33138. BABYLON.Tools.Error("texture missing KTX identifier");
  33139. return;
  33140. }
  33141. // load the reset of the header in native 32 bit int
  33142. var header = new Int32Array(this.arrayBuffer, 12, 13);
  33143. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  33144. var oppositeEndianess = header[0] === 0x01020304;
  33145. // read all the header elements in order they exist in the file, without modification (sans endainness)
  33146. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  33147. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  33148. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  33149. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  33150. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  33151. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  33152. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  33153. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  33154. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  33155. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  33156. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  33157. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  33158. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  33159. if (this.glType !== 0) {
  33160. BABYLON.Tools.Error("only compressed formats currently supported");
  33161. return;
  33162. }
  33163. else {
  33164. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  33165. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  33166. }
  33167. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  33168. BABYLON.Tools.Error("only 2D textures currently supported");
  33169. return;
  33170. }
  33171. if (this.numberOfArrayElements !== 0) {
  33172. BABYLON.Tools.Error("texture arrays not currently supported");
  33173. return;
  33174. }
  33175. if (this.numberOfFaces !== facesExpected) {
  33176. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  33177. return;
  33178. }
  33179. // we now have a completely validated file, so could use existence of loadType as success
  33180. // would need to make this more elaborate & adjust checks above to support more than one load type
  33181. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  33182. }
  33183. // not as fast hardware based, but will probably never need to use
  33184. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  33185. return ((val & 0xFF) << 24)
  33186. | ((val & 0xFF00) << 8)
  33187. | ((val >> 8) & 0xFF00)
  33188. | ((val >> 24) & 0xFF);
  33189. };
  33190. /**
  33191. * It is assumed that the texture has already been created & is currently bound
  33192. */
  33193. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  33194. switch (this.loadType) {
  33195. case KhronosTextureContainer.COMPRESSED_2D:
  33196. this._upload2DCompressedLevels(gl, loadMipmaps);
  33197. break;
  33198. case KhronosTextureContainer.TEX_2D:
  33199. case KhronosTextureContainer.COMPRESSED_3D:
  33200. case KhronosTextureContainer.TEX_3D:
  33201. }
  33202. };
  33203. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  33204. // initialize width & height for level 1
  33205. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  33206. var width = this.pixelWidth;
  33207. var height = this.pixelHeight;
  33208. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  33209. for (var level = 0; level < mipmapCount; level++) {
  33210. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  33211. for (var face = 0; face < this.numberOfFaces; face++) {
  33212. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33213. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  33214. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  33215. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  33216. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  33217. }
  33218. width = Math.max(1.0, width * 0.5);
  33219. height = Math.max(1.0, height * 0.5);
  33220. }
  33221. };
  33222. return KhronosTextureContainer;
  33223. }());
  33224. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  33225. // load types
  33226. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  33227. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  33228. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  33229. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  33230. Internals.KhronosTextureContainer = KhronosTextureContainer;
  33231. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33232. })(BABYLON || (BABYLON = {}));
  33233. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  33234. var BABYLON;
  33235. (function (BABYLON) {
  33236. var PostProcess = (function () {
  33237. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  33238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  33239. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33240. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  33241. if (blockCompilation === void 0) { blockCompilation = false; }
  33242. this.name = name;
  33243. this.width = -1;
  33244. this.height = -1;
  33245. this.autoClear = true;
  33246. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  33247. /*
  33248. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  33249. Can only be used on a single postprocess or on the last one of a chain.
  33250. */
  33251. this.enablePixelPerfectMode = false;
  33252. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  33253. this.alwaysForcePOT = false;
  33254. this.samples = 1;
  33255. this._reusable = false;
  33256. this._textures = new BABYLON.SmartArray(2);
  33257. this._currentRenderTextureInd = 0;
  33258. this._scaleRatio = new BABYLON.Vector2(1, 1);
  33259. this._texelSize = BABYLON.Vector2.Zero();
  33260. // Events
  33261. /**
  33262. * An event triggered when the postprocess is activated.
  33263. * @type {BABYLON.Observable}
  33264. */
  33265. this.onActivateObservable = new BABYLON.Observable();
  33266. /**
  33267. * An event triggered when the postprocess changes its size.
  33268. * @type {BABYLON.Observable}
  33269. */
  33270. this.onSizeChangedObservable = new BABYLON.Observable();
  33271. /**
  33272. * An event triggered when the postprocess applies its effect.
  33273. * @type {BABYLON.Observable}
  33274. */
  33275. this.onApplyObservable = new BABYLON.Observable();
  33276. /**
  33277. * An event triggered before rendering the postprocess
  33278. * @type {BABYLON.Observable}
  33279. */
  33280. this.onBeforeRenderObservable = new BABYLON.Observable();
  33281. /**
  33282. * An event triggered after rendering the postprocess
  33283. * @type {BABYLON.Observable}
  33284. */
  33285. this.onAfterRenderObservable = new BABYLON.Observable();
  33286. if (camera != null) {
  33287. this._camera = camera;
  33288. this._scene = camera.getScene();
  33289. camera.attachPostProcess(this);
  33290. this._engine = this._scene.getEngine();
  33291. }
  33292. else {
  33293. this._engine = engine;
  33294. }
  33295. this._options = options;
  33296. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  33297. this._reusable = reusable || false;
  33298. this._textureType = textureType;
  33299. this._samplers = samplers || [];
  33300. this._samplers.push("textureSampler");
  33301. this._fragmentUrl = fragmentUrl;
  33302. this._vertexUrl = vertexUrl;
  33303. this._parameters = parameters || [];
  33304. this._parameters.push("scale");
  33305. this._indexParameters = indexParameters;
  33306. if (!blockCompilation) {
  33307. this.updateEffect(defines);
  33308. }
  33309. }
  33310. Object.defineProperty(PostProcess.prototype, "onActivate", {
  33311. set: function (callback) {
  33312. if (this._onActivateObserver) {
  33313. this.onActivateObservable.remove(this._onActivateObserver);
  33314. }
  33315. this._onActivateObserver = this.onActivateObservable.add(callback);
  33316. },
  33317. enumerable: true,
  33318. configurable: true
  33319. });
  33320. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  33321. set: function (callback) {
  33322. if (this._onSizeChangedObserver) {
  33323. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  33324. }
  33325. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  33326. },
  33327. enumerable: true,
  33328. configurable: true
  33329. });
  33330. Object.defineProperty(PostProcess.prototype, "onApply", {
  33331. set: function (callback) {
  33332. if (this._onApplyObserver) {
  33333. this.onApplyObservable.remove(this._onApplyObserver);
  33334. }
  33335. this._onApplyObserver = this.onApplyObservable.add(callback);
  33336. },
  33337. enumerable: true,
  33338. configurable: true
  33339. });
  33340. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  33341. set: function (callback) {
  33342. if (this._onBeforeRenderObserver) {
  33343. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  33344. }
  33345. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  33346. },
  33347. enumerable: true,
  33348. configurable: true
  33349. });
  33350. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  33351. set: function (callback) {
  33352. if (this._onAfterRenderObserver) {
  33353. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  33354. }
  33355. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  33356. },
  33357. enumerable: true,
  33358. configurable: true
  33359. });
  33360. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  33361. get: function () {
  33362. return this._textures.data[this._currentRenderTextureInd];
  33363. },
  33364. set: function (value) {
  33365. this._forcedOutputTexture = value;
  33366. },
  33367. enumerable: true,
  33368. configurable: true
  33369. });
  33370. PostProcess.prototype.getCamera = function () {
  33371. return this._camera;
  33372. };
  33373. Object.defineProperty(PostProcess.prototype, "texelSize", {
  33374. get: function () {
  33375. if (this._shareOutputWithPostProcess) {
  33376. return this._shareOutputWithPostProcess.texelSize;
  33377. }
  33378. if (this._forcedOutputTexture) {
  33379. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  33380. }
  33381. return this._texelSize;
  33382. },
  33383. enumerable: true,
  33384. configurable: true
  33385. });
  33386. PostProcess.prototype.getEngine = function () {
  33387. return this._engine;
  33388. };
  33389. PostProcess.prototype.getEffect = function () {
  33390. return this._effect;
  33391. };
  33392. PostProcess.prototype.shareOutputWith = function (postProcess) {
  33393. this._disposeTextures();
  33394. this._shareOutputWithPostProcess = postProcess;
  33395. return this;
  33396. };
  33397. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  33398. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  33399. };
  33400. PostProcess.prototype.isReusable = function () {
  33401. return this._reusable;
  33402. };
  33403. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  33404. PostProcess.prototype.markTextureDirty = function () {
  33405. this.width = -1;
  33406. };
  33407. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  33408. var _this = this;
  33409. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  33410. camera = camera || this._camera;
  33411. var scene = camera.getScene();
  33412. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  33413. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  33414. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  33415. var desiredWidth = this._options.width || requiredWidth;
  33416. var desiredHeight = this._options.height || requiredHeight;
  33417. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  33418. if (!this._options.width) {
  33419. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  33420. }
  33421. if (!this._options.height) {
  33422. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  33423. }
  33424. }
  33425. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  33426. if (this._textures.length > 0) {
  33427. for (var i = 0; i < this._textures.length; i++) {
  33428. this._engine._releaseTexture(this._textures.data[i]);
  33429. }
  33430. this._textures.reset();
  33431. }
  33432. this.width = desiredWidth;
  33433. this.height = desiredHeight;
  33434. var textureSize = { width: this.width, height: this.height };
  33435. var textureOptions = {
  33436. generateMipMaps: false,
  33437. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  33438. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  33439. samplingMode: this.renderTargetSamplingMode,
  33440. type: this._textureType
  33441. };
  33442. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  33443. if (this._reusable) {
  33444. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  33445. }
  33446. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  33447. this.onSizeChangedObservable.notifyObservers(this);
  33448. }
  33449. this._textures.forEach(function (texture) {
  33450. if (texture.samples !== _this.samples) {
  33451. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  33452. }
  33453. });
  33454. }
  33455. var target;
  33456. if (this._shareOutputWithPostProcess) {
  33457. target = this._shareOutputWithPostProcess.outputTexture;
  33458. }
  33459. else if (this._forcedOutputTexture) {
  33460. target = this._forcedOutputTexture;
  33461. this.width = this._forcedOutputTexture._width;
  33462. this.height = this._forcedOutputTexture._height;
  33463. }
  33464. else {
  33465. target = this.outputTexture;
  33466. }
  33467. if (this.enablePixelPerfectMode) {
  33468. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  33469. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  33470. }
  33471. else {
  33472. this._scaleRatio.copyFromFloats(1, 1);
  33473. this._engine.bindFramebuffer(target);
  33474. }
  33475. this.onActivateObservable.notifyObservers(camera);
  33476. // Clear
  33477. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  33478. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  33479. }
  33480. if (this._reusable) {
  33481. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  33482. }
  33483. };
  33484. Object.defineProperty(PostProcess.prototype, "isSupported", {
  33485. get: function () {
  33486. return this._effect.isSupported;
  33487. },
  33488. enumerable: true,
  33489. configurable: true
  33490. });
  33491. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  33492. get: function () {
  33493. if (this._shareOutputWithPostProcess) {
  33494. return this._shareOutputWithPostProcess.aspectRatio;
  33495. }
  33496. if (this._forcedOutputTexture) {
  33497. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  33498. }
  33499. return this.width / this.height;
  33500. },
  33501. enumerable: true,
  33502. configurable: true
  33503. });
  33504. PostProcess.prototype.apply = function () {
  33505. // Check
  33506. if (!this._effect || !this._effect.isReady())
  33507. return null;
  33508. // States
  33509. this._engine.enableEffect(this._effect);
  33510. this._engine.setState(false);
  33511. this._engine.setDepthBuffer(false);
  33512. this._engine.setDepthWrite(false);
  33513. // Alpha
  33514. this._engine.setAlphaMode(this.alphaMode);
  33515. if (this.alphaConstants) {
  33516. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  33517. }
  33518. // Texture
  33519. var source;
  33520. if (this._shareOutputWithPostProcess) {
  33521. source = this._shareOutputWithPostProcess.outputTexture;
  33522. }
  33523. else if (this._forcedOutputTexture) {
  33524. source = this._forcedOutputTexture;
  33525. }
  33526. else {
  33527. source = this.outputTexture;
  33528. }
  33529. this._effect._bindTexture("textureSampler", source);
  33530. // Parameters
  33531. this._effect.setVector2("scale", this._scaleRatio);
  33532. this.onApplyObservable.notifyObservers(this._effect);
  33533. return this._effect;
  33534. };
  33535. PostProcess.prototype._disposeTextures = function () {
  33536. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  33537. return;
  33538. }
  33539. if (this._textures.length > 0) {
  33540. for (var i = 0; i < this._textures.length; i++) {
  33541. this._engine._releaseTexture(this._textures.data[i]);
  33542. }
  33543. }
  33544. this._textures.dispose();
  33545. };
  33546. PostProcess.prototype.dispose = function (camera) {
  33547. camera = camera || this._camera;
  33548. this._disposeTextures();
  33549. if (!camera) {
  33550. return;
  33551. }
  33552. camera.detachPostProcess(this);
  33553. var index = camera._postProcesses.indexOf(this);
  33554. if (index === 0 && camera._postProcesses.length > 0) {
  33555. this._camera._postProcesses[0].markTextureDirty();
  33556. }
  33557. this.onActivateObservable.clear();
  33558. this.onAfterRenderObservable.clear();
  33559. this.onApplyObservable.clear();
  33560. this.onBeforeRenderObservable.clear();
  33561. this.onSizeChangedObservable.clear();
  33562. };
  33563. return PostProcess;
  33564. }());
  33565. BABYLON.PostProcess = PostProcess;
  33566. })(BABYLON || (BABYLON = {}));
  33567. //# sourceMappingURL=babylon.postProcess.js.map
  33568. var BABYLON;
  33569. (function (BABYLON) {
  33570. var PassPostProcess = (function (_super) {
  33571. __extends(PassPostProcess, _super);
  33572. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  33573. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33574. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  33575. }
  33576. return PassPostProcess;
  33577. }(BABYLON.PostProcess));
  33578. BABYLON.PassPostProcess = PassPostProcess;
  33579. })(BABYLON || (BABYLON = {}));
  33580. //# sourceMappingURL=babylon.passPostProcess.js.map
  33581. var BABYLON;
  33582. (function (BABYLON) {
  33583. var ShadowGenerator = (function () {
  33584. /**
  33585. * Creates a ShadowGenerator object.
  33586. * A ShadowGenerator is the required tool to use the shadows.
  33587. * Each light casting shadows needs to use its own ShadowGenerator.
  33588. * Required parameters :
  33589. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  33590. * - `light`: the light object generating the shadows.
  33591. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  33592. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  33593. */
  33594. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  33595. // Members
  33596. this._bias = 0.00005;
  33597. this._blurBoxOffset = 1;
  33598. this._blurScale = 2;
  33599. this._blurKernel = 1;
  33600. this._useKernelBlur = false;
  33601. this._filter = ShadowGenerator.FILTER_NONE;
  33602. this._darkness = 0;
  33603. this._transparencyShadow = false;
  33604. this.forceBackFacesOnly = false;
  33605. this._lightDirection = BABYLON.Vector3.Zero();
  33606. this._viewMatrix = BABYLON.Matrix.Zero();
  33607. this._projectionMatrix = BABYLON.Matrix.Zero();
  33608. this._transformMatrix = BABYLON.Matrix.Zero();
  33609. this._worldViewProjection = BABYLON.Matrix.Zero();
  33610. this._currentFaceIndex = 0;
  33611. this._currentFaceIndexCache = 0;
  33612. this._isCube = false;
  33613. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  33614. this._mapSize = mapSize;
  33615. this._light = light;
  33616. this._scene = light.getScene();
  33617. light._shadowGenerator = this;
  33618. // Texture type fallback from float to int if not supported.
  33619. var caps = this._scene.getEngine().getCaps();
  33620. if (!useFullFloatFirst) {
  33621. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33622. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33623. }
  33624. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33625. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33626. }
  33627. else {
  33628. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33629. }
  33630. }
  33631. else {
  33632. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33633. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33634. }
  33635. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33636. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33637. }
  33638. else {
  33639. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33640. }
  33641. }
  33642. this._initializeGenerator();
  33643. }
  33644. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  33645. // Static
  33646. get: function () {
  33647. return ShadowGenerator._FILTER_NONE;
  33648. },
  33649. enumerable: true,
  33650. configurable: true
  33651. });
  33652. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  33653. get: function () {
  33654. return ShadowGenerator._FILTER_POISSONSAMPLING;
  33655. },
  33656. enumerable: true,
  33657. configurable: true
  33658. });
  33659. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  33660. get: function () {
  33661. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  33662. },
  33663. enumerable: true,
  33664. configurable: true
  33665. });
  33666. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  33667. get: function () {
  33668. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  33669. },
  33670. enumerable: true,
  33671. configurable: true
  33672. });
  33673. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  33674. get: function () {
  33675. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33676. },
  33677. enumerable: true,
  33678. configurable: true
  33679. });
  33680. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  33681. get: function () {
  33682. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33683. },
  33684. enumerable: true,
  33685. configurable: true
  33686. });
  33687. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  33688. get: function () {
  33689. return this._bias;
  33690. },
  33691. set: function (bias) {
  33692. this._bias = bias;
  33693. },
  33694. enumerable: true,
  33695. configurable: true
  33696. });
  33697. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  33698. get: function () {
  33699. return this._blurBoxOffset;
  33700. },
  33701. set: function (value) {
  33702. if (this._blurBoxOffset === value) {
  33703. return;
  33704. }
  33705. this._blurBoxOffset = value;
  33706. this._disposeBlurPostProcesses();
  33707. },
  33708. enumerable: true,
  33709. configurable: true
  33710. });
  33711. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  33712. get: function () {
  33713. return this._blurScale;
  33714. },
  33715. set: function (value) {
  33716. if (this._blurScale === value) {
  33717. return;
  33718. }
  33719. this._blurScale = value;
  33720. this._disposeBlurPostProcesses();
  33721. },
  33722. enumerable: true,
  33723. configurable: true
  33724. });
  33725. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  33726. get: function () {
  33727. return this._blurKernel;
  33728. },
  33729. set: function (value) {
  33730. if (this._blurKernel === value) {
  33731. return;
  33732. }
  33733. this._blurKernel = value;
  33734. this._disposeBlurPostProcesses();
  33735. },
  33736. enumerable: true,
  33737. configurable: true
  33738. });
  33739. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33740. get: function () {
  33741. return this._useKernelBlur;
  33742. },
  33743. set: function (value) {
  33744. if (this._useKernelBlur === value) {
  33745. return;
  33746. }
  33747. this._useKernelBlur = value;
  33748. this._disposeBlurPostProcesses();
  33749. },
  33750. enumerable: true,
  33751. configurable: true
  33752. });
  33753. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33754. get: function () {
  33755. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33756. },
  33757. set: function (value) {
  33758. this._depthScale = value;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33764. get: function () {
  33765. return this._filter;
  33766. },
  33767. set: function (value) {
  33768. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33769. if (this._light.needCube()) {
  33770. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33771. this.useExponentialShadowMap = true;
  33772. return;
  33773. }
  33774. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33775. this.useCloseExponentialShadowMap = true;
  33776. return;
  33777. }
  33778. }
  33779. if (this._filter === value) {
  33780. return;
  33781. }
  33782. this._filter = value;
  33783. this._disposeBlurPostProcesses();
  33784. this._applyFilterValues();
  33785. this._light._markMeshesAsLightDirty();
  33786. },
  33787. enumerable: true,
  33788. configurable: true
  33789. });
  33790. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33791. get: function () {
  33792. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33793. },
  33794. set: function (value) {
  33795. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33796. },
  33797. enumerable: true,
  33798. configurable: true
  33799. });
  33800. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33801. get: function () {
  33802. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33803. return this.useExponentialShadowMap;
  33804. },
  33805. set: function (value) {
  33806. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33807. this.useExponentialShadowMap = value;
  33808. },
  33809. enumerable: true,
  33810. configurable: true
  33811. });
  33812. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33813. get: function () {
  33814. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33815. return this.useBlurExponentialShadowMap;
  33816. },
  33817. set: function (value) {
  33818. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33819. this.useBlurExponentialShadowMap = value;
  33820. },
  33821. enumerable: true,
  33822. configurable: true
  33823. });
  33824. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33825. get: function () {
  33826. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33827. },
  33828. set: function (value) {
  33829. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33830. },
  33831. enumerable: true,
  33832. configurable: true
  33833. });
  33834. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33835. get: function () {
  33836. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33837. },
  33838. set: function (value) {
  33839. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33840. },
  33841. enumerable: true,
  33842. configurable: true
  33843. });
  33844. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33845. get: function () {
  33846. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33847. },
  33848. set: function (value) {
  33849. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33850. },
  33851. enumerable: true,
  33852. configurable: true
  33853. });
  33854. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33855. get: function () {
  33856. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33857. },
  33858. set: function (value) {
  33859. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33860. },
  33861. enumerable: true,
  33862. configurable: true
  33863. });
  33864. /**
  33865. * Returns the darkness value (float).
  33866. */
  33867. ShadowGenerator.prototype.getDarkness = function () {
  33868. return this._darkness;
  33869. };
  33870. /**
  33871. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33872. * Returns the ShadowGenerator.
  33873. */
  33874. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33875. if (darkness >= 1.0)
  33876. this._darkness = 1.0;
  33877. else if (darkness <= 0.0)
  33878. this._darkness = 0.0;
  33879. else
  33880. this._darkness = darkness;
  33881. return this;
  33882. };
  33883. /**
  33884. * Sets the ability to have transparent shadow (boolean).
  33885. * Returns the ShadowGenerator.
  33886. */
  33887. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33888. this._transparencyShadow = hasShadow;
  33889. return this;
  33890. };
  33891. /**
  33892. * Returns a RenderTargetTexture object : the shadow map texture.
  33893. */
  33894. ShadowGenerator.prototype.getShadowMap = function () {
  33895. return this._shadowMap;
  33896. };
  33897. /**
  33898. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33899. */
  33900. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33901. if (this._shadowMap2) {
  33902. return this._shadowMap2;
  33903. }
  33904. return this._shadowMap;
  33905. };
  33906. /**
  33907. * Returns the associated light object.
  33908. */
  33909. ShadowGenerator.prototype.getLight = function () {
  33910. return this._light;
  33911. };
  33912. ShadowGenerator.prototype._initializeGenerator = function () {
  33913. this._light._markMeshesAsLightDirty();
  33914. this._initializeShadowMap();
  33915. };
  33916. ShadowGenerator.prototype._initializeShadowMap = function () {
  33917. var _this = this;
  33918. // Render target
  33919. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33920. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33921. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33922. this._shadowMap.anisotropicFilteringLevel = 1;
  33923. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33924. this._shadowMap.renderParticles = false;
  33925. // Record Face Index before render.
  33926. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33927. _this._currentFaceIndex = faceIndex;
  33928. });
  33929. // Custom render function.
  33930. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33931. // Blur if required afer render.
  33932. this._shadowMap.onAfterUnbindObservable.add(function () {
  33933. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33934. return;
  33935. }
  33936. if (!_this._blurPostProcesses) {
  33937. _this._initializeBlurRTTAndPostProcesses();
  33938. }
  33939. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33940. });
  33941. // Clear according to the chosen filter.
  33942. this._shadowMap.onClearObservable.add(function (engine) {
  33943. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33944. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33945. }
  33946. else {
  33947. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33948. }
  33949. });
  33950. };
  33951. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33952. var _this = this;
  33953. var engine = this._scene.getEngine();
  33954. var targetSize = this._mapSize / this.blurScale;
  33955. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33956. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33957. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33958. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33959. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33960. }
  33961. if (this.useKernelBlur) {
  33962. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33963. this._kernelBlurXPostprocess.width = targetSize;
  33964. this._kernelBlurXPostprocess.height = targetSize;
  33965. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33966. effect.setTexture("textureSampler", _this._shadowMap);
  33967. });
  33968. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33969. this._kernelBlurXPostprocess.autoClear = false;
  33970. this._kernelBlurYPostprocess.autoClear = false;
  33971. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33972. this._kernelBlurXPostprocess.packedFloat = true;
  33973. this._kernelBlurYPostprocess.packedFloat = true;
  33974. }
  33975. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33976. }
  33977. else {
  33978. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  33979. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33980. effect.setFloat2("screenSize", targetSize, targetSize);
  33981. effect.setTexture("textureSampler", _this._shadowMap);
  33982. });
  33983. this._boxBlurPostprocess.autoClear = false;
  33984. this._blurPostProcesses = [this._boxBlurPostprocess];
  33985. }
  33986. };
  33987. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33988. var index;
  33989. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33990. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33991. }
  33992. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33993. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33994. }
  33995. if (this._transparencyShadow) {
  33996. for (index = 0; index < transparentSubMeshes.length; index++) {
  33997. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33998. }
  33999. }
  34000. };
  34001. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  34002. var _this = this;
  34003. var mesh = subMesh.getRenderingMesh();
  34004. var scene = this._scene;
  34005. var engine = scene.getEngine();
  34006. // Culling
  34007. engine.setState(subMesh.getMaterial().backFaceCulling);
  34008. // Managing instances
  34009. var batch = mesh._getInstancesRenderList(subMesh._id);
  34010. if (batch.mustReturn) {
  34011. return;
  34012. }
  34013. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  34014. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  34015. engine.enableEffect(this._effect);
  34016. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  34017. var material = subMesh.getMaterial();
  34018. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  34019. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  34020. this._effect.setVector3("lightPosition", this.getLight().position);
  34021. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  34022. // Alpha test
  34023. if (material && material.needAlphaTesting()) {
  34024. var alphaTexture = material.getAlphaTestTexture();
  34025. if (alphaTexture) {
  34026. this._effect.setTexture("diffuseSampler", alphaTexture);
  34027. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  34028. }
  34029. }
  34030. // Bones
  34031. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34032. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34033. }
  34034. if (this.forceBackFacesOnly) {
  34035. engine.setState(true, 0, false, true);
  34036. }
  34037. // Draw
  34038. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  34039. if (this.forceBackFacesOnly) {
  34040. engine.setState(true, 0, false, false);
  34041. }
  34042. }
  34043. else {
  34044. // Need to reset refresh rate of the shadowMap
  34045. this._shadowMap.resetRefreshCounter();
  34046. }
  34047. };
  34048. ShadowGenerator.prototype._applyFilterValues = function () {
  34049. if (this.filter === ShadowGenerator.FILTER_NONE) {
  34050. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  34051. }
  34052. else {
  34053. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  34054. }
  34055. };
  34056. /**
  34057. * Boolean : true when the ShadowGenerator is finally computed.
  34058. */
  34059. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  34060. var defines = [];
  34061. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  34062. defines.push("#define FLOAT");
  34063. }
  34064. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  34065. defines.push("#define ESM");
  34066. }
  34067. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34068. var mesh = subMesh.getMesh();
  34069. var material = subMesh.getMaterial();
  34070. // Alpha test
  34071. if (material && material.needAlphaTesting()) {
  34072. var alphaTexture = material.getAlphaTestTexture();
  34073. if (alphaTexture) {
  34074. defines.push("#define ALPHATEST");
  34075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34076. attribs.push(BABYLON.VertexBuffer.UVKind);
  34077. defines.push("#define UV1");
  34078. }
  34079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34080. if (alphaTexture.coordinatesIndex === 1) {
  34081. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34082. defines.push("#define UV2");
  34083. }
  34084. }
  34085. }
  34086. }
  34087. // Bones
  34088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  34089. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34090. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34091. if (mesh.numBoneInfluencers > 4) {
  34092. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34093. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34094. }
  34095. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34096. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34097. }
  34098. else {
  34099. defines.push("#define NUM_BONE_INFLUENCERS 0");
  34100. }
  34101. // Instances
  34102. if (useInstances) {
  34103. defines.push("#define INSTANCES");
  34104. attribs.push("world0");
  34105. attribs.push("world1");
  34106. attribs.push("world2");
  34107. attribs.push("world3");
  34108. }
  34109. // Get correct effect
  34110. var join = defines.join("\n");
  34111. if (this._cachedDefines !== join) {
  34112. this._cachedDefines = join;
  34113. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  34114. }
  34115. return this._effect.isReady();
  34116. };
  34117. /**
  34118. * This creates the defines related to the standard BJS materials.
  34119. */
  34120. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  34121. var scene = this._scene;
  34122. var light = this._light;
  34123. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  34124. return;
  34125. }
  34126. defines["SHADOW" + lightIndex] = true;
  34127. if (this.usePoissonSampling) {
  34128. defines["SHADOWPCF" + lightIndex] = true;
  34129. }
  34130. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  34131. defines["SHADOWESM" + lightIndex] = true;
  34132. }
  34133. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  34134. defines["SHADOWCLOSEESM" + lightIndex] = true;
  34135. }
  34136. if (light.needCube()) {
  34137. defines["SHADOWCUBE" + lightIndex] = true;
  34138. }
  34139. };
  34140. /**
  34141. * This binds shadow lights related to the standard BJS materials.
  34142. * It implies the unifroms available on the materials are the standard BJS ones.
  34143. */
  34144. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  34145. var light = this._light;
  34146. var scene = this._scene;
  34147. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  34148. return;
  34149. }
  34150. if (!light.needCube()) {
  34151. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  34152. }
  34153. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  34154. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  34155. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  34156. };
  34157. // Methods
  34158. /**
  34159. * Returns a Matrix object : the updated transformation matrix.
  34160. */
  34161. ShadowGenerator.prototype.getTransformMatrix = function () {
  34162. var scene = this._scene;
  34163. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  34164. return this._transformMatrix;
  34165. }
  34166. this._currentRenderID = scene.getRenderId();
  34167. this._currentFaceIndexCache = this._currentFaceIndex;
  34168. var lightPosition = this._light.position;
  34169. if (this._light.computeTransformedInformation()) {
  34170. lightPosition = this._light.transformedPosition;
  34171. }
  34172. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  34173. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  34174. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  34175. }
  34176. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  34177. this._cachedPosition = lightPosition.clone();
  34178. this._cachedDirection = this._lightDirection.clone();
  34179. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  34180. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  34181. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  34182. }
  34183. return this._transformMatrix;
  34184. };
  34185. ShadowGenerator.prototype.recreateShadowMap = function () {
  34186. // Track render list.
  34187. var renderList = this._shadowMap.renderList;
  34188. // Clean up existing data.
  34189. this._disposeRTTandPostProcesses();
  34190. // Reinitializes.
  34191. this._initializeGenerator();
  34192. // Reaffect the filter to ensure a correct fallback if necessary.
  34193. this.filter = this.filter;
  34194. // Reaffect the filter.
  34195. this._applyFilterValues();
  34196. // Reaffect Render List.
  34197. this._shadowMap.renderList = renderList;
  34198. };
  34199. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  34200. if (this._shadowMap2) {
  34201. this._shadowMap2.dispose();
  34202. this._shadowMap2 = null;
  34203. }
  34204. if (this._downSamplePostprocess) {
  34205. this._downSamplePostprocess.dispose();
  34206. this._downSamplePostprocess = null;
  34207. }
  34208. if (this._boxBlurPostprocess) {
  34209. this._boxBlurPostprocess.dispose();
  34210. this._boxBlurPostprocess = null;
  34211. }
  34212. if (this._kernelBlurXPostprocess) {
  34213. this._kernelBlurXPostprocess.dispose();
  34214. this._kernelBlurXPostprocess = null;
  34215. }
  34216. if (this._kernelBlurYPostprocess) {
  34217. this._kernelBlurYPostprocess.dispose();
  34218. this._kernelBlurYPostprocess = null;
  34219. }
  34220. this._blurPostProcesses = null;
  34221. };
  34222. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  34223. if (this._shadowMap) {
  34224. this._shadowMap.dispose();
  34225. this._shadowMap = null;
  34226. }
  34227. this._disposeBlurPostProcesses();
  34228. };
  34229. /**
  34230. * Disposes the ShadowGenerator.
  34231. * Returns nothing.
  34232. */
  34233. ShadowGenerator.prototype.dispose = function () {
  34234. this._disposeRTTandPostProcesses();
  34235. this._light._shadowGenerator = null;
  34236. this._light._markMeshesAsLightDirty();
  34237. };
  34238. /**
  34239. * Serializes the ShadowGenerator and returns a serializationObject.
  34240. */
  34241. ShadowGenerator.prototype.serialize = function () {
  34242. var serializationObject = {};
  34243. var shadowMap = this.getShadowMap();
  34244. serializationObject.lightId = this._light.id;
  34245. serializationObject.mapSize = shadowMap.getRenderSize();
  34246. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  34247. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  34248. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  34249. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  34250. serializationObject.usePoissonSampling = this.usePoissonSampling;
  34251. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  34252. serializationObject.depthScale = this.depthScale;
  34253. serializationObject.darkness = this.getDarkness();
  34254. serializationObject.blurBoxOffset = this.blurBoxOffset;
  34255. serializationObject.blurKernel = this.blurKernel;
  34256. serializationObject.blurScale = this.blurScale;
  34257. serializationObject.useKernelBlur = this.useKernelBlur;
  34258. serializationObject.transparencyShadow = this._transparencyShadow;
  34259. serializationObject.renderList = [];
  34260. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  34261. var mesh = shadowMap.renderList[meshIndex];
  34262. serializationObject.renderList.push(mesh.id);
  34263. }
  34264. return serializationObject;
  34265. };
  34266. /**
  34267. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  34268. */
  34269. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  34270. //casting to point light, as light is missing the position attr and typescript complains.
  34271. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  34272. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  34273. var shadowMap = shadowGenerator.getShadowMap();
  34274. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  34275. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  34276. meshes.forEach(function (mesh) {
  34277. shadowMap.renderList.push(mesh);
  34278. });
  34279. }
  34280. if (parsedShadowGenerator.usePoissonSampling) {
  34281. shadowGenerator.usePoissonSampling = true;
  34282. }
  34283. else if (parsedShadowGenerator.useExponentialShadowMap) {
  34284. shadowGenerator.useExponentialShadowMap = true;
  34285. }
  34286. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  34287. shadowGenerator.useBlurExponentialShadowMap = true;
  34288. }
  34289. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  34290. shadowGenerator.useCloseExponentialShadowMap = true;
  34291. }
  34292. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  34293. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  34294. }
  34295. else if (parsedShadowGenerator.useVarianceShadowMap) {
  34296. shadowGenerator.useExponentialShadowMap = true;
  34297. }
  34298. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  34299. shadowGenerator.useBlurExponentialShadowMap = true;
  34300. }
  34301. if (parsedShadowGenerator.depthScale) {
  34302. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  34303. }
  34304. if (parsedShadowGenerator.blurScale) {
  34305. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  34306. }
  34307. if (parsedShadowGenerator.blurBoxOffset) {
  34308. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  34309. }
  34310. if (parsedShadowGenerator.useKernelBlur) {
  34311. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  34312. }
  34313. if (parsedShadowGenerator.blurKernel) {
  34314. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  34315. }
  34316. if (parsedShadowGenerator.bias !== undefined) {
  34317. shadowGenerator.bias = parsedShadowGenerator.bias;
  34318. }
  34319. if (parsedShadowGenerator.darkness) {
  34320. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  34321. }
  34322. if (parsedShadowGenerator.transparencyShadow) {
  34323. shadowGenerator.setTransparencyShadow(true);
  34324. }
  34325. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  34326. return shadowGenerator;
  34327. };
  34328. return ShadowGenerator;
  34329. }());
  34330. ShadowGenerator._FILTER_NONE = 0;
  34331. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  34332. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  34333. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  34334. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  34335. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  34336. BABYLON.ShadowGenerator = ShadowGenerator;
  34337. })(BABYLON || (BABYLON = {}));
  34338. //# sourceMappingURL=babylon.shadowGenerator.js.map
  34339. var BABYLON;
  34340. (function (BABYLON) {
  34341. var ShadowLight = (function (_super) {
  34342. __extends(ShadowLight, _super);
  34343. function ShadowLight() {
  34344. var _this = _super !== null && _super.apply(this, arguments) || this;
  34345. _this._needProjectionMatrixCompute = true;
  34346. return _this;
  34347. }
  34348. Object.defineProperty(ShadowLight.prototype, "direction", {
  34349. get: function () {
  34350. return this._direction;
  34351. },
  34352. set: function (value) {
  34353. this._direction = value;
  34354. },
  34355. enumerable: true,
  34356. configurable: true
  34357. });
  34358. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  34359. get: function () {
  34360. return this._shadowMinZ;
  34361. },
  34362. set: function (value) {
  34363. this._shadowMinZ = value;
  34364. this.forceProjectionMatrixCompute();
  34365. },
  34366. enumerable: true,
  34367. configurable: true
  34368. });
  34369. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  34370. get: function () {
  34371. return this._shadowMaxZ;
  34372. },
  34373. set: function (value) {
  34374. this._shadowMaxZ = value;
  34375. this.forceProjectionMatrixCompute();
  34376. },
  34377. enumerable: true,
  34378. configurable: true
  34379. });
  34380. /**
  34381. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  34382. */
  34383. ShadowLight.prototype.computeTransformedInformation = function () {
  34384. if (this.parent && this.parent.getWorldMatrix) {
  34385. if (!this.transformedPosition) {
  34386. this.transformedPosition = BABYLON.Vector3.Zero();
  34387. }
  34388. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  34389. // In case the direction is present.
  34390. if (this.direction) {
  34391. if (!this.transformedDirection) {
  34392. this.transformedDirection = BABYLON.Vector3.Zero();
  34393. }
  34394. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  34395. }
  34396. return true;
  34397. }
  34398. return false;
  34399. };
  34400. /**
  34401. * Return the depth scale used for the shadow map.
  34402. */
  34403. ShadowLight.prototype.getDepthScale = function () {
  34404. return 50.0;
  34405. };
  34406. /**
  34407. * Returns the light direction (Vector3) for any passed face index.
  34408. */
  34409. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  34410. return this.transformedDirection ? this.transformedDirection : this.direction;
  34411. };
  34412. /**
  34413. * Returns the DirectionalLight absolute position in the World.
  34414. */
  34415. ShadowLight.prototype.getAbsolutePosition = function () {
  34416. return this.transformedPosition ? this.transformedPosition : this.position;
  34417. };
  34418. /**
  34419. * Sets the DirectionalLight direction toward the passed target (Vector3).
  34420. * Returns the updated DirectionalLight direction (Vector3).
  34421. */
  34422. ShadowLight.prototype.setDirectionToTarget = function (target) {
  34423. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  34424. return this.direction;
  34425. };
  34426. /**
  34427. * Returns the light rotation (Vector3).
  34428. */
  34429. ShadowLight.prototype.getRotation = function () {
  34430. this.direction.normalize();
  34431. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  34432. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  34433. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  34434. };
  34435. /**
  34436. * Boolean : false by default.
  34437. */
  34438. ShadowLight.prototype.needCube = function () {
  34439. return false;
  34440. };
  34441. /**
  34442. * Specifies wether or not the projection matrix should be recomputed this frame.
  34443. */
  34444. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  34445. return this._needProjectionMatrixCompute;
  34446. };
  34447. /**
  34448. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  34449. */
  34450. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  34451. this._needProjectionMatrixCompute = true;
  34452. };
  34453. /**
  34454. * Get the world matrix of the sahdow lights.
  34455. */
  34456. ShadowLight.prototype._getWorldMatrix = function () {
  34457. if (!this._worldMatrix) {
  34458. this._worldMatrix = BABYLON.Matrix.Identity();
  34459. }
  34460. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  34461. return this._worldMatrix;
  34462. };
  34463. /**
  34464. * Gets the minZ used for shadow according to both the scene and the light.
  34465. * @param activeCamera
  34466. */
  34467. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  34468. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  34469. };
  34470. /**
  34471. * Gets the maxZ used for shadow according to both the scene and the light.
  34472. * @param activeCamera
  34473. */
  34474. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  34475. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  34476. };
  34477. /**
  34478. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  34479. * Returns the light.
  34480. */
  34481. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34482. if (this.customProjectionMatrixBuilder) {
  34483. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  34484. }
  34485. else {
  34486. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34487. }
  34488. return this;
  34489. };
  34490. return ShadowLight;
  34491. }(BABYLON.Light));
  34492. __decorate([
  34493. BABYLON.serializeAsVector3()
  34494. ], ShadowLight.prototype, "position", void 0);
  34495. __decorate([
  34496. BABYLON.serializeAsVector3()
  34497. ], ShadowLight.prototype, "direction", null);
  34498. __decorate([
  34499. BABYLON.serialize()
  34500. ], ShadowLight.prototype, "shadowMinZ", null);
  34501. __decorate([
  34502. BABYLON.serialize()
  34503. ], ShadowLight.prototype, "shadowMaxZ", null);
  34504. BABYLON.ShadowLight = ShadowLight;
  34505. })(BABYLON || (BABYLON = {}));
  34506. //# sourceMappingURL=babylon.shadowLight.js.map
  34507. var BABYLON;
  34508. (function (BABYLON) {
  34509. var PointLight = (function (_super) {
  34510. __extends(PointLight, _super);
  34511. /**
  34512. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  34513. * A PointLight emits the light in every direction.
  34514. * It can cast shadows.
  34515. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  34516. * ```javascript
  34517. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  34518. * ```
  34519. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34520. */
  34521. function PointLight(name, position, scene) {
  34522. var _this = _super.call(this, name, scene) || this;
  34523. _this._shadowAngle = Math.PI / 2;
  34524. _this.position = position;
  34525. return _this;
  34526. }
  34527. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  34528. /**
  34529. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34530. * This specifies what angle the shadow will use to be created.
  34531. *
  34532. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34533. */
  34534. get: function () {
  34535. return this._shadowAngle;
  34536. },
  34537. /**
  34538. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34539. * This specifies what angle the shadow will use to be created.
  34540. *
  34541. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34542. */
  34543. set: function (value) {
  34544. this._shadowAngle = value;
  34545. this.forceProjectionMatrixCompute();
  34546. },
  34547. enumerable: true,
  34548. configurable: true
  34549. });
  34550. Object.defineProperty(PointLight.prototype, "direction", {
  34551. get: function () {
  34552. return this._direction;
  34553. },
  34554. /**
  34555. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34556. */
  34557. set: function (value) {
  34558. var previousNeedCube = this.needCube();
  34559. this._direction = value;
  34560. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34561. this._shadowGenerator.recreateShadowMap();
  34562. }
  34563. },
  34564. enumerable: true,
  34565. configurable: true
  34566. });
  34567. /**
  34568. * Returns the string "PointLight"
  34569. */
  34570. PointLight.prototype.getClassName = function () {
  34571. return "PointLight";
  34572. };
  34573. /**
  34574. * Returns the integer 0.
  34575. */
  34576. PointLight.prototype.getTypeID = function () {
  34577. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34578. };
  34579. /**
  34580. * Specifies wether or not the shadowmap should be a cube texture.
  34581. */
  34582. PointLight.prototype.needCube = function () {
  34583. return !this.direction;
  34584. };
  34585. /**
  34586. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34587. */
  34588. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34589. if (this.direction) {
  34590. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34591. }
  34592. else {
  34593. switch (faceIndex) {
  34594. case 0:
  34595. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34596. case 1:
  34597. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34598. case 2:
  34599. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34600. case 3:
  34601. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34602. case 4:
  34603. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34604. case 5:
  34605. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34606. }
  34607. }
  34608. return BABYLON.Vector3.Zero();
  34609. };
  34610. /**
  34611. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34612. * - fov = PI / 2
  34613. * - aspect ratio : 1.0
  34614. * - z-near and far equal to the active camera minZ and maxZ.
  34615. * Returns the PointLight.
  34616. */
  34617. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34618. var activeCamera = this.getScene().activeCamera;
  34619. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34620. };
  34621. PointLight.prototype._buildUniformLayout = function () {
  34622. this._uniformBuffer.addUniform("vLightData", 4);
  34623. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34624. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34625. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34626. this._uniformBuffer.addUniform("depthValues", 2);
  34627. this._uniformBuffer.create();
  34628. };
  34629. /**
  34630. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34631. * Returns the PointLight.
  34632. */
  34633. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34634. if (this.computeTransformedInformation()) {
  34635. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34636. return this;
  34637. }
  34638. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34639. return this;
  34640. };
  34641. return PointLight;
  34642. }(BABYLON.ShadowLight));
  34643. __decorate([
  34644. BABYLON.serialize()
  34645. ], PointLight.prototype, "shadowAngle", null);
  34646. BABYLON.PointLight = PointLight;
  34647. })(BABYLON || (BABYLON = {}));
  34648. //# sourceMappingURL=babylon.pointLight.js.map
  34649. /// <reference path="babylon.light.ts" />
  34650. var BABYLON;
  34651. (function (BABYLON) {
  34652. var DirectionalLight = (function (_super) {
  34653. __extends(DirectionalLight, _super);
  34654. /**
  34655. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34656. * The directional light is emitted from everywhere in the given direction.
  34657. * It can cast shawdows.
  34658. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34659. */
  34660. function DirectionalLight(name, direction, scene) {
  34661. var _this = _super.call(this, name, scene) || this;
  34662. _this._shadowFrustumSize = 0;
  34663. _this._shadowOrthoScale = 0.5;
  34664. _this.autoUpdateExtends = true;
  34665. // Cache
  34666. _this._orthoLeft = Number.MAX_VALUE;
  34667. _this._orthoRight = Number.MIN_VALUE;
  34668. _this._orthoTop = Number.MIN_VALUE;
  34669. _this._orthoBottom = Number.MAX_VALUE;
  34670. _this.position = direction.scale(-1.0);
  34671. _this.direction = direction;
  34672. return _this;
  34673. }
  34674. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34675. /**
  34676. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34677. */
  34678. get: function () {
  34679. return this._shadowFrustumSize;
  34680. },
  34681. /**
  34682. * Specifies a fix frustum size for the shadow generation.
  34683. */
  34684. set: function (value) {
  34685. this._shadowFrustumSize = value;
  34686. this.forceProjectionMatrixCompute();
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34692. get: function () {
  34693. return this._shadowOrthoScale;
  34694. },
  34695. set: function (value) {
  34696. this._shadowOrthoScale = value;
  34697. this.forceProjectionMatrixCompute();
  34698. },
  34699. enumerable: true,
  34700. configurable: true
  34701. });
  34702. /**
  34703. * Returns the string "DirectionalLight".
  34704. */
  34705. DirectionalLight.prototype.getClassName = function () {
  34706. return "DirectionalLight";
  34707. };
  34708. /**
  34709. * Returns the integer 1.
  34710. */
  34711. DirectionalLight.prototype.getTypeID = function () {
  34712. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34713. };
  34714. /**
  34715. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34716. * Returns the DirectionalLight Shadow projection matrix.
  34717. */
  34718. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34719. if (this.shadowFrustumSize > 0) {
  34720. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34721. }
  34722. else {
  34723. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34724. }
  34725. };
  34726. /**
  34727. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34728. * Returns the DirectionalLight Shadow projection matrix.
  34729. */
  34730. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34731. var activeCamera = this.getScene().activeCamera;
  34732. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34733. };
  34734. /**
  34735. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34736. * Returns the DirectionalLight Shadow projection matrix.
  34737. */
  34738. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34739. var activeCamera = this.getScene().activeCamera;
  34740. // Check extends
  34741. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34742. var tempVector3 = BABYLON.Vector3.Zero();
  34743. this._orthoLeft = Number.MAX_VALUE;
  34744. this._orthoRight = Number.MIN_VALUE;
  34745. this._orthoTop = Number.MIN_VALUE;
  34746. this._orthoBottom = Number.MAX_VALUE;
  34747. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34748. var mesh = renderList[meshIndex];
  34749. if (!mesh) {
  34750. continue;
  34751. }
  34752. var boundingInfo = mesh.getBoundingInfo();
  34753. if (!boundingInfo) {
  34754. continue;
  34755. }
  34756. var boundingBox = boundingInfo.boundingBox;
  34757. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34758. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34759. if (tempVector3.x < this._orthoLeft)
  34760. this._orthoLeft = tempVector3.x;
  34761. if (tempVector3.y < this._orthoBottom)
  34762. this._orthoBottom = tempVector3.y;
  34763. if (tempVector3.x > this._orthoRight)
  34764. this._orthoRight = tempVector3.x;
  34765. if (tempVector3.y > this._orthoTop)
  34766. this._orthoTop = tempVector3.y;
  34767. }
  34768. }
  34769. }
  34770. var xOffset = this._orthoRight - this._orthoLeft;
  34771. var yOffset = this._orthoTop - this._orthoBottom;
  34772. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34773. };
  34774. DirectionalLight.prototype._buildUniformLayout = function () {
  34775. this._uniformBuffer.addUniform("vLightData", 4);
  34776. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34777. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34778. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34779. this._uniformBuffer.addUniform("depthValues", 2);
  34780. this._uniformBuffer.create();
  34781. };
  34782. /**
  34783. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34784. * Returns the DirectionalLight.
  34785. */
  34786. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34787. if (this.computeTransformedInformation()) {
  34788. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34789. return this;
  34790. }
  34791. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34792. return this;
  34793. };
  34794. /**
  34795. * Gets the minZ used for shadow according to both the scene and the light.
  34796. *
  34797. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34798. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34799. * @param activeCamera
  34800. */
  34801. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34802. return 1;
  34803. };
  34804. /**
  34805. * Gets the maxZ used for shadow according to both the scene and the light.
  34806. *
  34807. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34808. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34809. * @param activeCamera
  34810. */
  34811. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34812. return 1;
  34813. };
  34814. return DirectionalLight;
  34815. }(BABYLON.ShadowLight));
  34816. __decorate([
  34817. BABYLON.serialize()
  34818. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34819. __decorate([
  34820. BABYLON.serialize()
  34821. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34822. __decorate([
  34823. BABYLON.serialize()
  34824. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34825. BABYLON.DirectionalLight = DirectionalLight;
  34826. })(BABYLON || (BABYLON = {}));
  34827. //# sourceMappingURL=babylon.directionalLight.js.map
  34828. var BABYLON;
  34829. (function (BABYLON) {
  34830. var SpotLight = (function (_super) {
  34831. __extends(SpotLight, _super);
  34832. /**
  34833. * Creates a SpotLight object in the scene with the passed parameters :
  34834. * - `position` (Vector3) is the initial SpotLight position,
  34835. * - `direction` (Vector3) is the initial SpotLight direction,
  34836. * - `angle` (float, in radians) is the spot light cone angle,
  34837. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34838. * A spot light is a simply light oriented cone.
  34839. * It can cast shadows.
  34840. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34841. */
  34842. function SpotLight(name, position, direction, angle, exponent, scene) {
  34843. var _this = _super.call(this, name, scene) || this;
  34844. _this.position = position;
  34845. _this.direction = direction;
  34846. _this.angle = angle;
  34847. _this.exponent = exponent;
  34848. return _this;
  34849. }
  34850. Object.defineProperty(SpotLight.prototype, "angle", {
  34851. get: function () {
  34852. return this._angle;
  34853. },
  34854. set: function (value) {
  34855. this._angle = value;
  34856. this.forceProjectionMatrixCompute();
  34857. },
  34858. enumerable: true,
  34859. configurable: true
  34860. });
  34861. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34862. get: function () {
  34863. return this._shadowAngleScale;
  34864. },
  34865. /**
  34866. * Allows scaling the angle of the light for shadow generation only.
  34867. */
  34868. set: function (value) {
  34869. this._shadowAngleScale = value;
  34870. this.forceProjectionMatrixCompute();
  34871. },
  34872. enumerable: true,
  34873. configurable: true
  34874. });
  34875. /**
  34876. * Returns the string "SpotLight".
  34877. */
  34878. SpotLight.prototype.getClassName = function () {
  34879. return "SpotLight";
  34880. };
  34881. /**
  34882. * Returns the integer 2.
  34883. */
  34884. SpotLight.prototype.getTypeID = function () {
  34885. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34886. };
  34887. /**
  34888. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  34889. * Returns the SpotLight.
  34890. */
  34891. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34892. var activeCamera = this.getScene().activeCamera;
  34893. this._shadowAngleScale = this._shadowAngleScale || 1;
  34894. var angle = this._shadowAngleScale * this._angle;
  34895. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34896. };
  34897. SpotLight.prototype._buildUniformLayout = function () {
  34898. this._uniformBuffer.addUniform("vLightData", 4);
  34899. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34900. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34901. this._uniformBuffer.addUniform("vLightDirection", 3);
  34902. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34903. this._uniformBuffer.addUniform("depthValues", 2);
  34904. this._uniformBuffer.create();
  34905. };
  34906. /**
  34907. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34908. * Return the SpotLight.
  34909. */
  34910. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34911. var normalizeDirection;
  34912. if (this.computeTransformedInformation()) {
  34913. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34914. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34915. }
  34916. else {
  34917. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34918. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34919. }
  34920. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34921. return this;
  34922. };
  34923. return SpotLight;
  34924. }(BABYLON.ShadowLight));
  34925. __decorate([
  34926. BABYLON.serialize()
  34927. ], SpotLight.prototype, "angle", null);
  34928. __decorate([
  34929. BABYLON.serialize()
  34930. /**
  34931. * Allows scaling the angle of the light for shadow generation only.
  34932. */
  34933. ], SpotLight.prototype, "shadowAngleScale", null);
  34934. __decorate([
  34935. BABYLON.serialize()
  34936. ], SpotLight.prototype, "exponent", void 0);
  34937. BABYLON.SpotLight = SpotLight;
  34938. })(BABYLON || (BABYLON = {}));
  34939. //# sourceMappingURL=babylon.spotLight.js.map
  34940. var BABYLON;
  34941. (function (BABYLON) {
  34942. var MultiMaterial = (function (_super) {
  34943. __extends(MultiMaterial, _super);
  34944. function MultiMaterial(name, scene) {
  34945. var _this = _super.call(this, name, scene, true) || this;
  34946. scene.multiMaterials.push(_this);
  34947. _this.subMaterials = new Array();
  34948. return _this;
  34949. }
  34950. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  34951. get: function () {
  34952. return this._subMaterials;
  34953. },
  34954. set: function (value) {
  34955. this._subMaterials = value;
  34956. this._hookArray(value);
  34957. },
  34958. enumerable: true,
  34959. configurable: true
  34960. });
  34961. MultiMaterial.prototype._hookArray = function (array) {
  34962. var _this = this;
  34963. var oldPush = array.push;
  34964. array.push = function () {
  34965. var items = [];
  34966. for (var _i = 0; _i < arguments.length; _i++) {
  34967. items[_i] = arguments[_i];
  34968. }
  34969. var result = oldPush.apply(array, items);
  34970. _this._markAllSubMeshesAsTexturesDirty();
  34971. return result;
  34972. };
  34973. var oldSplice = array.splice;
  34974. array.splice = function (index, deleteCount) {
  34975. var deleted = oldSplice.apply(array, [index, deleteCount]);
  34976. _this._markAllSubMeshesAsTexturesDirty();
  34977. return deleted;
  34978. };
  34979. };
  34980. // Properties
  34981. MultiMaterial.prototype.getSubMaterial = function (index) {
  34982. if (index < 0 || index >= this.subMaterials.length) {
  34983. return this.getScene().defaultMaterial;
  34984. }
  34985. return this.subMaterials[index];
  34986. };
  34987. MultiMaterial.prototype.getActiveTextures = function () {
  34988. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  34989. var _a;
  34990. };
  34991. // Methods
  34992. MultiMaterial.prototype.getClassName = function () {
  34993. return "MultiMaterial";
  34994. };
  34995. MultiMaterial.prototype.isReady = function (mesh) {
  34996. for (var index = 0; index < this.subMaterials.length; index++) {
  34997. var subMaterial = this.subMaterials[index];
  34998. if (subMaterial) {
  34999. if (!this.subMaterials[index].isReady(mesh)) {
  35000. return false;
  35001. }
  35002. }
  35003. }
  35004. return true;
  35005. };
  35006. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  35007. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  35008. for (var index = 0; index < this.subMaterials.length; index++) {
  35009. var subMaterial = null;
  35010. if (cloneChildren) {
  35011. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  35012. }
  35013. else {
  35014. subMaterial = this.subMaterials[index];
  35015. }
  35016. newMultiMaterial.subMaterials.push(subMaterial);
  35017. }
  35018. return newMultiMaterial;
  35019. };
  35020. MultiMaterial.prototype.serialize = function () {
  35021. var serializationObject = {};
  35022. serializationObject.name = this.name;
  35023. serializationObject.id = this.id;
  35024. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35025. serializationObject.materials = [];
  35026. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  35027. var subMat = this.subMaterials[matIndex];
  35028. if (subMat) {
  35029. serializationObject.materials.push(subMat.id);
  35030. }
  35031. else {
  35032. serializationObject.materials.push(null);
  35033. }
  35034. }
  35035. return serializationObject;
  35036. };
  35037. return MultiMaterial;
  35038. }(BABYLON.Material));
  35039. BABYLON.MultiMaterial = MultiMaterial;
  35040. })(BABYLON || (BABYLON = {}));
  35041. //# sourceMappingURL=babylon.multiMaterial.js.map
  35042. var BABYLON;
  35043. (function (BABYLON) {
  35044. var PBRMaterialDefines = (function (_super) {
  35045. __extends(PBRMaterialDefines, _super);
  35046. function PBRMaterialDefines() {
  35047. var _this = _super.call(this) || this;
  35048. _this.PBR = true;
  35049. _this.MAINUV1 = false;
  35050. _this.MAINUV2 = false;
  35051. _this.UV1 = false;
  35052. _this.UV2 = false;
  35053. _this.ALBEDO = false;
  35054. _this.ALBEDODIRECTUV = 0;
  35055. _this.VERTEXCOLOR = false;
  35056. _this.AMBIENT = false;
  35057. _this.AMBIENTDIRECTUV = 0;
  35058. _this.AMBIENTINGRAYSCALE = false;
  35059. _this.OPACITY = false;
  35060. _this.VERTEXALPHA = false;
  35061. _this.OPACITYDIRECTUV = 0;
  35062. _this.OPACITYRGB = false;
  35063. _this.ALPHATEST = false;
  35064. _this.ALPHABLEND = false;
  35065. _this.ALPHAFROMALBEDO = false;
  35066. _this.ALPHATESTVALUE = 0.5;
  35067. _this.SPECULAROVERALPHA = false;
  35068. _this.RADIANCEOVERALPHA = false;
  35069. _this.ALPHAFRESNEL = false;
  35070. _this.PREMULTIPLYALPHA = false;
  35071. _this.EMISSIVE = false;
  35072. _this.EMISSIVEDIRECTUV = 0;
  35073. _this.REFLECTIVITY = false;
  35074. _this.REFLECTIVITYDIRECTUV = 0;
  35075. _this.SPECULARTERM = false;
  35076. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  35077. _this.MICROSURFACEAUTOMATIC = false;
  35078. _this.LODBASEDMICROSFURACE = false;
  35079. _this.MICROSURFACEMAP = false;
  35080. _this.MICROSURFACEMAPDIRECTUV = 0;
  35081. _this.METALLICWORKFLOW = false;
  35082. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  35083. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  35084. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  35085. _this.AOSTOREINMETALMAPRED = false;
  35086. _this.ENVIRONMENTBRDF = false;
  35087. _this.NORMAL = false;
  35088. _this.TANGENT = false;
  35089. _this.BUMP = false;
  35090. _this.BUMPDIRECTUV = 0;
  35091. _this.PARALLAX = false;
  35092. _this.PARALLAXOCCLUSION = false;
  35093. _this.INVERTNORMALMAPX = false;
  35094. _this.INVERTNORMALMAPY = false;
  35095. _this.NORMALXYSCALE = true;
  35096. _this.LIGHTMAP = false;
  35097. _this.LIGHTMAPDIRECTUV = 0;
  35098. _this.USELIGHTMAPASSHADOWMAP = false;
  35099. _this.REFLECTION = false;
  35100. _this.REFLECTIONMAP_3D = false;
  35101. _this.REFLECTIONMAP_SPHERICAL = false;
  35102. _this.REFLECTIONMAP_PLANAR = false;
  35103. _this.REFLECTIONMAP_CUBIC = false;
  35104. _this.REFLECTIONMAP_PROJECTION = false;
  35105. _this.REFLECTIONMAP_SKYBOX = false;
  35106. _this.REFLECTIONMAP_EXPLICIT = false;
  35107. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35108. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35109. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35110. _this.INVERTCUBICMAP = false;
  35111. _this.USESPHERICALFROMREFLECTIONMAP = false;
  35112. _this.USESPHERICALINFRAGMENT = false;
  35113. _this.REFLECTIONMAP_OPPOSITEZ = false;
  35114. _this.LODINREFLECTIONALPHA = false;
  35115. _this.GAMMAREFLECTION = false;
  35116. _this.REFRACTION = false;
  35117. _this.REFRACTIONMAP_3D = false;
  35118. _this.REFRACTIONMAP_OPPOSITEZ = false;
  35119. _this.LODINREFRACTIONALPHA = false;
  35120. _this.GAMMAREFRACTION = false;
  35121. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  35122. _this.INSTANCES = false;
  35123. _this.NUM_BONE_INFLUENCERS = 0;
  35124. _this.BonesPerMesh = 0;
  35125. _this.MORPHTARGETS = false;
  35126. _this.MORPHTARGETS_NORMAL = false;
  35127. _this.MORPHTARGETS_TANGENT = false;
  35128. _this.NUM_MORPH_INFLUENCERS = 0;
  35129. _this.IMAGEPROCESSING = false;
  35130. _this.VIGNETTE = false;
  35131. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35132. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35133. _this.TONEMAPPING = false;
  35134. _this.CONTRAST = false;
  35135. _this.COLORCURVES = false;
  35136. _this.COLORGRADING = false;
  35137. _this.SAMPLER3DGREENDEPTH = false;
  35138. _this.SAMPLER3DBGRMAP = false;
  35139. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35140. _this.EXPOSURE = false;
  35141. _this.USEPHYSICALLIGHTFALLOFF = false;
  35142. _this.TWOSIDEDLIGHTING = false;
  35143. _this.SHADOWFLOAT = false;
  35144. _this.USERIGHTHANDEDSYSTEM = false;
  35145. _this.CLIPPLANE = false;
  35146. _this.POINTSIZE = false;
  35147. _this.FOG = false;
  35148. _this.LOGARITHMICDEPTH = false;
  35149. _this.rebuild();
  35150. return _this;
  35151. }
  35152. PBRMaterialDefines.prototype.reset = function () {
  35153. _super.prototype.reset.call(this);
  35154. this.ALPHATESTVALUE = 0.5;
  35155. this.PBR = true;
  35156. };
  35157. return PBRMaterialDefines;
  35158. }(BABYLON.MaterialDefines));
  35159. /**
  35160. * The Physically based material base class of BJS.
  35161. *
  35162. * This offers the main features of a standard PBR material.
  35163. * For more information, please refer to the documentation :
  35164. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35165. */
  35166. var PBRBaseMaterial = (function (_super) {
  35167. __extends(PBRBaseMaterial, _super);
  35168. /**
  35169. * Instantiates a new PBRMaterial instance.
  35170. *
  35171. * @param name The material name
  35172. * @param scene The scene the material will be use in.
  35173. */
  35174. function PBRBaseMaterial(name, scene) {
  35175. var _this = _super.call(this, name, scene) || this;
  35176. /**
  35177. * Intensity of the direct lights e.g. the four lights available in your scene.
  35178. * This impacts both the direct diffuse and specular highlights.
  35179. */
  35180. _this._directIntensity = 1.0;
  35181. /**
  35182. * Intensity of the emissive part of the material.
  35183. * This helps controlling the emissive effect without modifying the emissive color.
  35184. */
  35185. _this._emissiveIntensity = 1.0;
  35186. /**
  35187. * Intensity of the environment e.g. how much the environment will light the object
  35188. * either through harmonics for rough material or through the refelction for shiny ones.
  35189. */
  35190. _this._environmentIntensity = 1.0;
  35191. /**
  35192. * This is a special control allowing the reduction of the specular highlights coming from the
  35193. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35194. */
  35195. _this._specularIntensity = 1.0;
  35196. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  35197. /**
  35198. * Debug Control allowing disabling the bump map on this material.
  35199. */
  35200. _this._disableBumpMap = false;
  35201. /**
  35202. * AKA Occlusion Texture Intensity in other nomenclature.
  35203. */
  35204. _this._ambientTextureStrength = 1.0;
  35205. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  35206. /**
  35207. * AKA Diffuse Color in other nomenclature.
  35208. */
  35209. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  35210. /**
  35211. * AKA Specular Color in other nomenclature.
  35212. */
  35213. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35214. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  35215. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  35216. /**
  35217. * AKA Glossiness in other nomenclature.
  35218. */
  35219. _this._microSurface = 0.9;
  35220. /**
  35221. * source material index of refraction (IOR)' / 'destination material IOR.
  35222. */
  35223. _this._indexOfRefraction = 0.66;
  35224. /**
  35225. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35226. */
  35227. _this._invertRefractionY = false;
  35228. /**
  35229. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35230. * Materials half opaque for instance using refraction could benefit from this control.
  35231. */
  35232. _this._linkRefractionWithTransparency = false;
  35233. _this._useLightmapAsShadowmap = false;
  35234. /**
  35235. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35236. */
  35237. _this._useAlphaFromAlbedoTexture = false;
  35238. /**
  35239. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35240. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35241. */
  35242. _this._useSpecularOverAlpha = true;
  35243. /**
  35244. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35245. */
  35246. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  35247. /**
  35248. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35249. */
  35250. _this._useRoughnessFromMetallicTextureAlpha = true;
  35251. /**
  35252. * Specifies if the metallic texture contains the roughness information in its green channel.
  35253. */
  35254. _this._useRoughnessFromMetallicTextureGreen = false;
  35255. /**
  35256. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35257. */
  35258. _this._useMetallnessFromMetallicTextureBlue = false;
  35259. /**
  35260. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35261. */
  35262. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  35263. /**
  35264. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35265. */
  35266. _this._useAmbientInGrayScale = false;
  35267. /**
  35268. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35269. * The material will try to infer what glossiness each pixel should be.
  35270. */
  35271. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  35272. /**
  35273. * BJS is using an harcoded light falloff based on a manually sets up range.
  35274. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35275. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35276. */
  35277. _this._usePhysicalLightFalloff = true;
  35278. /**
  35279. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35280. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35281. */
  35282. _this._useRadianceOverAlpha = true;
  35283. /**
  35284. * Allows using the bump map in parallax mode.
  35285. */
  35286. _this._useParallax = false;
  35287. /**
  35288. * Allows using the bump map in parallax occlusion mode.
  35289. */
  35290. _this._useParallaxOcclusion = false;
  35291. /**
  35292. * Controls the scale bias of the parallax mode.
  35293. */
  35294. _this._parallaxScaleBias = 0.05;
  35295. /**
  35296. * If sets to true, disables all the lights affecting the material.
  35297. */
  35298. _this._disableLighting = false;
  35299. /**
  35300. * Number of Simultaneous lights allowed on the material.
  35301. */
  35302. _this._maxSimultaneousLights = 4;
  35303. /**
  35304. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35305. */
  35306. _this._invertNormalMapX = false;
  35307. /**
  35308. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35309. */
  35310. _this._invertNormalMapY = false;
  35311. /**
  35312. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35313. */
  35314. _this._twoSidedLighting = false;
  35315. /**
  35316. * Defines the alpha limits in alpha test mode.
  35317. */
  35318. _this._alphaCutOff = 0.4;
  35319. /**
  35320. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35321. */
  35322. _this._forceAlphaTest = false;
  35323. /**
  35324. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  35325. * in your scene composition.
  35326. */
  35327. _this._premultiplyAlpha = false;
  35328. /**
  35329. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35330. * And/Or occlude the blended part.
  35331. */
  35332. _this._useAlphaFresnel = false;
  35333. /**
  35334. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35335. * from cos thetav and roughness:
  35336. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35337. */
  35338. _this._environmentBRDFTexture = null;
  35339. _this._renderTargets = new BABYLON.SmartArray(16);
  35340. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35341. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35342. _this._tempColor = new BABYLON.Color3();
  35343. // Setup the default processing configuration to the scene.
  35344. _this._attachImageProcessingConfiguration(null);
  35345. _this.getRenderTargetTextures = function () {
  35346. _this._renderTargets.reset();
  35347. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35348. _this._renderTargets.push(_this._reflectionTexture);
  35349. }
  35350. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35351. _this._renderTargets.push(_this._refractionTexture);
  35352. }
  35353. return _this._renderTargets;
  35354. };
  35355. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35356. return _this;
  35357. }
  35358. /**
  35359. * Attaches a new image processing configuration to the PBR Material.
  35360. * @param configuration
  35361. */
  35362. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35363. var _this = this;
  35364. if (configuration === this._imageProcessingConfiguration) {
  35365. return;
  35366. }
  35367. // Detaches observer.
  35368. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35369. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35370. }
  35371. // Pick the scene configuration if needed.
  35372. if (!configuration) {
  35373. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35374. }
  35375. else {
  35376. this._imageProcessingConfiguration = configuration;
  35377. }
  35378. // Attaches observer.
  35379. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35380. _this._markAllSubMeshesAsImageProcessingDirty();
  35381. });
  35382. };
  35383. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35384. get: function () {
  35385. return this._useLogarithmicDepth;
  35386. },
  35387. set: function (value) {
  35388. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35389. },
  35390. enumerable: true,
  35391. configurable: true
  35392. });
  35393. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35394. if (this._linkRefractionWithTransparency) {
  35395. return false;
  35396. }
  35397. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35398. };
  35399. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35400. if (this._forceAlphaTest) {
  35401. return true;
  35402. }
  35403. if (this._linkRefractionWithTransparency) {
  35404. return false;
  35405. }
  35406. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  35407. };
  35408. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35409. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  35410. };
  35411. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35412. return this._albedoTexture;
  35413. };
  35414. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35415. if (this.isFrozen) {
  35416. if (this._wasPreviouslyReady) {
  35417. return true;
  35418. }
  35419. }
  35420. if (!subMesh._materialDefines) {
  35421. subMesh._materialDefines = new PBRMaterialDefines();
  35422. }
  35423. var scene = this.getScene();
  35424. var defines = subMesh._materialDefines;
  35425. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35426. if (defines._renderId === scene.getRenderId()) {
  35427. return true;
  35428. }
  35429. }
  35430. var engine = scene.getEngine();
  35431. // Lights
  35432. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35433. defines._needNormals = true;
  35434. // Textures
  35435. if (defines._areTexturesDirty) {
  35436. defines._needUVs = false;
  35437. if (scene.texturesEnabled) {
  35438. if (scene.getEngine().getCaps().textureLOD) {
  35439. defines.LODBASEDMICROSFURACE = true;
  35440. }
  35441. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35442. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35443. return false;
  35444. }
  35445. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35446. }
  35447. else {
  35448. defines.ALBEDO = false;
  35449. }
  35450. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35451. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35452. return false;
  35453. }
  35454. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35455. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35456. }
  35457. else {
  35458. defines.AMBIENT = false;
  35459. }
  35460. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35461. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35462. return false;
  35463. }
  35464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35465. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35466. }
  35467. else {
  35468. defines.OPACITY = false;
  35469. }
  35470. var reflectionTexture = this._getReflectionTexture();
  35471. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35472. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35473. return false;
  35474. }
  35475. defines.REFLECTION = true;
  35476. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35477. defines.REFLECTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35478. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35479. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35480. defines.INVERTCUBICMAP = true;
  35481. }
  35482. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35483. switch (reflectionTexture.coordinatesMode) {
  35484. case BABYLON.Texture.CUBIC_MODE:
  35485. case BABYLON.Texture.INVCUBIC_MODE:
  35486. defines.REFLECTIONMAP_CUBIC = true;
  35487. break;
  35488. case BABYLON.Texture.EXPLICIT_MODE:
  35489. defines.REFLECTIONMAP_EXPLICIT = true;
  35490. break;
  35491. case BABYLON.Texture.PLANAR_MODE:
  35492. defines.REFLECTIONMAP_PLANAR = true;
  35493. break;
  35494. case BABYLON.Texture.PROJECTION_MODE:
  35495. defines.REFLECTIONMAP_PROJECTION = true;
  35496. break;
  35497. case BABYLON.Texture.SKYBOX_MODE:
  35498. defines.REFLECTIONMAP_SKYBOX = true;
  35499. break;
  35500. case BABYLON.Texture.SPHERICAL_MODE:
  35501. defines.REFLECTIONMAP_SPHERICAL = true;
  35502. break;
  35503. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35504. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35505. break;
  35506. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35507. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35508. break;
  35509. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35510. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35511. break;
  35512. }
  35513. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35514. if (reflectionTexture.sphericalPolynomial) {
  35515. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35516. if (scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35517. defines.USESPHERICALINFRAGMENT = true;
  35518. }
  35519. }
  35520. }
  35521. }
  35522. else {
  35523. defines.REFLECTION = false;
  35524. defines.REFLECTIONMAP_3D = false;
  35525. defines.REFLECTIONMAP_SPHERICAL = false;
  35526. defines.REFLECTIONMAP_PLANAR = false;
  35527. defines.REFLECTIONMAP_CUBIC = false;
  35528. defines.REFLECTIONMAP_PROJECTION = false;
  35529. defines.REFLECTIONMAP_SKYBOX = false;
  35530. defines.REFLECTIONMAP_EXPLICIT = false;
  35531. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35532. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35533. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35534. defines.INVERTCUBICMAP = false;
  35535. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35536. defines.USESPHERICALINFRAGMENT = false;
  35537. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35538. defines.LODINREFLECTIONALPHA = false;
  35539. defines.GAMMAREFLECTION = false;
  35540. }
  35541. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35542. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35543. return false;
  35544. }
  35545. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35546. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35547. }
  35548. else {
  35549. defines.LIGHTMAP = false;
  35550. }
  35551. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35552. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35553. return false;
  35554. }
  35555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35556. }
  35557. else {
  35558. defines.EMISSIVE = false;
  35559. }
  35560. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35561. if (this._metallicTexture) {
  35562. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35563. return false;
  35564. }
  35565. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35566. defines.METALLICWORKFLOW = true;
  35567. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35568. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35569. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35570. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35571. }
  35572. else if (this._reflectivityTexture) {
  35573. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35574. return false;
  35575. }
  35576. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35577. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35578. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35579. }
  35580. else {
  35581. defines.REFLECTIVITY = false;
  35582. }
  35583. if (this._microSurfaceTexture) {
  35584. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35585. return false;
  35586. }
  35587. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35588. }
  35589. else {
  35590. defines.MICROSURFACEMAP = false;
  35591. }
  35592. }
  35593. else {
  35594. defines.REFLECTIVITY = false;
  35595. defines.MICROSURFACEMAP = false;
  35596. }
  35597. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35598. // Bump texure can not be none blocking.
  35599. if (!this._bumpTexture.isReady()) {
  35600. return false;
  35601. }
  35602. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35603. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35604. defines.PARALLAX = true;
  35605. if (this._useParallaxOcclusion) {
  35606. defines.PARALLAXOCCLUSION = true;
  35607. }
  35608. }
  35609. if (this._invertNormalMapX) {
  35610. defines.INVERTNORMALMAPX = true;
  35611. }
  35612. if (this._invertNormalMapY) {
  35613. defines.INVERTNORMALMAPY = true;
  35614. }
  35615. if (scene._mirroredCameraPosition) {
  35616. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  35617. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  35618. }
  35619. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  35620. }
  35621. else {
  35622. defines.BUMP = false;
  35623. }
  35624. var refractionTexture = this._getRefractionTexture();
  35625. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35626. if (!refractionTexture.isReadyOrNotBlocking()) {
  35627. return false;
  35628. }
  35629. defines.REFRACTION = true;
  35630. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35631. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35632. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35633. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35634. if (this._linkRefractionWithTransparency) {
  35635. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35636. }
  35637. }
  35638. else {
  35639. defines.REFRACTION = false;
  35640. }
  35641. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35642. // This is blocking.
  35643. if (!this._environmentBRDFTexture.isReady()) {
  35644. return false;
  35645. }
  35646. defines.ENVIRONMENTBRDF = true;
  35647. }
  35648. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35649. defines.ALPHAFROMALBEDO = true;
  35650. }
  35651. }
  35652. if (this._useSpecularOverAlpha) {
  35653. defines.SPECULAROVERALPHA = true;
  35654. }
  35655. if (this._usePhysicalLightFalloff) {
  35656. defines.USEPHYSICALLIGHTFALLOFF = true;
  35657. }
  35658. if (this._useRadianceOverAlpha) {
  35659. defines.RADIANCEOVERALPHA = true;
  35660. }
  35661. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35662. defines.METALLICWORKFLOW = true;
  35663. }
  35664. if (!this.backFaceCulling && this._twoSidedLighting) {
  35665. defines.TWOSIDEDLIGHTING = true;
  35666. }
  35667. defines.ALPHATESTVALUE = this._alphaCutOff;
  35668. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  35669. defines.ALPHABLEND = this.needAlphaBlending();
  35670. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35671. }
  35672. if (defines._areImageProcessingDirty) {
  35673. if (!this._imageProcessingConfiguration.isReady()) {
  35674. return false;
  35675. }
  35676. this._imageProcessingConfiguration.prepareDefines(defines);
  35677. }
  35678. // Misc.
  35679. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35680. // Values that need to be evaluated on every frame
  35681. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  35682. // Attribs
  35683. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35684. if (mesh) {
  35685. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35686. mesh.createNormals(true);
  35687. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35688. }
  35689. }
  35690. }
  35691. // Get correct effect
  35692. if (defines.isDirty) {
  35693. defines.markAsProcessed();
  35694. scene.resetCachedMaterial();
  35695. // Fallbacks
  35696. var fallbacks = new BABYLON.EffectFallbacks();
  35697. if (defines.ENVIRONMENTBRDF) {
  35698. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  35699. }
  35700. if (defines.REFLECTION) {
  35701. fallbacks.addFallback(0, "REFLECTION");
  35702. }
  35703. if (defines.REFRACTION) {
  35704. fallbacks.addFallback(0, "REFRACTION");
  35705. }
  35706. if (defines.REFLECTIVITY) {
  35707. fallbacks.addFallback(0, "REFLECTIVITY");
  35708. }
  35709. if (defines.BUMP) {
  35710. fallbacks.addFallback(0, "BUMP");
  35711. }
  35712. if (defines.PARALLAX) {
  35713. fallbacks.addFallback(1, "PARALLAX");
  35714. }
  35715. if (defines.PARALLAXOCCLUSION) {
  35716. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35717. }
  35718. if (defines.SPECULAROVERALPHA) {
  35719. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35720. }
  35721. if (defines.FOG) {
  35722. fallbacks.addFallback(1, "FOG");
  35723. }
  35724. if (defines.POINTSIZE) {
  35725. fallbacks.addFallback(0, "POINTSIZE");
  35726. }
  35727. if (defines.LOGARITHMICDEPTH) {
  35728. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35729. }
  35730. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35731. if (defines.SPECULARTERM) {
  35732. fallbacks.addFallback(0, "SPECULARTERM");
  35733. }
  35734. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35735. fallbacks.addCPUSkinningFallback(0, mesh);
  35736. }
  35737. //Attributes
  35738. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35739. if (defines.NORMAL) {
  35740. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35741. }
  35742. if (defines.TANGENT) {
  35743. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35744. }
  35745. if (defines.UV1) {
  35746. attribs.push(BABYLON.VertexBuffer.UVKind);
  35747. }
  35748. if (defines.UV2) {
  35749. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35750. }
  35751. if (defines.VERTEXCOLOR) {
  35752. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35753. }
  35754. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35755. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35756. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35757. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35758. "vFogInfos", "vFogColor", "pointSize",
  35759. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35760. "mBones",
  35761. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35762. "vLightingIntensity",
  35763. "logarithmicDepthConstant",
  35764. "vSphericalX", "vSphericalY", "vSphericalZ",
  35765. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35766. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35767. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos"
  35768. ];
  35769. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35770. "bumpSampler", "lightmapSampler", "opacitySampler",
  35771. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35772. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35773. "microSurfaceSampler", "environmentBrdfSampler"];
  35774. var uniformBuffers = ["Material", "Scene"];
  35775. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35776. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35777. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35778. uniformsNames: uniforms,
  35779. uniformBuffersNames: uniformBuffers,
  35780. samplers: samplers,
  35781. defines: defines,
  35782. maxSimultaneousLights: this._maxSimultaneousLights
  35783. });
  35784. var onCompiled = function (effect) {
  35785. if (this.onCompiled) {
  35786. this.onCompiled(effect);
  35787. }
  35788. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35789. }.bind(this);
  35790. var join = defines.toString();
  35791. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35792. attributes: attribs,
  35793. uniformsNames: uniforms,
  35794. uniformBuffersNames: uniformBuffers,
  35795. samplers: samplers,
  35796. defines: join,
  35797. fallbacks: fallbacks,
  35798. onCompiled: onCompiled,
  35799. onError: this.onError,
  35800. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35801. }, engine), defines);
  35802. this.buildUniformLayout();
  35803. }
  35804. if (!subMesh.effect.isReady()) {
  35805. return false;
  35806. }
  35807. defines._renderId = scene.getRenderId();
  35808. this._wasPreviouslyReady = true;
  35809. return true;
  35810. };
  35811. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35812. // Order is important !
  35813. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35814. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35815. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35816. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35817. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35818. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35819. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35820. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35821. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35822. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35823. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35824. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35825. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35826. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35827. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35828. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35829. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35830. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35831. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35832. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35833. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35834. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35835. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35836. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35837. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35838. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35839. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35840. this._uniformBuffer.addUniform("pointSize", 1);
  35841. this._uniformBuffer.create();
  35842. };
  35843. PBRBaseMaterial.prototype.unbind = function () {
  35844. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35845. this._uniformBuffer.setTexture("reflectionSampler", null);
  35846. }
  35847. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35848. this._uniformBuffer.setTexture("refractionSampler", null);
  35849. }
  35850. _super.prototype.unbind.call(this);
  35851. };
  35852. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35853. this._activeEffect.setMatrix("world", world);
  35854. };
  35855. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35856. var scene = this.getScene();
  35857. var defines = subMesh._materialDefines;
  35858. if (!defines) {
  35859. return;
  35860. }
  35861. var effect = subMesh.effect;
  35862. this._activeEffect = effect;
  35863. // Matrices
  35864. this.bindOnlyWorldMatrix(world);
  35865. // Bones
  35866. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35867. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35868. this._uniformBuffer.bindToEffect(effect, "Material");
  35869. this.bindViewProjection(effect);
  35870. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35871. // Texture uniforms
  35872. if (scene.texturesEnabled) {
  35873. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35874. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35875. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35876. }
  35877. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35878. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35879. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35880. }
  35881. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35882. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35883. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35884. }
  35885. var reflectionTexture = this._getReflectionTexture();
  35886. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35887. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35888. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35889. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35890. var polynomials = reflectionTexture.sphericalPolynomial;
  35891. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35892. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35893. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35894. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35895. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35896. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35897. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35898. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35899. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35900. }
  35901. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35902. }
  35903. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35904. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35905. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35906. }
  35907. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35908. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35909. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35910. }
  35911. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35912. if (this._metallicTexture) {
  35913. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35914. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35915. }
  35916. else if (this._reflectivityTexture) {
  35917. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35918. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35919. }
  35920. if (this._microSurfaceTexture) {
  35921. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35922. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35923. }
  35924. }
  35925. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35926. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35927. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35928. }
  35929. var refractionTexture = this._getRefractionTexture();
  35930. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35931. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35932. var depth = 1.0;
  35933. if (!refractionTexture.isCube) {
  35934. if (refractionTexture.depth) {
  35935. depth = refractionTexture.depth;
  35936. }
  35937. }
  35938. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35939. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35940. }
  35941. }
  35942. // Point size
  35943. if (this.pointsCloud) {
  35944. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35945. }
  35946. // Colors
  35947. if (defines.METALLICWORKFLOW) {
  35948. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35949. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35950. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35951. }
  35952. else {
  35953. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35954. }
  35955. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35956. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35957. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35958. // Misc
  35959. this._lightingInfos.x = this._directIntensity;
  35960. this._lightingInfos.y = this._emissiveIntensity;
  35961. this._lightingInfos.z = this._environmentIntensity;
  35962. this._lightingInfos.w = this._specularIntensity;
  35963. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35964. }
  35965. // Textures
  35966. if (scene.texturesEnabled) {
  35967. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35968. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35969. }
  35970. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35971. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35972. }
  35973. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35974. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35975. }
  35976. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35977. if (defines.LODBASEDMICROSFURACE) {
  35978. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35979. }
  35980. else {
  35981. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35982. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35983. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35984. }
  35985. }
  35986. if (defines.ENVIRONMENTBRDF) {
  35987. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35988. }
  35989. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35990. if (defines.LODBASEDMICROSFURACE) {
  35991. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35992. }
  35993. else {
  35994. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35995. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35996. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35997. }
  35998. }
  35999. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36000. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  36001. }
  36002. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36003. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  36004. }
  36005. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36006. if (this._metallicTexture) {
  36007. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  36008. }
  36009. else if (this._reflectivityTexture) {
  36010. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  36011. }
  36012. if (this._microSurfaceTexture) {
  36013. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  36014. }
  36015. }
  36016. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36017. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  36018. }
  36019. }
  36020. // Clip plane
  36021. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  36022. // Colors
  36023. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  36024. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  36025. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  36026. }
  36027. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  36028. // Lights
  36029. if (scene.lightsEnabled && !this._disableLighting) {
  36030. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  36031. }
  36032. // View
  36033. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  36034. this.bindView(effect);
  36035. }
  36036. // Fog
  36037. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  36038. // Morph targets
  36039. if (defines.NUM_MORPH_INFLUENCERS) {
  36040. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  36041. }
  36042. // image processing
  36043. this._imageProcessingConfiguration.bind(this._activeEffect);
  36044. // Log. depth
  36045. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  36046. }
  36047. this._uniformBuffer.update();
  36048. this._afterBind(mesh);
  36049. scene = null;
  36050. };
  36051. PBRBaseMaterial.prototype.getAnimatables = function () {
  36052. var results = [];
  36053. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  36054. results.push(this._albedoTexture);
  36055. }
  36056. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  36057. results.push(this._ambientTexture);
  36058. }
  36059. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  36060. results.push(this._opacityTexture);
  36061. }
  36062. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  36063. results.push(this._reflectionTexture);
  36064. }
  36065. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  36066. results.push(this._emissiveTexture);
  36067. }
  36068. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  36069. results.push(this._metallicTexture);
  36070. }
  36071. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  36072. results.push(this._reflectivityTexture);
  36073. }
  36074. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  36075. results.push(this._bumpTexture);
  36076. }
  36077. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  36078. results.push(this._lightmapTexture);
  36079. }
  36080. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  36081. results.push(this._refractionTexture);
  36082. }
  36083. return results;
  36084. };
  36085. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  36086. if (this._reflectionTexture) {
  36087. return this._reflectionTexture;
  36088. }
  36089. return this.getScene().environmentTexture;
  36090. };
  36091. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  36092. if (this._refractionTexture) {
  36093. return this._refractionTexture;
  36094. }
  36095. if (this._linkRefractionWithTransparency) {
  36096. return this.getScene().environmentTexture;
  36097. }
  36098. return null;
  36099. };
  36100. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36101. if (forceDisposeTextures) {
  36102. if (this._albedoTexture) {
  36103. this._albedoTexture.dispose();
  36104. }
  36105. if (this._ambientTexture) {
  36106. this._ambientTexture.dispose();
  36107. }
  36108. if (this._opacityTexture) {
  36109. this._opacityTexture.dispose();
  36110. }
  36111. if (this._reflectionTexture) {
  36112. this._reflectionTexture.dispose();
  36113. }
  36114. if (this._environmentBRDFTexture) {
  36115. this._environmentBRDFTexture.dispose();
  36116. }
  36117. if (this._emissiveTexture) {
  36118. this._emissiveTexture.dispose();
  36119. }
  36120. if (this._metallicTexture) {
  36121. this._metallicTexture.dispose();
  36122. }
  36123. if (this._reflectivityTexture) {
  36124. this._reflectivityTexture.dispose();
  36125. }
  36126. if (this._bumpTexture) {
  36127. this._bumpTexture.dispose();
  36128. }
  36129. if (this._lightmapTexture) {
  36130. this._lightmapTexture.dispose();
  36131. }
  36132. if (this._refractionTexture) {
  36133. this._refractionTexture.dispose();
  36134. }
  36135. }
  36136. this._renderTargets.dispose();
  36137. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36138. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36139. }
  36140. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36141. };
  36142. return PBRBaseMaterial;
  36143. }(BABYLON.PushMaterial));
  36144. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  36145. __decorate([
  36146. BABYLON.serializeAsImageProcessingConfiguration()
  36147. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  36148. __decorate([
  36149. BABYLON.serialize()
  36150. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  36151. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  36152. })(BABYLON || (BABYLON = {}));
  36153. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  36154. var BABYLON;
  36155. (function (BABYLON) {
  36156. var Internals;
  36157. (function (Internals) {
  36158. /**
  36159. * The Physically based simple base material of BJS.
  36160. *
  36161. * This enables better naming and convention enforcements on top of the pbrMaterial.
  36162. * It is used as the base class for both the specGloss and metalRough conventions.
  36163. */
  36164. var PBRBaseSimpleMaterial = (function (_super) {
  36165. __extends(PBRBaseSimpleMaterial, _super);
  36166. /**
  36167. * Instantiates a new PBRMaterial instance.
  36168. *
  36169. * @param name The material name
  36170. * @param scene The scene the material will be use in.
  36171. */
  36172. function PBRBaseSimpleMaterial(name, scene) {
  36173. var _this = _super.call(this, name, scene) || this;
  36174. /**
  36175. * Number of Simultaneous lights allowed on the material.
  36176. */
  36177. _this.maxSimultaneousLights = 4;
  36178. /**
  36179. * If sets to true, disables all the lights affecting the material.
  36180. */
  36181. _this.disableLighting = false;
  36182. /**
  36183. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36184. */
  36185. _this.invertNormalMapX = false;
  36186. /**
  36187. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36188. */
  36189. _this.invertNormalMapY = false;
  36190. /**
  36191. * Emissivie color used to self-illuminate the model.
  36192. */
  36193. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36194. /**
  36195. * Occlusion Channel Strenght.
  36196. */
  36197. _this.occlusionStrength = 1.0;
  36198. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36199. _this._useAmbientInGrayScale = true;
  36200. return _this;
  36201. }
  36202. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  36203. /**
  36204. * Gets the current transparency mode.
  36205. */
  36206. get: function () {
  36207. return this._transparencyMode;
  36208. },
  36209. /**
  36210. * Sets the transparency mode of the material.
  36211. */
  36212. set: function (value) {
  36213. if (this._transparencyMode === value) {
  36214. return;
  36215. }
  36216. this._transparencyMode = value;
  36217. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  36218. this._forceAlphaTest = true;
  36219. }
  36220. else {
  36221. this._forceAlphaTest = false;
  36222. }
  36223. this._markAllSubMeshesAsTexturesDirty();
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  36229. /**
  36230. * Gets the current double sided mode.
  36231. */
  36232. get: function () {
  36233. return this._twoSidedLighting;
  36234. },
  36235. /**
  36236. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36237. */
  36238. set: function (value) {
  36239. if (this._twoSidedLighting === value) {
  36240. return;
  36241. }
  36242. this._twoSidedLighting = value;
  36243. this.backFaceCulling = !value;
  36244. this._markAllSubMeshesAsTexturesDirty();
  36245. },
  36246. enumerable: true,
  36247. configurable: true
  36248. });
  36249. /**
  36250. * Specifies wether or not the alpha value of the albedo texture should be used.
  36251. */
  36252. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36253. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36254. };
  36255. /**
  36256. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  36257. */
  36258. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  36259. if (this._linkRefractionWithTransparency) {
  36260. return false;
  36261. }
  36262. return (this.alpha < 1.0) ||
  36263. (this._shouldUseAlphaFromAlbedoTexture() &&
  36264. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  36265. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  36266. };
  36267. /**
  36268. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  36269. */
  36270. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  36271. if (this._linkRefractionWithTransparency) {
  36272. return false;
  36273. }
  36274. return this._shouldUseAlphaFromAlbedoTexture() &&
  36275. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  36276. };
  36277. return PBRBaseSimpleMaterial;
  36278. }(BABYLON.PBRBaseMaterial));
  36279. __decorate([
  36280. BABYLON.serialize(),
  36281. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36282. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36283. __decorate([
  36284. BABYLON.serialize(),
  36285. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36286. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36287. __decorate([
  36288. BABYLON.serializeAsTexture(),
  36289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36290. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36291. __decorate([
  36292. BABYLON.serialize(),
  36293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36294. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36295. __decorate([
  36296. BABYLON.serialize(),
  36297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36298. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36299. __decorate([
  36300. BABYLON.serializeAsTexture(),
  36301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36302. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36303. __decorate([
  36304. BABYLON.serializeAsColor3("emissive"),
  36305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36306. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36307. __decorate([
  36308. BABYLON.serializeAsTexture(),
  36309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36310. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36311. __decorate([
  36312. BABYLON.serialize(),
  36313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36314. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36315. __decorate([
  36316. BABYLON.serializeAsTexture(),
  36317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36318. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36319. __decorate([
  36320. BABYLON.serialize(),
  36321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36322. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36323. __decorate([
  36324. BABYLON.serialize()
  36325. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  36326. __decorate([
  36327. BABYLON.serialize()
  36328. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36329. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36330. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36331. })(BABYLON || (BABYLON = {}));
  36332. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36333. var BABYLON;
  36334. (function (BABYLON) {
  36335. /**
  36336. * The Physically based material of BJS.
  36337. *
  36338. * This offers the main features of a standard PBR material.
  36339. * For more information, please refer to the documentation :
  36340. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36341. */
  36342. var PBRMaterial = (function (_super) {
  36343. __extends(PBRMaterial, _super);
  36344. /**
  36345. * Instantiates a new PBRMaterial instance.
  36346. *
  36347. * @param name The material name
  36348. * @param scene The scene the material will be use in.
  36349. */
  36350. function PBRMaterial(name, scene) {
  36351. var _this = _super.call(this, name, scene) || this;
  36352. /**
  36353. * Intensity of the direct lights e.g. the four lights available in your scene.
  36354. * This impacts both the direct diffuse and specular highlights.
  36355. */
  36356. _this.directIntensity = 1.0;
  36357. /**
  36358. * Intensity of the emissive part of the material.
  36359. * This helps controlling the emissive effect without modifying the emissive color.
  36360. */
  36361. _this.emissiveIntensity = 1.0;
  36362. /**
  36363. * Intensity of the environment e.g. how much the environment will light the object
  36364. * either through harmonics for rough material or through the refelction for shiny ones.
  36365. */
  36366. _this.environmentIntensity = 1.0;
  36367. /**
  36368. * This is a special control allowing the reduction of the specular highlights coming from the
  36369. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36370. */
  36371. _this.specularIntensity = 1.0;
  36372. /**
  36373. * Debug Control allowing disabling the bump map on this material.
  36374. */
  36375. _this.disableBumpMap = false;
  36376. /**
  36377. * AKA Occlusion Texture Intensity in other nomenclature.
  36378. */
  36379. _this.ambientTextureStrength = 1.0;
  36380. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36381. /**
  36382. * AKA Diffuse Color in other nomenclature.
  36383. */
  36384. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36385. /**
  36386. * AKA Specular Color in other nomenclature.
  36387. */
  36388. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36389. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36390. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36391. /**
  36392. * AKA Glossiness in other nomenclature.
  36393. */
  36394. _this.microSurface = 1.0;
  36395. /**
  36396. * source material index of refraction (IOR)' / 'destination material IOR.
  36397. */
  36398. _this.indexOfRefraction = 0.66;
  36399. /**
  36400. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36401. */
  36402. _this.invertRefractionY = false;
  36403. /**
  36404. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36405. * Materials half opaque for instance using refraction could benefit from this control.
  36406. */
  36407. _this.linkRefractionWithTransparency = false;
  36408. _this.useLightmapAsShadowmap = false;
  36409. /**
  36410. * Specifies that the alpha is coming form the albedo channel alpha channel.
  36411. */
  36412. _this.useAlphaFromAlbedoTexture = false;
  36413. /**
  36414. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36415. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36416. */
  36417. _this.useSpecularOverAlpha = true;
  36418. /**
  36419. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36420. */
  36421. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36422. /**
  36423. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36424. */
  36425. _this.useRoughnessFromMetallicTextureAlpha = true;
  36426. /**
  36427. * Specifies if the metallic texture contains the roughness information in its green channel.
  36428. */
  36429. _this.useRoughnessFromMetallicTextureGreen = false;
  36430. /**
  36431. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36432. */
  36433. _this.useMetallnessFromMetallicTextureBlue = false;
  36434. /**
  36435. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36436. */
  36437. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36438. /**
  36439. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36440. */
  36441. _this.useAmbientInGrayScale = false;
  36442. /**
  36443. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36444. * The material will try to infer what glossiness each pixel should be.
  36445. */
  36446. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36447. /**
  36448. * BJS is using an harcoded light falloff based on a manually sets up range.
  36449. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36450. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36451. */
  36452. _this.usePhysicalLightFalloff = true;
  36453. /**
  36454. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36455. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36456. */
  36457. _this.useRadianceOverAlpha = true;
  36458. /**
  36459. * Allows using the bump map in parallax mode.
  36460. */
  36461. _this.useParallax = false;
  36462. /**
  36463. * Allows using the bump map in parallax occlusion mode.
  36464. */
  36465. _this.useParallaxOcclusion = false;
  36466. /**
  36467. * Controls the scale bias of the parallax mode.
  36468. */
  36469. _this.parallaxScaleBias = 0.05;
  36470. /**
  36471. * If sets to true, disables all the lights affecting the material.
  36472. */
  36473. _this.disableLighting = false;
  36474. /**
  36475. * Number of Simultaneous lights allowed on the material.
  36476. */
  36477. _this.maxSimultaneousLights = 4;
  36478. /**
  36479. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36480. */
  36481. _this.invertNormalMapX = false;
  36482. /**
  36483. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36484. */
  36485. _this.invertNormalMapY = false;
  36486. /**
  36487. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36488. */
  36489. _this.twoSidedLighting = false;
  36490. /**
  36491. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  36492. * in your scene composition.
  36493. */
  36494. _this.premultiplyAlpha = false;
  36495. /**
  36496. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36497. * And/Or occlude the blended part.
  36498. */
  36499. _this.useAlphaFresnel = false;
  36500. /**
  36501. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36502. * And/Or occlude the blended part.
  36503. */
  36504. _this.environmentBRDFTexture = null;
  36505. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36506. return _this;
  36507. }
  36508. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36509. /**
  36510. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36511. */
  36512. get: function () {
  36513. return this._PBRMATERIAL_OPAQUE;
  36514. },
  36515. enumerable: true,
  36516. configurable: true
  36517. });
  36518. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36519. /**
  36520. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36521. */
  36522. get: function () {
  36523. return this._PBRMATERIAL_ALPHATEST;
  36524. },
  36525. enumerable: true,
  36526. configurable: true
  36527. });
  36528. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36529. /**
  36530. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36531. */
  36532. get: function () {
  36533. return this._PBRMATERIAL_ALPHABLEND;
  36534. },
  36535. enumerable: true,
  36536. configurable: true
  36537. });
  36538. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36539. /**
  36540. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36541. * They are also discarded below the alpha cutoff threshold to improve performances.
  36542. */
  36543. get: function () {
  36544. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36545. },
  36546. enumerable: true,
  36547. configurable: true
  36548. });
  36549. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36550. /**
  36551. * Gets the image processing configuration used either in this material.
  36552. */
  36553. get: function () {
  36554. return this._imageProcessingConfiguration;
  36555. },
  36556. /**
  36557. * Sets the Default image processing configuration used either in the this material.
  36558. *
  36559. * If sets to null, the scene one is in use.
  36560. */
  36561. set: function (value) {
  36562. this._attachImageProcessingConfiguration(value);
  36563. // Ensure the effect will be rebuilt.
  36564. this._markAllSubMeshesAsTexturesDirty();
  36565. },
  36566. enumerable: true,
  36567. configurable: true
  36568. });
  36569. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36570. /**
  36571. * Gets wether the color curves effect is enabled.
  36572. */
  36573. get: function () {
  36574. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36575. },
  36576. /**
  36577. * Sets wether the color curves effect is enabled.
  36578. */
  36579. set: function (value) {
  36580. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36581. },
  36582. enumerable: true,
  36583. configurable: true
  36584. });
  36585. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36586. /**
  36587. * Gets wether the color grading effect is enabled.
  36588. */
  36589. get: function () {
  36590. return this.imageProcessingConfiguration.colorGradingEnabled;
  36591. },
  36592. /**
  36593. * Gets wether the color grading effect is enabled.
  36594. */
  36595. set: function (value) {
  36596. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36597. },
  36598. enumerable: true,
  36599. configurable: true
  36600. });
  36601. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36602. /**
  36603. * Gets wether tonemapping is enabled or not.
  36604. */
  36605. get: function () {
  36606. return this._imageProcessingConfiguration.toneMappingEnabled;
  36607. },
  36608. /**
  36609. * Sets wether tonemapping is enabled or not
  36610. */
  36611. set: function (value) {
  36612. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36613. },
  36614. enumerable: true,
  36615. configurable: true
  36616. });
  36617. ;
  36618. ;
  36619. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36620. /**
  36621. * The camera exposure used on this material.
  36622. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36623. * This corresponds to a photographic exposure.
  36624. */
  36625. get: function () {
  36626. return this._imageProcessingConfiguration.exposure;
  36627. },
  36628. /**
  36629. * The camera exposure used on this material.
  36630. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36631. * This corresponds to a photographic exposure.
  36632. */
  36633. set: function (value) {
  36634. this._imageProcessingConfiguration.exposure = value;
  36635. },
  36636. enumerable: true,
  36637. configurable: true
  36638. });
  36639. ;
  36640. ;
  36641. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36642. /**
  36643. * Gets The camera contrast used on this material.
  36644. */
  36645. get: function () {
  36646. return this._imageProcessingConfiguration.contrast;
  36647. },
  36648. /**
  36649. * Sets The camera contrast used on this material.
  36650. */
  36651. set: function (value) {
  36652. this._imageProcessingConfiguration.contrast = value;
  36653. },
  36654. enumerable: true,
  36655. configurable: true
  36656. });
  36657. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36658. /**
  36659. * Gets the Color Grading 2D Lookup Texture.
  36660. */
  36661. get: function () {
  36662. return this._imageProcessingConfiguration.colorGradingTexture;
  36663. },
  36664. /**
  36665. * Sets the Color Grading 2D Lookup Texture.
  36666. */
  36667. set: function (value) {
  36668. this._imageProcessingConfiguration.colorGradingTexture = value;
  36669. },
  36670. enumerable: true,
  36671. configurable: true
  36672. });
  36673. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36674. /**
  36675. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36676. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36677. * 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;
  36678. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36679. */
  36680. get: function () {
  36681. return this._imageProcessingConfiguration.colorCurves;
  36682. },
  36683. /**
  36684. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36685. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36686. * 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;
  36687. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36688. */
  36689. set: function (value) {
  36690. this._imageProcessingConfiguration.colorCurves = value;
  36691. },
  36692. enumerable: true,
  36693. configurable: true
  36694. });
  36695. PBRMaterial.prototype.getClassName = function () {
  36696. return "PBRMaterial";
  36697. };
  36698. PBRMaterial.prototype.getActiveTextures = function () {
  36699. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36700. if (this._albedoTexture) {
  36701. activeTextures.push(this._albedoTexture);
  36702. }
  36703. if (this._ambientTexture) {
  36704. activeTextures.push(this._ambientTexture);
  36705. }
  36706. if (this._opacityTexture) {
  36707. activeTextures.push(this._opacityTexture);
  36708. }
  36709. if (this._reflectionTexture) {
  36710. activeTextures.push(this._reflectionTexture);
  36711. }
  36712. if (this._emissiveTexture) {
  36713. activeTextures.push(this._emissiveTexture);
  36714. }
  36715. if (this._reflectionTexture) {
  36716. activeTextures.push(this._reflectionTexture);
  36717. }
  36718. if (this._metallicTexture) {
  36719. activeTextures.push(this._metallicTexture);
  36720. }
  36721. if (this._microSurfaceTexture) {
  36722. activeTextures.push(this._microSurfaceTexture);
  36723. }
  36724. if (this._bumpTexture) {
  36725. activeTextures.push(this._bumpTexture);
  36726. }
  36727. if (this._lightmapTexture) {
  36728. activeTextures.push(this._lightmapTexture);
  36729. }
  36730. if (this._refractionTexture) {
  36731. activeTextures.push(this._refractionTexture);
  36732. }
  36733. return activeTextures;
  36734. };
  36735. PBRMaterial.prototype.hasTexture = function (texture) {
  36736. if (_super.prototype.hasTexture.call(this, texture)) {
  36737. return true;
  36738. }
  36739. if (this._albedoTexture === texture) {
  36740. return true;
  36741. }
  36742. if (this._ambientTexture === texture) {
  36743. return true;
  36744. }
  36745. if (this._opacityTexture === texture) {
  36746. return true;
  36747. }
  36748. if (this._reflectionTexture === texture) {
  36749. return true;
  36750. }
  36751. if (this._metallicTexture === texture) {
  36752. return true;
  36753. }
  36754. if (this._microSurfaceTexture === texture) {
  36755. return true;
  36756. }
  36757. if (this._bumpTexture === texture) {
  36758. return true;
  36759. }
  36760. if (this._lightmapTexture === texture) {
  36761. return true;
  36762. }
  36763. if (this._refractionTexture === texture) {
  36764. return true;
  36765. }
  36766. return false;
  36767. };
  36768. PBRMaterial.prototype.clone = function (name) {
  36769. var _this = this;
  36770. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36771. };
  36772. PBRMaterial.prototype.serialize = function () {
  36773. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36774. serializationObject.customType = "BABYLON.PBRMaterial";
  36775. return serializationObject;
  36776. };
  36777. // Statics
  36778. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36779. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36780. };
  36781. return PBRMaterial;
  36782. }(BABYLON.PBRBaseMaterial));
  36783. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36784. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36785. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36786. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36787. __decorate([
  36788. BABYLON.serialize(),
  36789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36790. ], PBRMaterial.prototype, "directIntensity", void 0);
  36791. __decorate([
  36792. BABYLON.serialize(),
  36793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36794. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36795. __decorate([
  36796. BABYLON.serialize(),
  36797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36798. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36799. __decorate([
  36800. BABYLON.serialize(),
  36801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36802. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36803. __decorate([
  36804. BABYLON.serialize(),
  36805. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36806. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36807. __decorate([
  36808. BABYLON.serializeAsTexture(),
  36809. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36810. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36811. __decorate([
  36812. BABYLON.serializeAsTexture(),
  36813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36814. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36815. __decorate([
  36816. BABYLON.serialize(),
  36817. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36818. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36819. __decorate([
  36820. BABYLON.serializeAsTexture(),
  36821. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36822. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36823. __decorate([
  36824. BABYLON.serializeAsTexture(),
  36825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36826. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36827. __decorate([
  36828. BABYLON.serializeAsTexture(),
  36829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36830. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36831. __decorate([
  36832. BABYLON.serializeAsTexture(),
  36833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36834. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36835. __decorate([
  36836. BABYLON.serializeAsTexture(),
  36837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36838. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36839. __decorate([
  36840. BABYLON.serialize(),
  36841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36842. ], PBRMaterial.prototype, "metallic", void 0);
  36843. __decorate([
  36844. BABYLON.serialize(),
  36845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36846. ], PBRMaterial.prototype, "roughness", void 0);
  36847. __decorate([
  36848. BABYLON.serializeAsTexture(),
  36849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36850. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36851. __decorate([
  36852. BABYLON.serializeAsTexture(),
  36853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36854. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36855. __decorate([
  36856. BABYLON.serializeAsTexture(),
  36857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36858. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36859. __decorate([
  36860. BABYLON.serializeAsTexture(),
  36861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36862. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36863. __decorate([
  36864. BABYLON.serializeAsColor3("ambient"),
  36865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36866. ], PBRMaterial.prototype, "ambientColor", void 0);
  36867. __decorate([
  36868. BABYLON.serializeAsColor3("albedo"),
  36869. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36870. ], PBRMaterial.prototype, "albedoColor", void 0);
  36871. __decorate([
  36872. BABYLON.serializeAsColor3("reflectivity"),
  36873. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36874. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36875. __decorate([
  36876. BABYLON.serializeAsColor3("reflection"),
  36877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36878. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36879. __decorate([
  36880. BABYLON.serializeAsColor3("emissive"),
  36881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36882. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36883. __decorate([
  36884. BABYLON.serialize(),
  36885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36886. ], PBRMaterial.prototype, "microSurface", void 0);
  36887. __decorate([
  36888. BABYLON.serialize(),
  36889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36890. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36891. __decorate([
  36892. BABYLON.serialize(),
  36893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36894. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36895. __decorate([
  36896. BABYLON.serialize(),
  36897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36898. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36899. __decorate([
  36900. BABYLON.serialize(),
  36901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36902. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36903. __decorate([
  36904. BABYLON.serialize(),
  36905. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36906. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36907. __decorate([
  36908. BABYLON.serialize(),
  36909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36910. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36911. __decorate([
  36912. BABYLON.serialize(),
  36913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36914. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36915. __decorate([
  36916. BABYLON.serialize(),
  36917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36918. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36919. __decorate([
  36920. BABYLON.serialize(),
  36921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36922. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36923. __decorate([
  36924. BABYLON.serialize(),
  36925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36926. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36927. __decorate([
  36928. BABYLON.serialize(),
  36929. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36930. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36931. __decorate([
  36932. BABYLON.serialize(),
  36933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36934. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36935. __decorate([
  36936. BABYLON.serialize(),
  36937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36938. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36939. __decorate([
  36940. BABYLON.serialize(),
  36941. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36942. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36943. __decorate([
  36944. BABYLON.serialize(),
  36945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36946. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36947. __decorate([
  36948. BABYLON.serialize(),
  36949. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36950. ], PBRMaterial.prototype, "useParallax", void 0);
  36951. __decorate([
  36952. BABYLON.serialize(),
  36953. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36954. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36955. __decorate([
  36956. BABYLON.serialize(),
  36957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36958. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36959. __decorate([
  36960. BABYLON.serialize(),
  36961. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36962. ], PBRMaterial.prototype, "disableLighting", void 0);
  36963. __decorate([
  36964. BABYLON.serialize(),
  36965. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36966. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36967. __decorate([
  36968. BABYLON.serialize(),
  36969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36970. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36971. __decorate([
  36972. BABYLON.serialize(),
  36973. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36974. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36975. __decorate([
  36976. BABYLON.serialize(),
  36977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36978. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36979. __decorate([
  36980. BABYLON.serialize(),
  36981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36982. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  36983. __decorate([
  36984. BABYLON.serialize(),
  36985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36986. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36987. __decorate([
  36988. BABYLON.serializeAsTexture(),
  36989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36990. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36991. BABYLON.PBRMaterial = PBRMaterial;
  36992. })(BABYLON || (BABYLON = {}));
  36993. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36994. var BABYLON;
  36995. (function (BABYLON) {
  36996. /**
  36997. * The PBR material of BJS following the metal roughness convention.
  36998. *
  36999. * This fits to the PBR convention in the GLTF definition:
  37000. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  37001. */
  37002. var PBRMetallicRoughnessMaterial = (function (_super) {
  37003. __extends(PBRMetallicRoughnessMaterial, _super);
  37004. /**
  37005. * Instantiates a new PBRMetalRoughnessMaterial instance.
  37006. *
  37007. * @param name The material name
  37008. * @param scene The scene the material will be use in.
  37009. */
  37010. function PBRMetallicRoughnessMaterial(name, scene) {
  37011. var _this = _super.call(this, name, scene) || this;
  37012. _this._useRoughnessFromMetallicTextureAlpha = false;
  37013. _this._useRoughnessFromMetallicTextureGreen = true;
  37014. _this._useMetallnessFromMetallicTextureBlue = true;
  37015. return _this;
  37016. }
  37017. /**
  37018. * Return the currrent class name of the material.
  37019. */
  37020. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  37021. return "PBRMetallicRoughnessMaterial";
  37022. };
  37023. /**
  37024. * Return the active textures of the material.
  37025. */
  37026. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  37027. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37028. if (this.baseTexture) {
  37029. activeTextures.push(this.baseTexture);
  37030. }
  37031. if (this.metallicRoughnessTexture) {
  37032. activeTextures.push(this.metallicRoughnessTexture);
  37033. }
  37034. return activeTextures;
  37035. };
  37036. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  37037. if (_super.prototype.hasTexture.call(this, texture)) {
  37038. return true;
  37039. }
  37040. if (this.baseTexture === texture) {
  37041. return true;
  37042. }
  37043. if (this.metallicRoughnessTexture === texture) {
  37044. return true;
  37045. }
  37046. return false;
  37047. };
  37048. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  37049. var _this = this;
  37050. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  37051. };
  37052. /**
  37053. * Serialize the material to a parsable JSON object.
  37054. */
  37055. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  37056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37057. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  37058. return serializationObject;
  37059. };
  37060. /**
  37061. * Parses a JSON object correponding to the serialize function.
  37062. */
  37063. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  37064. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  37065. };
  37066. return PBRMetallicRoughnessMaterial;
  37067. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37068. __decorate([
  37069. BABYLON.serializeAsColor3(),
  37070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37071. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  37072. __decorate([
  37073. BABYLON.serializeAsTexture(),
  37074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37075. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  37076. __decorate([
  37077. BABYLON.serialize(),
  37078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37079. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  37080. __decorate([
  37081. BABYLON.serialize(),
  37082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37083. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  37084. __decorate([
  37085. BABYLON.serializeAsTexture(),
  37086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  37087. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  37088. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  37089. })(BABYLON || (BABYLON = {}));
  37090. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  37091. var BABYLON;
  37092. (function (BABYLON) {
  37093. /**
  37094. * The PBR material of BJS following the specular glossiness convention.
  37095. *
  37096. * This fits to the PBR convention in the GLTF definition:
  37097. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  37098. */
  37099. var PBRSpecularGlossinessMaterial = (function (_super) {
  37100. __extends(PBRSpecularGlossinessMaterial, _super);
  37101. /**
  37102. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  37103. *
  37104. * @param name The material name
  37105. * @param scene The scene the material will be use in.
  37106. */
  37107. function PBRSpecularGlossinessMaterial(name, scene) {
  37108. var _this = _super.call(this, name, scene) || this;
  37109. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  37110. return _this;
  37111. }
  37112. /**
  37113. * Return the currrent class name of the material.
  37114. */
  37115. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  37116. return "PBRSpecularGlossinessMaterial";
  37117. };
  37118. /**
  37119. * Return the active textures of the material.
  37120. */
  37121. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  37122. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37123. if (this.diffuseTexture) {
  37124. activeTextures.push(this.diffuseTexture);
  37125. }
  37126. if (this.specularGlossinessTexture) {
  37127. activeTextures.push(this.specularGlossinessTexture);
  37128. }
  37129. return activeTextures;
  37130. };
  37131. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  37132. if (_super.prototype.hasTexture.call(this, texture)) {
  37133. return true;
  37134. }
  37135. if (this.diffuseTexture === texture) {
  37136. return true;
  37137. }
  37138. if (this.specularGlossinessTexture === texture) {
  37139. return true;
  37140. }
  37141. return false;
  37142. };
  37143. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  37144. var _this = this;
  37145. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  37146. };
  37147. /**
  37148. * Serialize the material to a parsable JSON object.
  37149. */
  37150. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  37151. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37152. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  37153. return serializationObject;
  37154. };
  37155. /**
  37156. * Parses a JSON object correponding to the serialize function.
  37157. */
  37158. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  37159. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  37160. };
  37161. return PBRSpecularGlossinessMaterial;
  37162. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  37163. __decorate([
  37164. BABYLON.serializeAsColor3("diffuse"),
  37165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  37166. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  37167. __decorate([
  37168. BABYLON.serializeAsTexture(),
  37169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  37170. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  37171. __decorate([
  37172. BABYLON.serializeAsColor3("specular"),
  37173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  37174. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  37175. __decorate([
  37176. BABYLON.serialize(),
  37177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  37178. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  37179. __decorate([
  37180. BABYLON.serializeAsTexture(),
  37181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  37182. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  37183. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  37184. })(BABYLON || (BABYLON = {}));
  37185. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  37186. var BABYLON;
  37187. (function (BABYLON) {
  37188. var ShaderMaterial = (function (_super) {
  37189. __extends(ShaderMaterial, _super);
  37190. function ShaderMaterial(name, scene, shaderPath, options) {
  37191. var _this = _super.call(this, name, scene) || this;
  37192. _this._textures = {};
  37193. _this._textureArrays = {};
  37194. _this._floats = {};
  37195. _this._floatsArrays = {};
  37196. _this._colors3 = {};
  37197. _this._colors4 = {};
  37198. _this._vectors2 = {};
  37199. _this._vectors3 = {};
  37200. _this._vectors4 = {};
  37201. _this._matrices = {};
  37202. _this._matrices3x3 = {};
  37203. _this._matrices2x2 = {};
  37204. _this._vectors3Arrays = {};
  37205. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  37206. _this._shaderPath = shaderPath;
  37207. options.needAlphaBlending = options.needAlphaBlending || false;
  37208. options.needAlphaTesting = options.needAlphaTesting || false;
  37209. options.attributes = options.attributes || ["position", "normal", "uv"];
  37210. options.uniforms = options.uniforms || ["worldViewProjection"];
  37211. options.uniformBuffers = options.uniformBuffers || [];
  37212. options.samplers = options.samplers || [];
  37213. options.defines = options.defines || [];
  37214. _this._options = options;
  37215. return _this;
  37216. }
  37217. ShaderMaterial.prototype.getClassName = function () {
  37218. return "ShaderMaterial";
  37219. };
  37220. ShaderMaterial.prototype.needAlphaBlending = function () {
  37221. return this._options.needAlphaBlending;
  37222. };
  37223. ShaderMaterial.prototype.needAlphaTesting = function () {
  37224. return this._options.needAlphaTesting;
  37225. };
  37226. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  37227. if (this._options.uniforms.indexOf(uniformName) === -1) {
  37228. this._options.uniforms.push(uniformName);
  37229. }
  37230. };
  37231. ShaderMaterial.prototype.setTexture = function (name, texture) {
  37232. if (this._options.samplers.indexOf(name) === -1) {
  37233. this._options.samplers.push(name);
  37234. }
  37235. this._textures[name] = texture;
  37236. return this;
  37237. };
  37238. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  37239. if (this._options.samplers.indexOf(name) === -1) {
  37240. this._options.samplers.push(name);
  37241. }
  37242. this._checkUniform(name);
  37243. this._textureArrays[name] = textures;
  37244. return this;
  37245. };
  37246. ShaderMaterial.prototype.setFloat = function (name, value) {
  37247. this._checkUniform(name);
  37248. this._floats[name] = value;
  37249. return this;
  37250. };
  37251. ShaderMaterial.prototype.setFloats = function (name, value) {
  37252. this._checkUniform(name);
  37253. this._floatsArrays[name] = value;
  37254. return this;
  37255. };
  37256. ShaderMaterial.prototype.setColor3 = function (name, value) {
  37257. this._checkUniform(name);
  37258. this._colors3[name] = value;
  37259. return this;
  37260. };
  37261. ShaderMaterial.prototype.setColor4 = function (name, value) {
  37262. this._checkUniform(name);
  37263. this._colors4[name] = value;
  37264. return this;
  37265. };
  37266. ShaderMaterial.prototype.setVector2 = function (name, value) {
  37267. this._checkUniform(name);
  37268. this._vectors2[name] = value;
  37269. return this;
  37270. };
  37271. ShaderMaterial.prototype.setVector3 = function (name, value) {
  37272. this._checkUniform(name);
  37273. this._vectors3[name] = value;
  37274. return this;
  37275. };
  37276. ShaderMaterial.prototype.setVector4 = function (name, value) {
  37277. this._checkUniform(name);
  37278. this._vectors4[name] = value;
  37279. return this;
  37280. };
  37281. ShaderMaterial.prototype.setMatrix = function (name, value) {
  37282. this._checkUniform(name);
  37283. this._matrices[name] = value;
  37284. return this;
  37285. };
  37286. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  37287. this._checkUniform(name);
  37288. this._matrices3x3[name] = value;
  37289. return this;
  37290. };
  37291. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  37292. this._checkUniform(name);
  37293. this._matrices2x2[name] = value;
  37294. return this;
  37295. };
  37296. ShaderMaterial.prototype.setArray3 = function (name, value) {
  37297. this._checkUniform(name);
  37298. this._vectors3Arrays[name] = value;
  37299. return this;
  37300. };
  37301. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  37302. if (!mesh) {
  37303. return true;
  37304. }
  37305. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  37306. return false;
  37307. }
  37308. return false;
  37309. };
  37310. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  37311. var scene = this.getScene();
  37312. var engine = scene.getEngine();
  37313. if (!this.checkReadyOnEveryCall) {
  37314. if (this._renderId === scene.getRenderId()) {
  37315. if (this._checkCache(scene, mesh, useInstances)) {
  37316. return true;
  37317. }
  37318. }
  37319. }
  37320. // Instances
  37321. var defines = [];
  37322. var attribs = [];
  37323. var fallbacks = new BABYLON.EffectFallbacks();
  37324. if (useInstances) {
  37325. defines.push("#define INSTANCES");
  37326. }
  37327. for (var index = 0; index < this._options.defines.length; index++) {
  37328. defines.push(this._options.defines[index]);
  37329. }
  37330. for (var index = 0; index < this._options.attributes.length; index++) {
  37331. attribs.push(this._options.attributes[index]);
  37332. }
  37333. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37334. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37335. defines.push("#define VERTEXCOLOR");
  37336. }
  37337. // Bones
  37338. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  37339. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37340. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37341. if (mesh.numBoneInfluencers > 4) {
  37342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37344. }
  37345. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37346. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37347. fallbacks.addCPUSkinningFallback(0, mesh);
  37348. if (this._options.uniforms.indexOf("mBones") === -1) {
  37349. this._options.uniforms.push("mBones");
  37350. }
  37351. }
  37352. else {
  37353. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37354. }
  37355. // Textures
  37356. for (var name in this._textures) {
  37357. if (!this._textures[name].isReady()) {
  37358. return false;
  37359. }
  37360. }
  37361. // Alpha test
  37362. if (engine.getAlphaTesting()) {
  37363. defines.push("#define ALPHATEST");
  37364. }
  37365. var previousEffect = this._effect;
  37366. var join = defines.join("\n");
  37367. this._effect = engine.createEffect(this._shaderPath, {
  37368. attributes: attribs,
  37369. uniformsNames: this._options.uniforms,
  37370. uniformBuffersNames: this._options.uniformBuffers,
  37371. samplers: this._options.samplers,
  37372. defines: join,
  37373. fallbacks: fallbacks,
  37374. onCompiled: this.onCompiled,
  37375. onError: this.onError
  37376. }, engine);
  37377. if (!this._effect.isReady()) {
  37378. return false;
  37379. }
  37380. if (previousEffect !== this._effect) {
  37381. scene.resetCachedMaterial();
  37382. }
  37383. this._renderId = scene.getRenderId();
  37384. return true;
  37385. };
  37386. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37387. var scene = this.getScene();
  37388. if (this._options.uniforms.indexOf("world") !== -1) {
  37389. this._effect.setMatrix("world", world);
  37390. }
  37391. if (this._options.uniforms.indexOf("worldView") !== -1) {
  37392. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  37393. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  37394. }
  37395. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  37396. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  37397. }
  37398. };
  37399. ShaderMaterial.prototype.bind = function (world, mesh) {
  37400. // Std values
  37401. this.bindOnlyWorldMatrix(world);
  37402. if (this.getScene().getCachedMaterial() !== this) {
  37403. if (this._options.uniforms.indexOf("view") !== -1) {
  37404. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  37405. }
  37406. if (this._options.uniforms.indexOf("projection") !== -1) {
  37407. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  37408. }
  37409. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  37410. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  37411. }
  37412. // Bones
  37413. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  37414. var name;
  37415. // Texture
  37416. for (name in this._textures) {
  37417. this._effect.setTexture(name, this._textures[name]);
  37418. }
  37419. // Texture arrays
  37420. for (name in this._textureArrays) {
  37421. this._effect.setTextureArray(name, this._textureArrays[name]);
  37422. }
  37423. // Float
  37424. for (name in this._floats) {
  37425. this._effect.setFloat(name, this._floats[name]);
  37426. }
  37427. // Float s
  37428. for (name in this._floatsArrays) {
  37429. this._effect.setArray(name, this._floatsArrays[name]);
  37430. }
  37431. // Color3
  37432. for (name in this._colors3) {
  37433. this._effect.setColor3(name, this._colors3[name]);
  37434. }
  37435. // Color4
  37436. for (name in this._colors4) {
  37437. var color = this._colors4[name];
  37438. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  37439. }
  37440. // Vector2
  37441. for (name in this._vectors2) {
  37442. this._effect.setVector2(name, this._vectors2[name]);
  37443. }
  37444. // Vector3
  37445. for (name in this._vectors3) {
  37446. this._effect.setVector3(name, this._vectors3[name]);
  37447. }
  37448. // Vector4
  37449. for (name in this._vectors4) {
  37450. this._effect.setVector4(name, this._vectors4[name]);
  37451. }
  37452. // Matrix
  37453. for (name in this._matrices) {
  37454. this._effect.setMatrix(name, this._matrices[name]);
  37455. }
  37456. // Matrix 3x3
  37457. for (name in this._matrices3x3) {
  37458. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  37459. }
  37460. // Matrix 2x2
  37461. for (name in this._matrices2x2) {
  37462. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  37463. }
  37464. // Vector3Array
  37465. for (name in this._vectors3Arrays) {
  37466. this._effect.setArray3(name, this._vectors3Arrays[name]);
  37467. }
  37468. }
  37469. this._afterBind(mesh);
  37470. };
  37471. ShaderMaterial.prototype.getActiveTextures = function () {
  37472. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37473. for (var name in this._textures) {
  37474. activeTextures.push(this._textures[name]);
  37475. }
  37476. for (var name in this._textureArrays) {
  37477. var array = this._textureArrays[name];
  37478. for (var index = 0; index < array.length; index++) {
  37479. activeTextures.push(array[index]);
  37480. }
  37481. }
  37482. return activeTextures;
  37483. };
  37484. ShaderMaterial.prototype.hasTexture = function (texture) {
  37485. if (_super.prototype.hasTexture.call(this, texture)) {
  37486. return true;
  37487. }
  37488. for (var name in this._textures) {
  37489. if (this._textures[name] === texture) {
  37490. return true;
  37491. }
  37492. }
  37493. for (var name in this._textureArrays) {
  37494. var array = this._textureArrays[name];
  37495. for (var index = 0; index < array.length; index++) {
  37496. if (array[index] === texture) {
  37497. return true;
  37498. }
  37499. }
  37500. }
  37501. return false;
  37502. };
  37503. ShaderMaterial.prototype.clone = function (name) {
  37504. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  37505. return newShaderMaterial;
  37506. };
  37507. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37508. if (forceDisposeTextures) {
  37509. var name;
  37510. for (name in this._textures) {
  37511. this._textures[name].dispose();
  37512. }
  37513. for (name in this._textureArrays) {
  37514. var array = this._textureArrays[name];
  37515. for (var index = 0; index < array.length; index++) {
  37516. array[index].dispose();
  37517. }
  37518. }
  37519. }
  37520. this._textures = {};
  37521. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37522. };
  37523. ShaderMaterial.prototype.serialize = function () {
  37524. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37525. serializationObject.customType = "BABYLON.ShaderMaterial";
  37526. serializationObject.options = this._options;
  37527. serializationObject.shaderPath = this._shaderPath;
  37528. var name;
  37529. // Texture
  37530. serializationObject.textures = {};
  37531. for (name in this._textures) {
  37532. serializationObject.textures[name] = this._textures[name].serialize();
  37533. }
  37534. // Texture arrays
  37535. serializationObject.textureArrays = {};
  37536. for (name in this._textureArrays) {
  37537. serializationObject.textureArrays[name] = [];
  37538. var array = this._textureArrays[name];
  37539. for (var index = 0; index < array.length; index++) {
  37540. serializationObject.textureArrays[name].push(array[index].serialize());
  37541. }
  37542. }
  37543. // Float
  37544. serializationObject.floats = {};
  37545. for (name in this._floats) {
  37546. serializationObject.floats[name] = this._floats[name];
  37547. }
  37548. // Float s
  37549. serializationObject.floatArrays = {};
  37550. for (name in this._floatsArrays) {
  37551. serializationObject.floatArrays[name] = this._floatsArrays[name];
  37552. }
  37553. // Color3
  37554. serializationObject.colors3 = {};
  37555. for (name in this._colors3) {
  37556. serializationObject.colors3[name] = this._colors3[name].asArray();
  37557. }
  37558. // Color4
  37559. serializationObject.colors4 = {};
  37560. for (name in this._colors4) {
  37561. serializationObject.colors4[name] = this._colors4[name].asArray();
  37562. }
  37563. // Vector2
  37564. serializationObject.vectors2 = {};
  37565. for (name in this._vectors2) {
  37566. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  37567. }
  37568. // Vector3
  37569. serializationObject.vectors3 = {};
  37570. for (name in this._vectors3) {
  37571. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  37572. }
  37573. // Vector4
  37574. serializationObject.vectors4 = {};
  37575. for (name in this._vectors4) {
  37576. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  37577. }
  37578. // Matrix
  37579. serializationObject.matrices = {};
  37580. for (name in this._matrices) {
  37581. serializationObject.matrices[name] = this._matrices[name].asArray();
  37582. }
  37583. // Matrix 3x3
  37584. serializationObject.matrices3x3 = {};
  37585. for (name in this._matrices3x3) {
  37586. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  37587. }
  37588. // Matrix 2x2
  37589. serializationObject.matrices2x2 = {};
  37590. for (name in this._matrices2x2) {
  37591. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  37592. }
  37593. // Vector3Array
  37594. serializationObject.vectors3Arrays = {};
  37595. for (name in this._vectors3Arrays) {
  37596. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  37597. }
  37598. return serializationObject;
  37599. };
  37600. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  37601. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  37602. var name;
  37603. // Texture
  37604. for (name in source.textures) {
  37605. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  37606. }
  37607. // Texture arrays
  37608. for (name in source.textureArrays) {
  37609. var array = source.textureArrays[name];
  37610. var textureArray = new Array();
  37611. for (var index = 0; index < array.length; index++) {
  37612. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  37613. }
  37614. material.setTextureArray(name, textureArray);
  37615. }
  37616. // Float
  37617. for (name in source.floats) {
  37618. material.setFloat(name, source.floats[name]);
  37619. }
  37620. // Float s
  37621. for (name in source.floatsArrays) {
  37622. material.setFloats(name, source.floatsArrays[name]);
  37623. }
  37624. // Color3
  37625. for (name in source.colors3) {
  37626. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  37627. }
  37628. // Color4
  37629. for (name in source.colors4) {
  37630. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  37631. }
  37632. // Vector2
  37633. for (name in source.vectors2) {
  37634. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  37635. }
  37636. // Vector3
  37637. for (name in source.vectors3) {
  37638. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  37639. }
  37640. // Vector4
  37641. for (name in source.vectors4) {
  37642. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  37643. }
  37644. // Matrix
  37645. for (name in source.matrices) {
  37646. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  37647. }
  37648. // Matrix 3x3
  37649. for (name in source.matrices3x3) {
  37650. material.setMatrix3x3(name, source.matrices3x3[name]);
  37651. }
  37652. // Matrix 2x2
  37653. for (name in source.matrices2x2) {
  37654. material.setMatrix2x2(name, source.matrices2x2[name]);
  37655. }
  37656. // Vector3Array
  37657. for (name in source.vectors3Arrays) {
  37658. material.setArray3(name, source.vectors3Arrays[name]);
  37659. }
  37660. return material;
  37661. };
  37662. return ShaderMaterial;
  37663. }(BABYLON.Material));
  37664. BABYLON.ShaderMaterial = ShaderMaterial;
  37665. })(BABYLON || (BABYLON = {}));
  37666. //# sourceMappingURL=babylon.shaderMaterial.js.map
  37667. var BABYLON;
  37668. (function (BABYLON) {
  37669. var MeshBuilder = (function () {
  37670. function MeshBuilder() {
  37671. }
  37672. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  37673. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  37674. return BABYLON.Mesh.DOUBLESIDE;
  37675. }
  37676. if (orientation === undefined || orientation === null) {
  37677. return BABYLON.Mesh.FRONTSIDE;
  37678. }
  37679. return orientation;
  37680. };
  37681. /**
  37682. * Creates a box mesh.
  37683. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37684. * The parameter `size` sets the size (float) of each box side (default 1).
  37685. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37686. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  37687. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37688. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37689. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37690. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37692. */
  37693. MeshBuilder.CreateBox = function (name, options, scene) {
  37694. var box = new BABYLON.Mesh(name, scene);
  37695. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37696. box.sideOrientation = options.sideOrientation;
  37697. var vertexData = BABYLON.VertexData.CreateBox(options);
  37698. vertexData.applyToMesh(box, options.updatable);
  37699. return box;
  37700. };
  37701. /**
  37702. * Creates a sphere mesh.
  37703. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37704. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37705. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  37706. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37707. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  37708. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  37709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37710. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37713. */
  37714. MeshBuilder.CreateSphere = function (name, options, scene) {
  37715. var sphere = new BABYLON.Mesh(name, scene);
  37716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37717. sphere.sideOrientation = options.sideOrientation;
  37718. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37719. vertexData.applyToMesh(sphere, options.updatable);
  37720. return sphere;
  37721. };
  37722. /**
  37723. * Creates a plane polygonal mesh. By default, this is a disc.
  37724. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37725. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37726. * 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.
  37727. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  37728. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37729. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37730. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37732. */
  37733. MeshBuilder.CreateDisc = function (name, options, scene) {
  37734. var disc = new BABYLON.Mesh(name, scene);
  37735. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37736. disc.sideOrientation = options.sideOrientation;
  37737. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37738. vertexData.applyToMesh(disc, options.updatable);
  37739. return disc;
  37740. };
  37741. /**
  37742. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37743. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37744. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37745. * 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`).
  37746. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37747. * 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.
  37748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37749. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37750. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37752. */
  37753. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37754. var sphere = new BABYLON.Mesh(name, scene);
  37755. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37756. sphere.sideOrientation = options.sideOrientation;
  37757. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37758. vertexData.applyToMesh(sphere, options.updatable);
  37759. return sphere;
  37760. };
  37761. ;
  37762. /**
  37763. * Creates a ribbon mesh.
  37764. * 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.
  37765. *
  37766. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37767. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37768. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37769. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37770. * 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.
  37771. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  37772. * 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
  37773. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37774. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37776. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37777. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  37778. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37779. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  37780. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37781. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37783. */
  37784. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37785. var pathArray = options.pathArray;
  37786. var closeArray = options.closeArray;
  37787. var closePath = options.closePath;
  37788. var offset = options.offset;
  37789. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37790. var instance = options.instance;
  37791. var updatable = options.updatable;
  37792. if (instance) {
  37793. // positionFunction : ribbon case
  37794. // only pathArray and sideOrientation parameters are taken into account for positions update
  37795. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37796. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37797. var positionFunction = function (positions) {
  37798. var minlg = pathArray[0].length;
  37799. var i = 0;
  37800. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37801. for (var si = 1; si <= ns; si++) {
  37802. for (var p = 0; p < pathArray.length; p++) {
  37803. var path = pathArray[p];
  37804. var l = path.length;
  37805. minlg = (minlg < l) ? minlg : l;
  37806. var j = 0;
  37807. while (j < minlg) {
  37808. positions[i] = path[j].x;
  37809. positions[i + 1] = path[j].y;
  37810. positions[i + 2] = path[j].z;
  37811. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37812. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37813. }
  37814. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37815. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37816. }
  37817. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37818. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37819. }
  37820. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37821. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37822. }
  37823. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37824. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37825. }
  37826. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37827. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37828. }
  37829. j++;
  37830. i += 3;
  37831. }
  37832. if (instance._closePath) {
  37833. positions[i] = path[0].x;
  37834. positions[i + 1] = path[0].y;
  37835. positions[i + 2] = path[0].z;
  37836. i += 3;
  37837. }
  37838. }
  37839. }
  37840. };
  37841. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37842. positionFunction(positions);
  37843. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37844. instance._boundingInfo.update(instance._worldMatrix);
  37845. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37846. if (options.colors) {
  37847. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37848. for (var c = 0; c < options.colors.length; c++) {
  37849. colors[c * 4] = options.colors[c].r;
  37850. colors[c * 4 + 1] = options.colors[c].g;
  37851. colors[c * 4 + 2] = options.colors[c].b;
  37852. colors[c * 4 + 3] = options.colors[c].a;
  37853. }
  37854. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37855. }
  37856. if (options.uvs) {
  37857. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37858. for (var i = 0; i < options.uvs.length; i++) {
  37859. uvs[i * 2] = options.uvs[i].x;
  37860. uvs[i * 2 + 1] = options.uvs[i].y;
  37861. }
  37862. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37863. }
  37864. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37865. var indices = instance.getIndices();
  37866. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37867. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37868. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37869. if (instance._closePath) {
  37870. var indexFirst = 0;
  37871. var indexLast = 0;
  37872. for (var p = 0; p < pathArray.length; p++) {
  37873. indexFirst = instance._idx[p] * 3;
  37874. if (p + 1 < pathArray.length) {
  37875. indexLast = (instance._idx[p + 1] - 1) * 3;
  37876. }
  37877. else {
  37878. indexLast = normals.length - 3;
  37879. }
  37880. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37881. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37882. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37883. normals[indexLast] = normals[indexFirst];
  37884. normals[indexLast + 1] = normals[indexFirst + 1];
  37885. normals[indexLast + 2] = normals[indexFirst + 2];
  37886. }
  37887. }
  37888. if (!(instance.areNormalsFrozen)) {
  37889. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37890. }
  37891. }
  37892. return instance;
  37893. }
  37894. else {
  37895. var ribbon = new BABYLON.Mesh(name, scene);
  37896. ribbon.sideOrientation = sideOrientation;
  37897. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37898. if (closePath) {
  37899. ribbon._idx = vertexData._idx;
  37900. }
  37901. ribbon._closePath = closePath;
  37902. ribbon._closeArray = closeArray;
  37903. vertexData.applyToMesh(ribbon, updatable);
  37904. return ribbon;
  37905. }
  37906. };
  37907. /**
  37908. * Creates a cylinder or a cone mesh.
  37909. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37910. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37911. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37912. * 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.
  37913. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37914. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37915. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37916. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37917. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37918. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  37919. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  37920. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37921. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  37922. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  37923. * If `enclose` is false, a ring surface is one element.
  37924. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37925. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  37926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37927. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37930. */
  37931. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37932. var cylinder = new BABYLON.Mesh(name, scene);
  37933. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37934. cylinder.sideOrientation = options.sideOrientation;
  37935. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37936. vertexData.applyToMesh(cylinder, options.updatable);
  37937. return cylinder;
  37938. };
  37939. /**
  37940. * Creates a torus mesh.
  37941. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37942. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37943. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37944. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37945. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37946. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37947. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37948. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37949. */
  37950. MeshBuilder.CreateTorus = function (name, options, scene) {
  37951. var torus = new BABYLON.Mesh(name, scene);
  37952. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37953. torus.sideOrientation = options.sideOrientation;
  37954. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37955. vertexData.applyToMesh(torus, options.updatable);
  37956. return torus;
  37957. };
  37958. /**
  37959. * Creates a torus knot mesh.
  37960. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37961. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37962. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37963. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37964. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37966. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  37967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37968. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37969. */
  37970. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37971. var torusKnot = new BABYLON.Mesh(name, scene);
  37972. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37973. torusKnot.sideOrientation = options.sideOrientation;
  37974. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37975. vertexData.applyToMesh(torusKnot, options.updatable);
  37976. return torusKnot;
  37977. };
  37978. /**
  37979. * Creates a line system mesh.
  37980. * A line system is a pool of many lines gathered in a single mesh.
  37981. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37982. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  37983. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37984. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  37985. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  37986. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  37987. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  37988. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37989. */
  37990. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  37991. var instance = options.instance;
  37992. var lines = options.lines;
  37993. if (instance) {
  37994. var positionFunction = function (positions) {
  37995. var i = 0;
  37996. for (var l = 0; l < lines.length; l++) {
  37997. var points = lines[l];
  37998. for (var p = 0; p < points.length; p++) {
  37999. positions[i] = points[p].x;
  38000. positions[i + 1] = points[p].y;
  38001. positions[i + 2] = points[p].z;
  38002. i += 3;
  38003. }
  38004. }
  38005. };
  38006. instance.updateMeshPositions(positionFunction, false);
  38007. return instance;
  38008. }
  38009. // line system creation
  38010. var lineSystem = new BABYLON.LinesMesh(name, scene);
  38011. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  38012. vertexData.applyToMesh(lineSystem, options.updatable);
  38013. return lineSystem;
  38014. };
  38015. /**
  38016. * Creates a line mesh.
  38017. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  38018. * 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.
  38019. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38020. * The parameter `points` is an array successive Vector3.
  38021. * 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
  38022. * When updating an instance, remember that only point positions can change, not the number of points.
  38023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38024. */
  38025. MeshBuilder.CreateLines = function (name, options, scene) {
  38026. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  38027. return lines;
  38028. };
  38029. /**
  38030. * Creates a dashed line mesh.
  38031. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  38032. * 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.
  38033. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38034. * The parameter `points` is an array successive Vector3.
  38035. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  38036. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  38037. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  38038. * 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
  38039. * When updating an instance, remember that only point positions can change, not the number of points.
  38040. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38041. */
  38042. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  38043. var points = options.points;
  38044. var instance = options.instance;
  38045. var gapSize = options.gapSize;
  38046. var dashNb = options.dashNb;
  38047. var dashSize = options.dashSize;
  38048. if (instance) {
  38049. var positionFunction = function (positions) {
  38050. var curvect = BABYLON.Vector3.Zero();
  38051. var nbSeg = positions.length / 6;
  38052. var lg = 0;
  38053. var nb = 0;
  38054. var shft = 0;
  38055. var dashshft = 0;
  38056. var curshft = 0;
  38057. var p = 0;
  38058. var i = 0;
  38059. var j = 0;
  38060. for (i = 0; i < points.length - 1; i++) {
  38061. points[i + 1].subtractToRef(points[i], curvect);
  38062. lg += curvect.length();
  38063. }
  38064. shft = lg / nbSeg;
  38065. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  38066. for (i = 0; i < points.length - 1; i++) {
  38067. points[i + 1].subtractToRef(points[i], curvect);
  38068. nb = Math.floor(curvect.length() / shft);
  38069. curvect.normalize();
  38070. j = 0;
  38071. while (j < nb && p < positions.length) {
  38072. curshft = shft * j;
  38073. positions[p] = points[i].x + curshft * curvect.x;
  38074. positions[p + 1] = points[i].y + curshft * curvect.y;
  38075. positions[p + 2] = points[i].z + curshft * curvect.z;
  38076. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  38077. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  38078. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  38079. p += 6;
  38080. j++;
  38081. }
  38082. }
  38083. while (p < positions.length) {
  38084. positions[p] = points[i].x;
  38085. positions[p + 1] = points[i].y;
  38086. positions[p + 2] = points[i].z;
  38087. p += 3;
  38088. }
  38089. };
  38090. instance.updateMeshPositions(positionFunction, false);
  38091. return instance;
  38092. }
  38093. // dashed lines creation
  38094. var dashedLines = new BABYLON.LinesMesh(name, scene);
  38095. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  38096. vertexData.applyToMesh(dashedLines, options.updatable);
  38097. dashedLines.dashSize = dashSize;
  38098. dashedLines.gapSize = gapSize;
  38099. return dashedLines;
  38100. };
  38101. /**
  38102. * Creates an extruded shape mesh.
  38103. * 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.
  38104. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  38105. *
  38106. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38107. * 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
  38108. * extruded along the Z axis.
  38109. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38110. * 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.
  38111. * The parameter `scale` (float, default 1) is the value to scale the shape.
  38112. * 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
  38113. * 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
  38114. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38115. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38116. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38117. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38118. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38120. */
  38121. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  38122. var path = options.path;
  38123. var shape = options.shape;
  38124. var scale = options.scale || 1;
  38125. var rotation = options.rotation || 0;
  38126. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38127. var updatable = options.updatable;
  38128. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38129. var instance = options.instance;
  38130. var invertUV = options.invertUV || false;
  38131. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  38132. };
  38133. /**
  38134. * Creates an custom extruded shape mesh.
  38135. * 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.
  38136. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  38137. *
  38138. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  38139. * 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
  38140. * extruded along the Z axis.
  38141. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  38142. * 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
  38143. * and the distance of this point from the begining of the path :
  38144. * ```javascript
  38145. * var rotationFunction = function(i, distance) {
  38146. * // do things
  38147. * return rotationValue; }
  38148. * ```
  38149. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  38150. * 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
  38151. * and the distance of this point from the begining of the path :
  38152. * ```javascript
  38153. * var scaleFunction = function(i, distance) {
  38154. * // do things
  38155. * return scaleValue;}
  38156. * ```
  38157. * It must returns a float value that will be the scale value applied to the shape on each path point.
  38158. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  38159. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  38160. * 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
  38161. * 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
  38162. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  38163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38164. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38165. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38166. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38168. */
  38169. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  38170. var path = options.path;
  38171. var shape = options.shape;
  38172. var scaleFunction = options.scaleFunction || (function () { return 1; });
  38173. var rotationFunction = options.rotationFunction || (function () { return 0; });
  38174. var ribbonCloseArray = options.ribbonCloseArray || false;
  38175. var ribbonClosePath = options.ribbonClosePath || false;
  38176. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  38177. var updatable = options.updatable;
  38178. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38179. var instance = options.instance;
  38180. var invertUV = options.invertUV || false;
  38181. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  38182. };
  38183. /**
  38184. * Creates lathe mesh.
  38185. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  38186. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  38187. *
  38188. * 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
  38189. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  38190. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  38191. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  38192. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  38193. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  38194. * 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
  38195. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38196. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38197. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38198. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38199. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38200. */
  38201. MeshBuilder.CreateLathe = function (name, options, scene) {
  38202. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  38203. var closed = (options.closed === undefined) ? true : options.closed;
  38204. var shape = options.shape;
  38205. var radius = options.radius || 1;
  38206. var tessellation = options.tessellation || 64;
  38207. var updatable = options.updatable;
  38208. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38209. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38210. var pi2 = Math.PI * 2;
  38211. var paths = new Array();
  38212. var invertUV = options.invertUV || false;
  38213. var i = 0;
  38214. var p = 0;
  38215. var step = pi2 / tessellation * arc;
  38216. var rotated;
  38217. var path = new Array();
  38218. ;
  38219. for (i = 0; i <= tessellation; i++) {
  38220. var path = [];
  38221. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  38222. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  38223. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  38224. }
  38225. for (p = 0; p < shape.length; p++) {
  38226. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  38227. path.push(rotated);
  38228. }
  38229. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  38230. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
  38231. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  38232. }
  38233. paths.push(path);
  38234. }
  38235. // lathe ribbon
  38236. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  38237. return lathe;
  38238. };
  38239. /**
  38240. * Creates a plane mesh.
  38241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38242. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  38243. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  38244. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  38245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38246. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38249. */
  38250. MeshBuilder.CreatePlane = function (name, options, scene) {
  38251. var plane = new BABYLON.Mesh(name, scene);
  38252. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38253. plane.sideOrientation = options.sideOrientation;
  38254. var vertexData = BABYLON.VertexData.CreatePlane(options);
  38255. vertexData.applyToMesh(plane, options.updatable);
  38256. if (options.sourcePlane) {
  38257. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  38258. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  38259. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  38260. plane.rotate(vectorProduct, product);
  38261. }
  38262. return plane;
  38263. };
  38264. /**
  38265. * Creates a ground mesh.
  38266. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  38267. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  38268. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  38269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38270. */
  38271. MeshBuilder.CreateGround = function (name, options, scene) {
  38272. var ground = new BABYLON.GroundMesh(name, scene);
  38273. ground._setReady(false);
  38274. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38275. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38276. ground._width = options.width || 1;
  38277. ground._height = options.height || 1;
  38278. ground._maxX = ground._width / 2;
  38279. ground._maxZ = ground._height / 2;
  38280. ground._minX = -ground._maxX;
  38281. ground._minZ = -ground._maxZ;
  38282. var vertexData = BABYLON.VertexData.CreateGround(options);
  38283. vertexData.applyToMesh(ground, options.updatable);
  38284. ground._setReady(true);
  38285. return ground;
  38286. };
  38287. /**
  38288. * Creates a tiled ground mesh.
  38289. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  38290. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  38291. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  38292. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  38293. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  38294. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  38295. * numbers of subdivisions on the ground width and height of each tile.
  38296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38297. */
  38298. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  38299. var tiledGround = new BABYLON.Mesh(name, scene);
  38300. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  38301. vertexData.applyToMesh(tiledGround, options.updatable);
  38302. return tiledGround;
  38303. };
  38304. /**
  38305. * Creates a ground mesh from a height map.
  38306. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  38307. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  38308. * The parameter `url` sets the URL of the height map image resource.
  38309. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  38310. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  38311. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  38312. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  38313. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  38314. * 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).
  38315. * This function is passed the newly built mesh :
  38316. * ```javascript
  38317. * function(mesh) { // do things
  38318. * return; }
  38319. * ```
  38320. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38321. */
  38322. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  38323. var width = options.width || 10.0;
  38324. var height = options.height || 10.0;
  38325. var subdivisions = options.subdivisions || 1 | 0;
  38326. var minHeight = options.minHeight || 0.0;
  38327. var maxHeight = options.maxHeight || 10.0;
  38328. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38329. var updatable = options.updatable;
  38330. var onReady = options.onReady;
  38331. var ground = new BABYLON.GroundMesh(name, scene);
  38332. ground._subdivisionsX = subdivisions;
  38333. ground._subdivisionsY = subdivisions;
  38334. ground._width = width;
  38335. ground._height = height;
  38336. ground._maxX = ground._width / 2.0;
  38337. ground._maxZ = ground._height / 2.0;
  38338. ground._minX = -ground._maxX;
  38339. ground._minZ = -ground._maxZ;
  38340. ground._setReady(false);
  38341. var onload = function (img) {
  38342. // Getting height map data
  38343. var canvas = document.createElement("canvas");
  38344. var context = canvas.getContext("2d");
  38345. var bufferWidth = img.width;
  38346. var bufferHeight = img.height;
  38347. canvas.width = bufferWidth;
  38348. canvas.height = bufferHeight;
  38349. context.drawImage(img, 0, 0);
  38350. // Create VertexData from map data
  38351. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  38352. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  38353. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  38354. width: width, height: height,
  38355. subdivisions: subdivisions,
  38356. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  38357. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  38358. });
  38359. vertexData.applyToMesh(ground, updatable);
  38360. ground._setReady(true);
  38361. //execute ready callback, if set
  38362. if (onReady) {
  38363. onReady(ground);
  38364. }
  38365. };
  38366. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  38367. return ground;
  38368. };
  38369. /**
  38370. * Creates a polygon mesh.
  38371. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  38372. * 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.
  38373. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38374. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38375. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38376. * Remember you can only change the shape positions, not their number when updating a polygon.
  38377. */
  38378. MeshBuilder.CreatePolygon = function (name, options, scene) {
  38379. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38380. var shape = options.shape;
  38381. var holes = options.holes || [];
  38382. var depth = options.depth || 0;
  38383. var contours = [];
  38384. var hole = [];
  38385. for (var i = 0; i < shape.length; i++) {
  38386. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  38387. }
  38388. var epsilon = 0.00000001;
  38389. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  38390. contours.pop();
  38391. }
  38392. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  38393. for (var hNb = 0; hNb < holes.length; hNb++) {
  38394. hole = [];
  38395. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  38396. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  38397. }
  38398. polygonTriangulation.addHole(hole);
  38399. }
  38400. var polygon = polygonTriangulation.build(options.updatable, depth);
  38401. polygon.sideOrientation = options.sideOrientation;
  38402. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  38403. vertexData.applyToMesh(polygon, options.updatable);
  38404. return polygon;
  38405. };
  38406. ;
  38407. /**
  38408. * Creates an extruded polygon mesh, with depth in the Y direction.
  38409. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  38410. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38411. */
  38412. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  38413. return MeshBuilder.CreatePolygon(name, options, scene);
  38414. };
  38415. ;
  38416. /**
  38417. * Creates a tube mesh.
  38418. * 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.
  38419. *
  38420. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  38421. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  38422. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  38423. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  38424. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  38425. * 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.
  38426. * It must return a radius value (positive float) :
  38427. * ```javascript
  38428. * var radiusFunction = function(i, distance) {
  38429. * // do things
  38430. * return radius; }
  38431. * ```
  38432. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  38433. * 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
  38434. * 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
  38435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38436. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38438. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38439. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38440. */
  38441. MeshBuilder.CreateTube = function (name, options, scene) {
  38442. var path = options.path;
  38443. var radius = options.radius || 1.0;
  38444. var tessellation = options.tessellation || 64 | 0;
  38445. var radiusFunction = options.radiusFunction;
  38446. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  38447. var invertUV = options.invertUV || false;
  38448. var updatable = options.updatable;
  38449. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38450. var instance = options.instance;
  38451. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  38452. // tube geometry
  38453. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  38454. var tangents = path3D.getTangents();
  38455. var normals = path3D.getNormals();
  38456. var distances = path3D.getDistances();
  38457. var pi2 = Math.PI * 2;
  38458. var step = pi2 / tessellation * arc;
  38459. var returnRadius = function () { return radius; };
  38460. var radiusFunctionFinal = radiusFunction || returnRadius;
  38461. var circlePath;
  38462. var rad;
  38463. var normal;
  38464. var rotated;
  38465. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38466. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38467. for (var i = 0; i < path.length; i++) {
  38468. rad = radiusFunctionFinal(i, distances[i]); // current radius
  38469. circlePath = Array(); // current circle array
  38470. normal = normals[i]; // current normal
  38471. for (var t = 0; t < tessellation; t++) {
  38472. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  38473. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  38474. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  38475. rotated.scaleInPlace(rad).addInPlace(path[i]);
  38476. circlePath[t] = rotated;
  38477. }
  38478. circlePaths[index] = circlePath;
  38479. index++;
  38480. }
  38481. // cap
  38482. var capPath = function (nbPoints, pathIndex) {
  38483. var pointCap = Array();
  38484. for (var i = 0; i < nbPoints; i++) {
  38485. pointCap.push(path[pathIndex]);
  38486. }
  38487. return pointCap;
  38488. };
  38489. switch (cap) {
  38490. case BABYLON.Mesh.NO_CAP:
  38491. break;
  38492. case BABYLON.Mesh.CAP_START:
  38493. circlePaths[0] = capPath(tessellation, 0);
  38494. circlePaths[1] = circlePaths[2].slice(0);
  38495. break;
  38496. case BABYLON.Mesh.CAP_END:
  38497. circlePaths[index] = circlePaths[index - 1].slice(0);
  38498. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38499. break;
  38500. case BABYLON.Mesh.CAP_ALL:
  38501. circlePaths[0] = capPath(tessellation, 0);
  38502. circlePaths[1] = circlePaths[2].slice(0);
  38503. circlePaths[index] = circlePaths[index - 1].slice(0);
  38504. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  38505. break;
  38506. default:
  38507. break;
  38508. }
  38509. return circlePaths;
  38510. };
  38511. var path3D;
  38512. var pathArray;
  38513. if (instance) {
  38514. var arc = options.arc || instance.arc;
  38515. path3D = (instance.path3D).update(path);
  38516. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  38517. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  38518. instance.path3D = path3D;
  38519. instance.pathArray = pathArray;
  38520. instance.arc = arc;
  38521. return instance;
  38522. }
  38523. // tube creation
  38524. path3D = new BABYLON.Path3D(path);
  38525. var newPathArray = new Array();
  38526. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38527. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  38528. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  38529. tube.pathArray = pathArray;
  38530. tube.path3D = path3D;
  38531. tube.tessellation = tessellation;
  38532. tube.cap = cap;
  38533. tube.arc = options.arc;
  38534. return tube;
  38535. };
  38536. /**
  38537. * Creates a polyhedron mesh.
  38538. *
  38539. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  38540. * 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
  38541. * to choose the wanted type.
  38542. * The parameter `size` (positive float, default 1) sets the polygon size.
  38543. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  38544. * 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`.
  38545. * 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
  38546. * 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)`).
  38547. * 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
  38548. * 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.
  38549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38550. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  38551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38553. */
  38554. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  38555. var polyhedron = new BABYLON.Mesh(name, scene);
  38556. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38557. polyhedron.sideOrientation = options.sideOrientation;
  38558. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  38559. vertexData.applyToMesh(polyhedron, options.updatable);
  38560. return polyhedron;
  38561. };
  38562. /**
  38563. * Creates a decal mesh.
  38564. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  38565. * 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.
  38566. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  38567. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  38568. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  38569. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  38570. */
  38571. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  38572. var indices = sourceMesh.getIndices();
  38573. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38574. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38575. var position = options.position || BABYLON.Vector3.Zero();
  38576. var normal = options.normal || BABYLON.Vector3.Up();
  38577. var size = options.size || BABYLON.Vector3.One();
  38578. var angle = options.angle || 0;
  38579. // Getting correct rotation
  38580. if (!normal) {
  38581. var target = new BABYLON.Vector3(0, 0, 1);
  38582. var camera = sourceMesh.getScene().activeCamera;
  38583. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  38584. normal = camera.globalPosition.subtract(cameraWorldTarget);
  38585. }
  38586. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  38587. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  38588. var pitch = Math.atan2(normal.y, len);
  38589. // Matrix
  38590. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  38591. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  38592. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  38593. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  38594. var vertexData = new BABYLON.VertexData();
  38595. vertexData.indices = [];
  38596. vertexData.positions = [];
  38597. vertexData.normals = [];
  38598. vertexData.uvs = [];
  38599. var currentVertexDataIndex = 0;
  38600. var extractDecalVector3 = function (indexId) {
  38601. var vertexId = indices[indexId];
  38602. var result = new BABYLON.PositionNormalVertex();
  38603. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  38604. // Send vector to decal local world
  38605. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  38606. // Get normal
  38607. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  38608. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  38609. return result;
  38610. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  38611. var clip = function (vertices, axis) {
  38612. if (vertices.length === 0) {
  38613. return vertices;
  38614. }
  38615. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  38616. var clipVertices = function (v0, v1) {
  38617. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  38618. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  38619. };
  38620. var result = new Array();
  38621. for (var index = 0; index < vertices.length; index += 3) {
  38622. var v1Out;
  38623. var v2Out;
  38624. var v3Out;
  38625. var total = 0;
  38626. var nV1, nV2, nV3, nV4;
  38627. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  38628. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  38629. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  38630. v1Out = d1 > 0;
  38631. v2Out = d2 > 0;
  38632. v3Out = d3 > 0;
  38633. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  38634. switch (total) {
  38635. case 0:
  38636. result.push(vertices[index]);
  38637. result.push(vertices[index + 1]);
  38638. result.push(vertices[index + 2]);
  38639. break;
  38640. case 1:
  38641. if (v1Out) {
  38642. nV1 = vertices[index + 1];
  38643. nV2 = vertices[index + 2];
  38644. nV3 = clipVertices(vertices[index], nV1);
  38645. nV4 = clipVertices(vertices[index], nV2);
  38646. }
  38647. if (v2Out) {
  38648. nV1 = vertices[index];
  38649. nV2 = vertices[index + 2];
  38650. nV3 = clipVertices(vertices[index + 1], nV1);
  38651. nV4 = clipVertices(vertices[index + 1], nV2);
  38652. result.push(nV3);
  38653. result.push(nV2.clone());
  38654. result.push(nV1.clone());
  38655. result.push(nV2.clone());
  38656. result.push(nV3.clone());
  38657. result.push(nV4);
  38658. break;
  38659. }
  38660. if (v3Out) {
  38661. nV1 = vertices[index];
  38662. nV2 = vertices[index + 1];
  38663. nV3 = clipVertices(vertices[index + 2], nV1);
  38664. nV4 = clipVertices(vertices[index + 2], nV2);
  38665. }
  38666. result.push(nV1.clone());
  38667. result.push(nV2.clone());
  38668. result.push(nV3);
  38669. result.push(nV4);
  38670. result.push(nV3.clone());
  38671. result.push(nV2.clone());
  38672. break;
  38673. case 2:
  38674. if (!v1Out) {
  38675. nV1 = vertices[index].clone();
  38676. nV2 = clipVertices(nV1, vertices[index + 1]);
  38677. nV3 = clipVertices(nV1, vertices[index + 2]);
  38678. result.push(nV1);
  38679. result.push(nV2);
  38680. result.push(nV3);
  38681. }
  38682. if (!v2Out) {
  38683. nV1 = vertices[index + 1].clone();
  38684. nV2 = clipVertices(nV1, vertices[index + 2]);
  38685. nV3 = clipVertices(nV1, vertices[index]);
  38686. result.push(nV1);
  38687. result.push(nV2);
  38688. result.push(nV3);
  38689. }
  38690. if (!v3Out) {
  38691. nV1 = vertices[index + 2].clone();
  38692. nV2 = clipVertices(nV1, vertices[index]);
  38693. nV3 = clipVertices(nV1, vertices[index + 1]);
  38694. result.push(nV1);
  38695. result.push(nV2);
  38696. result.push(nV3);
  38697. }
  38698. break;
  38699. case 3:
  38700. break;
  38701. }
  38702. }
  38703. return result;
  38704. };
  38705. for (var index = 0; index < indices.length; index += 3) {
  38706. var faceVertices = new Array();
  38707. faceVertices.push(extractDecalVector3(index));
  38708. faceVertices.push(extractDecalVector3(index + 1));
  38709. faceVertices.push(extractDecalVector3(index + 2));
  38710. // Clip
  38711. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38712. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38713. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38714. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38715. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38716. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38717. if (faceVertices.length === 0) {
  38718. continue;
  38719. }
  38720. // Add UVs and get back to world
  38721. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38722. var vertex = faceVertices[vIndex];
  38723. //TODO check for Int32Array | Uint32Array | Uint16Array
  38724. vertexData.indices.push(currentVertexDataIndex);
  38725. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38726. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38727. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38728. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38729. currentVertexDataIndex++;
  38730. }
  38731. }
  38732. // Return mesh
  38733. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38734. vertexData.applyToMesh(decal);
  38735. decal.position = position.clone();
  38736. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38737. return decal;
  38738. };
  38739. // Privates
  38740. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  38741. // extrusion geometry
  38742. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38743. var tangents = path3D.getTangents();
  38744. var normals = path3D.getNormals();
  38745. var binormals = path3D.getBinormals();
  38746. var distances = path3D.getDistances();
  38747. var angle = 0;
  38748. var returnScale = function () { return scale; };
  38749. var returnRotation = function () { return rotation; };
  38750. var rotate = custom ? rotateFunction : returnRotation;
  38751. var scl = custom ? scaleFunction : returnScale;
  38752. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38753. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38754. for (var i = 0; i < curve.length; i++) {
  38755. var shapePath = new Array();
  38756. var angleStep = rotate(i, distances[i]);
  38757. var scaleRatio = scl(i, distances[i]);
  38758. for (var p = 0; p < shape.length; p++) {
  38759. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38760. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38761. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38762. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38763. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38764. shapePath[p] = rotated;
  38765. }
  38766. shapePaths[index] = shapePath;
  38767. angle += angleStep;
  38768. index++;
  38769. }
  38770. // cap
  38771. var capPath = function (shapePath) {
  38772. var pointCap = Array();
  38773. var barycenter = BABYLON.Vector3.Zero();
  38774. var i;
  38775. for (i = 0; i < shapePath.length; i++) {
  38776. barycenter.addInPlace(shapePath[i]);
  38777. }
  38778. barycenter.scaleInPlace(1.0 / shapePath.length);
  38779. for (i = 0; i < shapePath.length; i++) {
  38780. pointCap.push(barycenter);
  38781. }
  38782. return pointCap;
  38783. };
  38784. switch (cap) {
  38785. case BABYLON.Mesh.NO_CAP:
  38786. break;
  38787. case BABYLON.Mesh.CAP_START:
  38788. shapePaths[0] = capPath(shapePaths[2]);
  38789. shapePaths[1] = shapePaths[2];
  38790. break;
  38791. case BABYLON.Mesh.CAP_END:
  38792. shapePaths[index] = shapePaths[index - 1];
  38793. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38794. break;
  38795. case BABYLON.Mesh.CAP_ALL:
  38796. shapePaths[0] = capPath(shapePaths[2]);
  38797. shapePaths[1] = shapePaths[2];
  38798. shapePaths[index] = shapePaths[index - 1];
  38799. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38800. break;
  38801. default:
  38802. break;
  38803. }
  38804. return shapePaths;
  38805. };
  38806. var path3D;
  38807. var pathArray;
  38808. if (instance) {
  38809. path3D = (instance.path3D).update(curve);
  38810. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38811. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38812. return instance;
  38813. }
  38814. // extruded shape creation
  38815. path3D = new BABYLON.Path3D(curve);
  38816. var newShapePaths = new Array();
  38817. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38818. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38819. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  38820. extrudedGeneric.pathArray = pathArray;
  38821. extrudedGeneric.path3D = path3D;
  38822. extrudedGeneric.cap = cap;
  38823. return extrudedGeneric;
  38824. };
  38825. return MeshBuilder;
  38826. }());
  38827. BABYLON.MeshBuilder = MeshBuilder;
  38828. })(BABYLON || (BABYLON = {}));
  38829. //# sourceMappingURL=babylon.meshBuilder.js.map
  38830. var BABYLON;
  38831. (function (BABYLON) {
  38832. var Layer = (function () {
  38833. function Layer(name, imgUrl, scene, isBackground, color) {
  38834. this.name = name;
  38835. this.scale = new BABYLON.Vector2(1, 1);
  38836. this.offset = new BABYLON.Vector2(0, 0);
  38837. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  38838. this.layerMask = 0x0FFFFFFF;
  38839. this._vertexBuffers = {};
  38840. // Events
  38841. /**
  38842. * An event triggered when the layer is disposed.
  38843. * @type {BABYLON.Observable}
  38844. */
  38845. this.onDisposeObservable = new BABYLON.Observable();
  38846. /**
  38847. * An event triggered before rendering the scene
  38848. * @type {BABYLON.Observable}
  38849. */
  38850. this.onBeforeRenderObservable = new BABYLON.Observable();
  38851. /**
  38852. * An event triggered after rendering the scene
  38853. * @type {BABYLON.Observable}
  38854. */
  38855. this.onAfterRenderObservable = new BABYLON.Observable();
  38856. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  38857. this.isBackground = isBackground === undefined ? true : isBackground;
  38858. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  38859. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38860. this._scene.layers.push(this);
  38861. var engine = this._scene.getEngine();
  38862. // VBO
  38863. var vertices = [];
  38864. vertices.push(1, 1);
  38865. vertices.push(-1, 1);
  38866. vertices.push(-1, -1);
  38867. vertices.push(1, -1);
  38868. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38870. // Indices
  38871. var indices = [];
  38872. indices.push(0);
  38873. indices.push(1);
  38874. indices.push(2);
  38875. indices.push(0);
  38876. indices.push(2);
  38877. indices.push(3);
  38878. this._indexBuffer = engine.createIndexBuffer(indices);
  38879. // Effects
  38880. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  38881. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  38882. }
  38883. Object.defineProperty(Layer.prototype, "onDispose", {
  38884. set: function (callback) {
  38885. if (this._onDisposeObserver) {
  38886. this.onDisposeObservable.remove(this._onDisposeObserver);
  38887. }
  38888. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38889. },
  38890. enumerable: true,
  38891. configurable: true
  38892. });
  38893. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  38894. set: function (callback) {
  38895. if (this._onBeforeRenderObserver) {
  38896. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  38897. }
  38898. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  38899. },
  38900. enumerable: true,
  38901. configurable: true
  38902. });
  38903. Object.defineProperty(Layer.prototype, "onAfterRender", {
  38904. set: function (callback) {
  38905. if (this._onAfterRenderObserver) {
  38906. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  38907. }
  38908. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  38909. },
  38910. enumerable: true,
  38911. configurable: true
  38912. });
  38913. Layer.prototype.render = function () {
  38914. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  38915. // Check
  38916. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  38917. return;
  38918. var engine = this._scene.getEngine();
  38919. this.onBeforeRenderObservable.notifyObservers(this);
  38920. // Render
  38921. engine.enableEffect(currentEffect);
  38922. engine.setState(false);
  38923. // Texture
  38924. currentEffect.setTexture("textureSampler", this.texture);
  38925. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  38926. // Color
  38927. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  38928. // Scale / offset
  38929. currentEffect.setVector2("offset", this.offset);
  38930. currentEffect.setVector2("scale", this.scale);
  38931. // VBOs
  38932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38933. // Draw order
  38934. if (!this.alphaTest) {
  38935. engine.setAlphaMode(this.alphaBlendingMode);
  38936. engine.draw(true, 0, 6);
  38937. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38938. }
  38939. else {
  38940. engine.draw(true, 0, 6);
  38941. }
  38942. this.onAfterRenderObservable.notifyObservers(this);
  38943. };
  38944. Layer.prototype.dispose = function () {
  38945. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38946. if (vertexBuffer) {
  38947. vertexBuffer.dispose();
  38948. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38949. }
  38950. if (this._indexBuffer) {
  38951. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38952. this._indexBuffer = null;
  38953. }
  38954. if (this.texture) {
  38955. this.texture.dispose();
  38956. this.texture = null;
  38957. }
  38958. // Remove from scene
  38959. var index = this._scene.layers.indexOf(this);
  38960. this._scene.layers.splice(index, 1);
  38961. // Callback
  38962. this.onDisposeObservable.notifyObservers(this);
  38963. this.onDisposeObservable.clear();
  38964. this.onAfterRenderObservable.clear();
  38965. this.onBeforeRenderObservable.clear();
  38966. };
  38967. return Layer;
  38968. }());
  38969. BABYLON.Layer = Layer;
  38970. })(BABYLON || (BABYLON = {}));
  38971. //# sourceMappingURL=babylon.layer.js.map
  38972. var BABYLON;
  38973. (function (BABYLON) {
  38974. var BlurPostProcess = (function (_super) {
  38975. __extends(BlurPostProcess, _super);
  38976. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  38977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38978. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38979. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  38980. _this.direction = direction;
  38981. _this._packedFloat = false;
  38982. _this.onApplyObservable.add(function (effect) {
  38983. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  38984. });
  38985. _this.kernel = kernel;
  38986. return _this;
  38987. }
  38988. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  38989. /**
  38990. * Gets the length in pixels of the blur sample region
  38991. */
  38992. get: function () {
  38993. return this._idealKernel;
  38994. },
  38995. /**
  38996. * Sets the length in pixels of the blur sample region
  38997. */
  38998. set: function (v) {
  38999. if (this._idealKernel === v) {
  39000. return;
  39001. }
  39002. v = Math.max(v, 1);
  39003. this._idealKernel = v;
  39004. this._kernel = this._nearestBestKernel(v);
  39005. this._updateParameters();
  39006. },
  39007. enumerable: true,
  39008. configurable: true
  39009. });
  39010. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  39011. /**
  39012. * Gets wether or not the blur is unpacking/repacking floats
  39013. */
  39014. get: function () {
  39015. return this._packedFloat;
  39016. },
  39017. /**
  39018. * Sets wether or not the blur needs to unpack/repack floats
  39019. */
  39020. set: function (v) {
  39021. if (this._packedFloat === v) {
  39022. return;
  39023. }
  39024. this._packedFloat = v;
  39025. this._updateParameters();
  39026. },
  39027. enumerable: true,
  39028. configurable: true
  39029. });
  39030. BlurPostProcess.prototype._updateParameters = function () {
  39031. // Generate sampling offsets and weights
  39032. var N = this._kernel;
  39033. var centerIndex = (N - 1) / 2;
  39034. // Generate Gaussian sampling weights over kernel
  39035. var offsets = [];
  39036. var weights = [];
  39037. var totalWeight = 0;
  39038. for (var i = 0; i < N; i++) {
  39039. var u = i / (N - 1);
  39040. var w = this._gaussianWeight(u * 2.0 - 1);
  39041. offsets[i] = (i - centerIndex);
  39042. weights[i] = w;
  39043. totalWeight += w;
  39044. }
  39045. // Normalize weights
  39046. for (var i = 0; i < weights.length; i++) {
  39047. weights[i] /= totalWeight;
  39048. }
  39049. // Optimize: combine samples to take advantage of hardware linear sampling
  39050. // Walk from left to center, combining pairs (symmetrically)
  39051. var linearSamplingWeights = [];
  39052. var linearSamplingOffsets = [];
  39053. var linearSamplingMap = [];
  39054. for (var i = 0; i <= centerIndex; i += 2) {
  39055. var j = Math.min(i + 1, Math.floor(centerIndex));
  39056. var singleCenterSample = i === j;
  39057. if (singleCenterSample) {
  39058. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  39059. }
  39060. else {
  39061. var sharedCell = j === centerIndex;
  39062. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  39063. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  39064. if (offsetLinear === 0) {
  39065. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  39066. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  39067. }
  39068. else {
  39069. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  39070. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  39071. }
  39072. }
  39073. }
  39074. for (var i = 0; i < linearSamplingMap.length; i++) {
  39075. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  39076. linearSamplingWeights[i] = linearSamplingMap[i].w;
  39077. }
  39078. // Replace with optimized
  39079. offsets = linearSamplingOffsets;
  39080. weights = linearSamplingWeights;
  39081. // Generate shaders
  39082. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  39083. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  39084. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  39085. var defines = "";
  39086. for (var i = 0; i < varyingCount; i++) {
  39087. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  39088. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  39089. }
  39090. var depCount = 0;
  39091. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  39092. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  39093. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  39094. depCount++;
  39095. }
  39096. if (this.packedFloat) {
  39097. defines += "#define PACKEDFLOAT 1";
  39098. }
  39099. this.updateEffect(defines, null, null, {
  39100. varyingCount: varyingCount,
  39101. depCount: depCount
  39102. });
  39103. };
  39104. /**
  39105. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  39106. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  39107. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  39108. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  39109. * The gaps between physical kernels are compensated for in the weighting of the samples
  39110. * @param idealKernel Ideal blur kernel.
  39111. * @return Nearest best kernel.
  39112. */
  39113. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  39114. var v = Math.round(idealKernel);
  39115. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  39116. var k = _a[_i];
  39117. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  39118. return Math.max(k, 3);
  39119. }
  39120. }
  39121. return Math.max(v, 3);
  39122. };
  39123. /**
  39124. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  39125. * @param x The point on the Gaussian distribution to sample.
  39126. * @return the value of the Gaussian function at x.
  39127. */
  39128. BlurPostProcess.prototype._gaussianWeight = function (x) {
  39129. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  39130. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  39131. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  39132. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  39133. // truncated at around 1.3% of peak strength.
  39134. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  39135. var sigma = (1 / 3);
  39136. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  39137. var exponent = -((x * x) / (2.0 * sigma * sigma));
  39138. var weight = (1.0 / denominator) * Math.exp(exponent);
  39139. return weight;
  39140. };
  39141. /**
  39142. * Generates a string that can be used as a floating point number in GLSL.
  39143. * @param x Value to print.
  39144. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  39145. * @return GLSL float string.
  39146. */
  39147. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  39148. if (decimalFigures === void 0) { decimalFigures = 8; }
  39149. return x.toFixed(decimalFigures).replace(/0+$/, '');
  39150. };
  39151. return BlurPostProcess;
  39152. }(BABYLON.PostProcess));
  39153. BABYLON.BlurPostProcess = BlurPostProcess;
  39154. })(BABYLON || (BABYLON = {}));
  39155. //# sourceMappingURL=babylon.blurPostProcess.js.map
  39156. var BABYLON;
  39157. (function (BABYLON) {
  39158. var FxaaPostProcess = (function (_super) {
  39159. __extends(FxaaPostProcess, _super);
  39160. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  39161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39162. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  39163. _this.onApplyObservable.add(function (effect) {
  39164. var texelSize = _this.texelSize;
  39165. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  39166. });
  39167. return _this;
  39168. }
  39169. return FxaaPostProcess;
  39170. }(BABYLON.PostProcess));
  39171. BABYLON.FxaaPostProcess = FxaaPostProcess;
  39172. })(BABYLON || (BABYLON = {}));
  39173. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  39174. var BABYLON;
  39175. (function (BABYLON) {
  39176. var HighlightsPostProcess = (function (_super) {
  39177. __extends(HighlightsPostProcess, _super);
  39178. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  39179. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39180. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  39181. }
  39182. return HighlightsPostProcess;
  39183. }(BABYLON.PostProcess));
  39184. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  39185. })(BABYLON || (BABYLON = {}));
  39186. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  39187. var BABYLON;
  39188. (function (BABYLON) {
  39189. var ImageProcessingPostProcess = (function (_super) {
  39190. __extends(ImageProcessingPostProcess, _super);
  39191. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  39192. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  39193. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  39194. _this._fromLinearSpace = true;
  39195. /**
  39196. * Defines cache preventing GC.
  39197. */
  39198. _this._defines = {
  39199. IMAGEPROCESSING: false,
  39200. VIGNETTE: false,
  39201. VIGNETTEBLENDMODEMULTIPLY: false,
  39202. VIGNETTEBLENDMODEOPAQUE: false,
  39203. TONEMAPPING: false,
  39204. CONTRAST: false,
  39205. COLORCURVES: false,
  39206. COLORGRADING: false,
  39207. FROMLINEARSPACE: false,
  39208. SAMPLER3DGREENDEPTH: false,
  39209. SAMPLER3DBGRMAP: false,
  39210. IMAGEPROCESSINGPOSTPROCESS: false,
  39211. EXPOSURE: false,
  39212. };
  39213. // Setup the default processing configuration to the scene.
  39214. _this._attachImageProcessingConfiguration(null);
  39215. _this.imageProcessingConfiguration.applyByPostProcess = true;
  39216. _this._updateParameters();
  39217. _this.onApply = function (effect) {
  39218. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  39219. };
  39220. return _this;
  39221. }
  39222. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  39223. /**
  39224. * Gets the image processing configuration used either in this material.
  39225. */
  39226. get: function () {
  39227. return this._imageProcessingConfiguration;
  39228. },
  39229. /**
  39230. * Sets the Default image processing configuration used either in the this material.
  39231. *
  39232. * If sets to null, the scene one is in use.
  39233. */
  39234. set: function (value) {
  39235. this._attachImageProcessingConfiguration(value);
  39236. },
  39237. enumerable: true,
  39238. configurable: true
  39239. });
  39240. /**
  39241. * Attaches a new image processing configuration to the PBR Material.
  39242. * @param configuration
  39243. */
  39244. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  39245. var _this = this;
  39246. if (configuration === this._imageProcessingConfiguration) {
  39247. return;
  39248. }
  39249. // Detaches observer.
  39250. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39251. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39252. }
  39253. // Pick the scene configuration if needed.
  39254. if (!configuration) {
  39255. var camera = this.getCamera();
  39256. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  39257. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  39258. }
  39259. else {
  39260. this._imageProcessingConfiguration = configuration;
  39261. }
  39262. // Attaches observer.
  39263. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39264. _this._updateParameters();
  39265. });
  39266. // Ensure the effect will be rebuilt.
  39267. this._updateParameters();
  39268. };
  39269. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  39270. /**
  39271. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  39272. */
  39273. get: function () {
  39274. return this.imageProcessingConfiguration.colorCurves;
  39275. },
  39276. /**
  39277. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  39278. */
  39279. set: function (value) {
  39280. this.imageProcessingConfiguration.colorCurves = value;
  39281. },
  39282. enumerable: true,
  39283. configurable: true
  39284. });
  39285. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  39286. /**
  39287. * Gets wether the color curves effect is enabled.
  39288. */
  39289. get: function () {
  39290. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39291. },
  39292. /**
  39293. * Sets wether the color curves effect is enabled.
  39294. */
  39295. set: function (value) {
  39296. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39297. },
  39298. enumerable: true,
  39299. configurable: true
  39300. });
  39301. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  39302. /**
  39303. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  39304. */
  39305. get: function () {
  39306. return this.imageProcessingConfiguration.colorGradingTexture;
  39307. },
  39308. /**
  39309. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  39310. */
  39311. set: function (value) {
  39312. this.imageProcessingConfiguration.colorGradingTexture = value;
  39313. },
  39314. enumerable: true,
  39315. configurable: true
  39316. });
  39317. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  39318. /**
  39319. * Gets wether the color grading effect is enabled.
  39320. */
  39321. get: function () {
  39322. return this.imageProcessingConfiguration.colorGradingEnabled;
  39323. },
  39324. /**
  39325. * Gets wether the color grading effect is enabled.
  39326. */
  39327. set: function (value) {
  39328. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39329. },
  39330. enumerable: true,
  39331. configurable: true
  39332. });
  39333. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  39334. /**
  39335. * Gets exposure used in the effect.
  39336. */
  39337. get: function () {
  39338. return this.imageProcessingConfiguration.exposure;
  39339. },
  39340. /**
  39341. * Sets exposure used in the effect.
  39342. */
  39343. set: function (value) {
  39344. this.imageProcessingConfiguration.exposure = value;
  39345. },
  39346. enumerable: true,
  39347. configurable: true
  39348. });
  39349. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  39350. /**
  39351. * Gets wether tonemapping is enabled or not.
  39352. */
  39353. get: function () {
  39354. return this._imageProcessingConfiguration.toneMappingEnabled;
  39355. },
  39356. /**
  39357. * Sets wether tonemapping is enabled or not
  39358. */
  39359. set: function (value) {
  39360. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39361. },
  39362. enumerable: true,
  39363. configurable: true
  39364. });
  39365. ;
  39366. ;
  39367. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  39368. /**
  39369. * Gets contrast used in the effect.
  39370. */
  39371. get: function () {
  39372. return this.imageProcessingConfiguration.contrast;
  39373. },
  39374. /**
  39375. * Sets contrast used in the effect.
  39376. */
  39377. set: function (value) {
  39378. this.imageProcessingConfiguration.contrast = value;
  39379. },
  39380. enumerable: true,
  39381. configurable: true
  39382. });
  39383. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  39384. /**
  39385. * Gets Vignette stretch size.
  39386. */
  39387. get: function () {
  39388. return this.imageProcessingConfiguration.vignetteStretch;
  39389. },
  39390. /**
  39391. * Sets Vignette stretch size.
  39392. */
  39393. set: function (value) {
  39394. this.imageProcessingConfiguration.vignetteStretch = value;
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  39400. /**
  39401. * Gets Vignette centre X Offset.
  39402. */
  39403. get: function () {
  39404. return this.imageProcessingConfiguration.vignetteCentreX;
  39405. },
  39406. /**
  39407. * Sets Vignette centre X Offset.
  39408. */
  39409. set: function (value) {
  39410. this.imageProcessingConfiguration.vignetteCentreX = value;
  39411. },
  39412. enumerable: true,
  39413. configurable: true
  39414. });
  39415. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  39416. /**
  39417. * Gets Vignette centre Y Offset.
  39418. */
  39419. get: function () {
  39420. return this.imageProcessingConfiguration.vignetteCentreY;
  39421. },
  39422. /**
  39423. * Sets Vignette centre Y Offset.
  39424. */
  39425. set: function (value) {
  39426. this.imageProcessingConfiguration.vignetteCentreY = value;
  39427. },
  39428. enumerable: true,
  39429. configurable: true
  39430. });
  39431. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  39432. /**
  39433. * Gets Vignette weight or intensity of the vignette effect.
  39434. */
  39435. get: function () {
  39436. return this.imageProcessingConfiguration.vignetteWeight;
  39437. },
  39438. /**
  39439. * Sets Vignette weight or intensity of the vignette effect.
  39440. */
  39441. set: function (value) {
  39442. this.imageProcessingConfiguration.vignetteWeight = value;
  39443. },
  39444. enumerable: true,
  39445. configurable: true
  39446. });
  39447. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  39448. /**
  39449. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  39450. * if vignetteEnabled is set to true.
  39451. */
  39452. get: function () {
  39453. return this.imageProcessingConfiguration.vignetteColor;
  39454. },
  39455. /**
  39456. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  39457. * if vignetteEnabled is set to true.
  39458. */
  39459. set: function (value) {
  39460. this.imageProcessingConfiguration.vignetteColor = value;
  39461. },
  39462. enumerable: true,
  39463. configurable: true
  39464. });
  39465. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  39466. /**
  39467. * Gets Camera field of view used by the Vignette effect.
  39468. */
  39469. get: function () {
  39470. return this.imageProcessingConfiguration.vignetteCameraFov;
  39471. },
  39472. /**
  39473. * Sets Camera field of view used by the Vignette effect.
  39474. */
  39475. set: function (value) {
  39476. this.imageProcessingConfiguration.vignetteCameraFov = value;
  39477. },
  39478. enumerable: true,
  39479. configurable: true
  39480. });
  39481. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  39482. /**
  39483. * Gets the vignette blend mode allowing different kind of effect.
  39484. */
  39485. get: function () {
  39486. return this.imageProcessingConfiguration.vignetteBlendMode;
  39487. },
  39488. /**
  39489. * Sets the vignette blend mode allowing different kind of effect.
  39490. */
  39491. set: function (value) {
  39492. this.imageProcessingConfiguration.vignetteBlendMode = value;
  39493. },
  39494. enumerable: true,
  39495. configurable: true
  39496. });
  39497. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  39498. /**
  39499. * Gets wether the vignette effect is enabled.
  39500. */
  39501. get: function () {
  39502. return this.imageProcessingConfiguration.vignetteEnabled;
  39503. },
  39504. /**
  39505. * Sets wether the vignette effect is enabled.
  39506. */
  39507. set: function (value) {
  39508. this.imageProcessingConfiguration.vignetteEnabled = value;
  39509. },
  39510. enumerable: true,
  39511. configurable: true
  39512. });
  39513. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  39514. /**
  39515. * Gets wether the input of the processing is in Gamma or Linear Space.
  39516. */
  39517. get: function () {
  39518. return this._fromLinearSpace;
  39519. },
  39520. /**
  39521. * Sets wether the input of the processing is in Gamma or Linear Space.
  39522. */
  39523. set: function (value) {
  39524. if (this._fromLinearSpace === value) {
  39525. return;
  39526. }
  39527. this._fromLinearSpace = value;
  39528. this._updateParameters();
  39529. },
  39530. enumerable: true,
  39531. configurable: true
  39532. });
  39533. ImageProcessingPostProcess.prototype._updateParameters = function () {
  39534. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  39535. this.imageProcessingConfiguration.prepareDefines(this._defines);
  39536. var defines = "";
  39537. for (var define in this._defines) {
  39538. if (this._defines[define]) {
  39539. defines += "#define " + define + ";\r\n";
  39540. }
  39541. }
  39542. var samplers = ["textureSampler"];
  39543. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  39544. var uniforms = ["scale"];
  39545. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  39546. this.updateEffect(defines, uniforms, samplers);
  39547. };
  39548. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  39549. _super.prototype.dispose.call(this, camera);
  39550. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39551. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39552. }
  39553. this.imageProcessingConfiguration.applyByPostProcess = false;
  39554. };
  39555. return ImageProcessingPostProcess;
  39556. }(BABYLON.PostProcess));
  39557. __decorate([
  39558. BABYLON.serialize()
  39559. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  39560. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  39561. })(BABYLON || (BABYLON = {}));
  39562. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  39563. var BABYLON;
  39564. (function (BABYLON) {
  39565. /**
  39566. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  39567. * It can help converting any input color in a desired output one. This can then be used to create effects
  39568. * from sepia, black and white to sixties or futuristic rendering...
  39569. *
  39570. * The only supported format is currently 3dl.
  39571. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  39572. */
  39573. var ColorGradingTexture = (function (_super) {
  39574. __extends(ColorGradingTexture, _super);
  39575. /**
  39576. * Instantiates a ColorGradingTexture from the following parameters.
  39577. *
  39578. * @param url The location of the color gradind data (currently only supporting 3dl)
  39579. * @param scene The scene the texture will be used in
  39580. */
  39581. function ColorGradingTexture(url, scene) {
  39582. var _this = _super.call(this, scene) || this;
  39583. if (!url) {
  39584. return _this;
  39585. }
  39586. _this._textureMatrix = BABYLON.Matrix.Identity();
  39587. _this.name = url;
  39588. _this.url = url;
  39589. _this.hasAlpha = false;
  39590. _this.isCube = false;
  39591. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39592. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39593. _this.anisotropicFilteringLevel = 1;
  39594. _this._texture = _this._getFromCache(url, true);
  39595. if (!_this._texture) {
  39596. if (!scene.useDelayedTextureLoading) {
  39597. _this.loadTexture();
  39598. }
  39599. else {
  39600. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39601. }
  39602. }
  39603. return _this;
  39604. }
  39605. /**
  39606. * Returns the texture matrix used in most of the material.
  39607. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  39608. */
  39609. ColorGradingTexture.prototype.getTextureMatrix = function () {
  39610. return this._textureMatrix;
  39611. };
  39612. /**
  39613. * Occurs when the file being loaded is a .3dl LUT file.
  39614. */
  39615. ColorGradingTexture.prototype.load3dlTexture = function () {
  39616. var _this = this;
  39617. var mipLevels = 0;
  39618. var floatArrayView = null;
  39619. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39620. this._texture = texture;
  39621. var callback = function (text) {
  39622. var data;
  39623. var tempData;
  39624. var line;
  39625. var lines = text.split('\n');
  39626. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  39627. var maxColor = 0;
  39628. for (var i = 0; i < lines.length; i++) {
  39629. line = lines[i];
  39630. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  39631. continue;
  39632. if (line.indexOf('#') === 0)
  39633. continue;
  39634. var words = line.split(" ");
  39635. if (size === 0) {
  39636. // Number of space + one
  39637. size = words.length;
  39638. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  39639. tempData = new Float32Array(size * size * size * 4);
  39640. continue;
  39641. }
  39642. if (size != 0) {
  39643. var r = Math.max(parseInt(words[0]), 0);
  39644. var g = Math.max(parseInt(words[1]), 0);
  39645. var b = Math.max(parseInt(words[2]), 0);
  39646. maxColor = Math.max(r, maxColor);
  39647. maxColor = Math.max(g, maxColor);
  39648. maxColor = Math.max(b, maxColor);
  39649. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  39650. tempData[pixelStorageIndex + 0] = r;
  39651. tempData[pixelStorageIndex + 1] = g;
  39652. tempData[pixelStorageIndex + 2] = b;
  39653. pixelIndexSlice++;
  39654. if (pixelIndexSlice % size == 0) {
  39655. pixelIndexH++;
  39656. pixelIndexSlice = 0;
  39657. if (pixelIndexH % size == 0) {
  39658. pixelIndexW++;
  39659. pixelIndexH = 0;
  39660. }
  39661. }
  39662. }
  39663. }
  39664. for (var i = 0; i < tempData.length; i++) {
  39665. if (i > 0 && (i + 1) % 4 === 0) {
  39666. data[i] = 255;
  39667. }
  39668. else {
  39669. var value = tempData[i];
  39670. data[i] = (value / maxColor * 255);
  39671. }
  39672. }
  39673. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  39674. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  39675. };
  39676. BABYLON.Tools.LoadFile(this.url, callback);
  39677. return this._texture;
  39678. };
  39679. /**
  39680. * Starts the loading process of the texture.
  39681. */
  39682. ColorGradingTexture.prototype.loadTexture = function () {
  39683. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  39684. this.load3dlTexture();
  39685. }
  39686. };
  39687. /**
  39688. * Clones the color gradind texture.
  39689. */
  39690. ColorGradingTexture.prototype.clone = function () {
  39691. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  39692. // Base texture
  39693. newTexture.level = this.level;
  39694. return newTexture;
  39695. };
  39696. /**
  39697. * Called during delayed load for textures.
  39698. */
  39699. ColorGradingTexture.prototype.delayLoad = function () {
  39700. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39701. return;
  39702. }
  39703. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39704. this._texture = this._getFromCache(this.url, true);
  39705. if (!this._texture) {
  39706. this.loadTexture();
  39707. }
  39708. };
  39709. /**
  39710. * Parses a color grading texture serialized by Babylon.
  39711. * @param parsedTexture The texture information being parsedTexture
  39712. * @param scene The scene to load the texture in
  39713. * @param rootUrl The root url of the data assets to load
  39714. * @return A color gradind texture
  39715. */
  39716. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39717. var texture = null;
  39718. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39719. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  39720. texture.name = parsedTexture.name;
  39721. texture.level = parsedTexture.level;
  39722. }
  39723. return texture;
  39724. };
  39725. /**
  39726. * Serializes the LUT texture to json format.
  39727. */
  39728. ColorGradingTexture.prototype.serialize = function () {
  39729. if (!this.name) {
  39730. return null;
  39731. }
  39732. var serializationObject = {};
  39733. serializationObject.name = this.name;
  39734. serializationObject.level = this.level;
  39735. serializationObject.customType = "BABYLON.ColorGradingTexture";
  39736. return serializationObject;
  39737. };
  39738. return ColorGradingTexture;
  39739. }(BABYLON.BaseTexture));
  39740. /**
  39741. * Empty line regex stored for GC.
  39742. */
  39743. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  39744. BABYLON.ColorGradingTexture = ColorGradingTexture;
  39745. })(BABYLON || (BABYLON = {}));
  39746. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  39747. var BABYLON;
  39748. (function (BABYLON) {
  39749. /**
  39750. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39751. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39752. * 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;
  39753. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39754. */
  39755. var ColorCurves = (function () {
  39756. function ColorCurves() {
  39757. this._dirty = true;
  39758. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  39759. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  39760. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39761. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  39762. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39763. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  39764. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  39765. this._globalHue = 30;
  39766. this._globalDensity = 0;
  39767. this._globalSaturation = 0;
  39768. this._globalExposure = 0;
  39769. this._highlightsHue = 30;
  39770. this._highlightsDensity = 0;
  39771. this._highlightsSaturation = 0;
  39772. this._highlightsExposure = 0;
  39773. this._midtonesHue = 30;
  39774. this._midtonesDensity = 0;
  39775. this._midtonesSaturation = 0;
  39776. this._midtonesExposure = 0;
  39777. this._shadowsHue = 30;
  39778. this._shadowsDensity = 0;
  39779. this._shadowsSaturation = 0;
  39780. this._shadowsExposure = 0;
  39781. }
  39782. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39783. /**
  39784. * Gets the global Hue value.
  39785. * 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).
  39786. */
  39787. get: function () {
  39788. return this._globalHue;
  39789. },
  39790. /**
  39791. * Sets the global Hue value.
  39792. * 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).
  39793. */
  39794. set: function (value) {
  39795. this._globalHue = value;
  39796. this._dirty = true;
  39797. },
  39798. enumerable: true,
  39799. configurable: true
  39800. });
  39801. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39802. /**
  39803. * Gets the global Density value.
  39804. * 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.
  39805. * Values less than zero provide a filter of opposite hue.
  39806. */
  39807. get: function () {
  39808. return this._globalDensity;
  39809. },
  39810. /**
  39811. * Sets the global Density value.
  39812. * 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.
  39813. * Values less than zero provide a filter of opposite hue.
  39814. */
  39815. set: function (value) {
  39816. this._globalDensity = value;
  39817. this._dirty = true;
  39818. },
  39819. enumerable: true,
  39820. configurable: true
  39821. });
  39822. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39823. /**
  39824. * Gets the global Saturation value.
  39825. * 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.
  39826. */
  39827. get: function () {
  39828. return this._globalSaturation;
  39829. },
  39830. /**
  39831. * Sets the global Saturation value.
  39832. * 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.
  39833. */
  39834. set: function (value) {
  39835. this._globalSaturation = value;
  39836. this._dirty = true;
  39837. },
  39838. enumerable: true,
  39839. configurable: true
  39840. });
  39841. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39842. /**
  39843. * Gets the highlights Hue value.
  39844. * 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).
  39845. */
  39846. get: function () {
  39847. return this._highlightsHue;
  39848. },
  39849. /**
  39850. * Sets the highlights Hue value.
  39851. * 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).
  39852. */
  39853. set: function (value) {
  39854. this._highlightsHue = value;
  39855. this._dirty = true;
  39856. },
  39857. enumerable: true,
  39858. configurable: true
  39859. });
  39860. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39861. /**
  39862. * Gets the highlights Density value.
  39863. * 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.
  39864. * Values less than zero provide a filter of opposite hue.
  39865. */
  39866. get: function () {
  39867. return this._highlightsDensity;
  39868. },
  39869. /**
  39870. * Sets the highlights Density value.
  39871. * 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.
  39872. * Values less than zero provide a filter of opposite hue.
  39873. */
  39874. set: function (value) {
  39875. this._highlightsDensity = value;
  39876. this._dirty = true;
  39877. },
  39878. enumerable: true,
  39879. configurable: true
  39880. });
  39881. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39882. /**
  39883. * Gets the highlights Saturation value.
  39884. * 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.
  39885. */
  39886. get: function () {
  39887. return this._highlightsSaturation;
  39888. },
  39889. /**
  39890. * Sets the highlights Saturation value.
  39891. * 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.
  39892. */
  39893. set: function (value) {
  39894. this._highlightsSaturation = value;
  39895. this._dirty = true;
  39896. },
  39897. enumerable: true,
  39898. configurable: true
  39899. });
  39900. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39901. /**
  39902. * Gets the highlights Exposure value.
  39903. * 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.
  39904. */
  39905. get: function () {
  39906. return this._highlightsExposure;
  39907. },
  39908. /**
  39909. * Sets the highlights Exposure value.
  39910. * 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.
  39911. */
  39912. set: function (value) {
  39913. this._highlightsExposure = value;
  39914. this._dirty = true;
  39915. },
  39916. enumerable: true,
  39917. configurable: true
  39918. });
  39919. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39920. /**
  39921. * Gets the midtones Hue value.
  39922. * 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).
  39923. */
  39924. get: function () {
  39925. return this._midtonesHue;
  39926. },
  39927. /**
  39928. * Sets the midtones Hue value.
  39929. * 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).
  39930. */
  39931. set: function (value) {
  39932. this._midtonesHue = value;
  39933. this._dirty = true;
  39934. },
  39935. enumerable: true,
  39936. configurable: true
  39937. });
  39938. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39939. /**
  39940. * Gets the midtones Density value.
  39941. * 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.
  39942. * Values less than zero provide a filter of opposite hue.
  39943. */
  39944. get: function () {
  39945. return this._midtonesDensity;
  39946. },
  39947. /**
  39948. * Sets the midtones Density value.
  39949. * 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.
  39950. * Values less than zero provide a filter of opposite hue.
  39951. */
  39952. set: function (value) {
  39953. this._midtonesDensity = value;
  39954. this._dirty = true;
  39955. },
  39956. enumerable: true,
  39957. configurable: true
  39958. });
  39959. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39960. /**
  39961. * Gets the midtones Saturation value.
  39962. * 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.
  39963. */
  39964. get: function () {
  39965. return this._midtonesSaturation;
  39966. },
  39967. /**
  39968. * Sets the midtones Saturation value.
  39969. * 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.
  39970. */
  39971. set: function (value) {
  39972. this._midtonesSaturation = value;
  39973. this._dirty = true;
  39974. },
  39975. enumerable: true,
  39976. configurable: true
  39977. });
  39978. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39979. /**
  39980. * Gets the midtones Exposure value.
  39981. * 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.
  39982. */
  39983. get: function () {
  39984. return this._midtonesExposure;
  39985. },
  39986. /**
  39987. * Sets the midtones Exposure value.
  39988. * 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.
  39989. */
  39990. set: function (value) {
  39991. this._midtonesExposure = value;
  39992. this._dirty = true;
  39993. },
  39994. enumerable: true,
  39995. configurable: true
  39996. });
  39997. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39998. /**
  39999. * Gets the shadows Hue value.
  40000. * 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).
  40001. */
  40002. get: function () {
  40003. return this._shadowsHue;
  40004. },
  40005. /**
  40006. * Sets the shadows Hue value.
  40007. * 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).
  40008. */
  40009. set: function (value) {
  40010. this._shadowsHue = value;
  40011. this._dirty = true;
  40012. },
  40013. enumerable: true,
  40014. configurable: true
  40015. });
  40016. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  40017. /**
  40018. * Gets the shadows Density value.
  40019. * 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.
  40020. * Values less than zero provide a filter of opposite hue.
  40021. */
  40022. get: function () {
  40023. return this._shadowsDensity;
  40024. },
  40025. /**
  40026. * Sets the shadows Density value.
  40027. * 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.
  40028. * Values less than zero provide a filter of opposite hue.
  40029. */
  40030. set: function (value) {
  40031. this._shadowsDensity = value;
  40032. this._dirty = true;
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  40038. /**
  40039. * Gets the shadows Saturation value.
  40040. * 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.
  40041. */
  40042. get: function () {
  40043. return this._shadowsSaturation;
  40044. },
  40045. /**
  40046. * Sets the shadows Saturation value.
  40047. * 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.
  40048. */
  40049. set: function (value) {
  40050. this._shadowsSaturation = value;
  40051. this._dirty = true;
  40052. },
  40053. enumerable: true,
  40054. configurable: true
  40055. });
  40056. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  40057. /**
  40058. * Gets the shadows Exposure value.
  40059. * 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.
  40060. */
  40061. get: function () {
  40062. return this._shadowsExposure;
  40063. },
  40064. /**
  40065. * Sets the shadows Exposure value.
  40066. * 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.
  40067. */
  40068. set: function (value) {
  40069. this._shadowsExposure = value;
  40070. this._dirty = true;
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. /**
  40076. * Binds the color curves to the shader.
  40077. * @param colorCurves The color curve to bind
  40078. * @param effect The effect to bind to
  40079. */
  40080. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  40081. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  40082. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  40083. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  40084. if (colorCurves._dirty) {
  40085. colorCurves._dirty = false;
  40086. // Fill in global info.
  40087. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  40088. // Compute highlights info.
  40089. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  40090. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  40091. // Compute midtones info.
  40092. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  40093. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  40094. // Compute shadows info.
  40095. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  40096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  40097. // Compute deltas (neutral is midtones).
  40098. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  40099. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  40100. }
  40101. if (effect) {
  40102. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  40103. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  40104. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  40105. }
  40106. };
  40107. /**
  40108. * Prepare the list of uniforms associated with the ColorCurves effects.
  40109. * @param uniformsList The list of uniforms used in the effect
  40110. */
  40111. ColorCurves.PrepareUniforms = function (uniformsList) {
  40112. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  40113. };
  40114. /**
  40115. * Returns color grading data based on a hue, density, saturation and exposure value.
  40116. * @param filterHue The hue of the color filter.
  40117. * @param filterDensity The density of the color filter.
  40118. * @param saturation The saturation.
  40119. * @param exposure The exposure.
  40120. * @param result The result data container.
  40121. */
  40122. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  40123. if (hue == null) {
  40124. return;
  40125. }
  40126. hue = ColorCurves.clamp(hue, 0, 360);
  40127. density = ColorCurves.clamp(density, -100, 100);
  40128. saturation = ColorCurves.clamp(saturation, -100, 100);
  40129. exposure = ColorCurves.clamp(exposure, -100, 100);
  40130. // Remap the slider/config filter density with non-linear mapping and also scale by half
  40131. // so that the maximum filter density is only 50% control. This provides fine control
  40132. // for small values and reasonable range.
  40133. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  40134. density *= 0.5;
  40135. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  40136. if (density < 0) {
  40137. density *= -1;
  40138. hue = (hue + 180) % 360;
  40139. }
  40140. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  40141. result.scaleToRef(2, result);
  40142. result.a = 1 + 0.01 * saturation;
  40143. };
  40144. /**
  40145. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  40146. * @param value The input slider value in range [-100,100].
  40147. * @returns Adjusted value.
  40148. */
  40149. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  40150. value /= 100;
  40151. var x = Math.abs(value);
  40152. x = Math.pow(x, 2);
  40153. if (value < 0) {
  40154. x *= -1;
  40155. }
  40156. x *= 100;
  40157. return x;
  40158. };
  40159. /**
  40160. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  40161. * @param hue The hue (H) input.
  40162. * @param saturation The saturation (S) input.
  40163. * @param brightness The brightness (B) input.
  40164. * @result An RGBA color represented as Vector4.
  40165. */
  40166. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  40167. var h = ColorCurves.clamp(hue, 0, 360);
  40168. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  40169. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  40170. if (s === 0) {
  40171. result.r = v;
  40172. result.g = v;
  40173. result.b = v;
  40174. }
  40175. else {
  40176. // sector 0 to 5
  40177. h /= 60;
  40178. var i = Math.floor(h);
  40179. // fractional part of h
  40180. var f = h - i;
  40181. var p = v * (1 - s);
  40182. var q = v * (1 - s * f);
  40183. var t = v * (1 - s * (1 - f));
  40184. switch (i) {
  40185. case 0:
  40186. result.r = v;
  40187. result.g = t;
  40188. result.b = p;
  40189. break;
  40190. case 1:
  40191. result.r = q;
  40192. result.g = v;
  40193. result.b = p;
  40194. break;
  40195. case 2:
  40196. result.r = p;
  40197. result.g = v;
  40198. result.b = t;
  40199. break;
  40200. case 3:
  40201. result.r = p;
  40202. result.g = q;
  40203. result.b = v;
  40204. break;
  40205. case 4:
  40206. result.r = t;
  40207. result.g = p;
  40208. result.b = v;
  40209. break;
  40210. default:
  40211. result.r = v;
  40212. result.g = p;
  40213. result.b = q;
  40214. break;
  40215. }
  40216. }
  40217. result.a = 1;
  40218. };
  40219. /**
  40220. * Returns a value clamped between min and max
  40221. * @param value The value to clamp
  40222. * @param min The minimum of value
  40223. * @param max The maximum of value
  40224. * @returns The clamped value.
  40225. */
  40226. ColorCurves.clamp = function (value, min, max) {
  40227. return Math.min(Math.max(value, min), max);
  40228. };
  40229. /**
  40230. * Clones the current color curve instance.
  40231. * @return The cloned curves
  40232. */
  40233. ColorCurves.prototype.clone = function () {
  40234. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  40235. };
  40236. /**
  40237. * Serializes the current color curve instance to a json representation.
  40238. * @return a JSON representation
  40239. */
  40240. ColorCurves.prototype.serialize = function () {
  40241. return BABYLON.SerializationHelper.Serialize(this);
  40242. };
  40243. /**
  40244. * Parses the color curve from a json representation.
  40245. * @param source the JSON source to parse
  40246. * @return The parsed curves
  40247. */
  40248. ColorCurves.Parse = function (source) {
  40249. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  40250. };
  40251. return ColorCurves;
  40252. }());
  40253. __decorate([
  40254. BABYLON.serialize()
  40255. ], ColorCurves.prototype, "_globalHue", void 0);
  40256. __decorate([
  40257. BABYLON.serialize()
  40258. ], ColorCurves.prototype, "_globalDensity", void 0);
  40259. __decorate([
  40260. BABYLON.serialize()
  40261. ], ColorCurves.prototype, "_globalSaturation", void 0);
  40262. __decorate([
  40263. BABYLON.serialize()
  40264. ], ColorCurves.prototype, "_globalExposure", void 0);
  40265. __decorate([
  40266. BABYLON.serialize()
  40267. ], ColorCurves.prototype, "_highlightsHue", void 0);
  40268. __decorate([
  40269. BABYLON.serialize()
  40270. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  40271. __decorate([
  40272. BABYLON.serialize()
  40273. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  40274. __decorate([
  40275. BABYLON.serialize()
  40276. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  40277. __decorate([
  40278. BABYLON.serialize()
  40279. ], ColorCurves.prototype, "_midtonesHue", void 0);
  40280. __decorate([
  40281. BABYLON.serialize()
  40282. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  40283. __decorate([
  40284. BABYLON.serialize()
  40285. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  40286. __decorate([
  40287. BABYLON.serialize()
  40288. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  40289. BABYLON.ColorCurves = ColorCurves;
  40290. })(BABYLON || (BABYLON = {}));
  40291. //# sourceMappingURL=babylon.colorCurves.js.map
  40292. var BABYLON;
  40293. (function (BABYLON) {
  40294. var PostProcessRenderPipelineManager = (function () {
  40295. function PostProcessRenderPipelineManager() {
  40296. this._renderPipelines = {};
  40297. }
  40298. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  40299. this._renderPipelines[renderPipeline._name] = renderPipeline;
  40300. };
  40301. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  40302. var renderPipeline = this._renderPipelines[renderPipelineName];
  40303. if (!renderPipeline) {
  40304. return;
  40305. }
  40306. renderPipeline._attachCameras(cameras, unique);
  40307. };
  40308. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  40309. var renderPipeline = this._renderPipelines[renderPipelineName];
  40310. if (!renderPipeline) {
  40311. return;
  40312. }
  40313. renderPipeline._detachCameras(cameras);
  40314. };
  40315. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40316. var renderPipeline = this._renderPipelines[renderPipelineName];
  40317. if (!renderPipeline) {
  40318. return;
  40319. }
  40320. renderPipeline._enableEffect(renderEffectName, cameras);
  40321. };
  40322. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  40323. var renderPipeline = this._renderPipelines[renderPipelineName];
  40324. if (!renderPipeline) {
  40325. return;
  40326. }
  40327. renderPipeline._disableEffect(renderEffectName, cameras);
  40328. };
  40329. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  40330. var renderPipeline = this._renderPipelines[renderPipelineName];
  40331. if (!renderPipeline) {
  40332. return;
  40333. }
  40334. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  40335. };
  40336. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  40337. var renderPipeline = this._renderPipelines[renderPipelineName];
  40338. if (!renderPipeline) {
  40339. return;
  40340. }
  40341. renderPipeline._disableDisplayOnlyPass(cameras);
  40342. };
  40343. PostProcessRenderPipelineManager.prototype.update = function () {
  40344. for (var renderPipelineName in this._renderPipelines) {
  40345. var pipeline = this._renderPipelines[renderPipelineName];
  40346. if (!pipeline.isSupported) {
  40347. pipeline.dispose();
  40348. delete this._renderPipelines[renderPipelineName];
  40349. }
  40350. else {
  40351. pipeline._update();
  40352. }
  40353. }
  40354. };
  40355. return PostProcessRenderPipelineManager;
  40356. }());
  40357. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  40358. })(BABYLON || (BABYLON = {}));
  40359. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  40360. var BABYLON;
  40361. (function (BABYLON) {
  40362. var PostProcessRenderPass = (function () {
  40363. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  40364. this._enabled = true;
  40365. this._refCount = 0;
  40366. this._name = name;
  40367. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  40368. this.setRenderList(renderList);
  40369. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  40370. this._renderTexture.onAfterRenderObservable.add(afterRender);
  40371. this._scene = scene;
  40372. this._renderList = renderList;
  40373. }
  40374. // private
  40375. PostProcessRenderPass.prototype._incRefCount = function () {
  40376. if (this._refCount === 0) {
  40377. this._scene.customRenderTargets.push(this._renderTexture);
  40378. }
  40379. return ++this._refCount;
  40380. };
  40381. PostProcessRenderPass.prototype._decRefCount = function () {
  40382. this._refCount--;
  40383. if (this._refCount <= 0) {
  40384. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  40385. }
  40386. return this._refCount;
  40387. };
  40388. PostProcessRenderPass.prototype._update = function () {
  40389. this.setRenderList(this._renderList);
  40390. };
  40391. // public
  40392. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  40393. this._renderTexture.renderList = renderList;
  40394. };
  40395. PostProcessRenderPass.prototype.getRenderTexture = function () {
  40396. return this._renderTexture;
  40397. };
  40398. return PostProcessRenderPass;
  40399. }());
  40400. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  40401. })(BABYLON || (BABYLON = {}));
  40402. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  40403. var BABYLON;
  40404. (function (BABYLON) {
  40405. var PostProcessRenderEffect = (function () {
  40406. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  40407. this._engine = engine;
  40408. this._name = name;
  40409. this._singleInstance = singleInstance || true;
  40410. this._getPostProcess = getPostProcess;
  40411. this._cameras = [];
  40412. this._indicesForCamera = [];
  40413. this._postProcesses = {};
  40414. this._renderPasses = {};
  40415. this._renderEffectAsPasses = {};
  40416. }
  40417. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  40418. get: function () {
  40419. for (var index in this._postProcesses) {
  40420. if (!this._postProcesses[index].isSupported) {
  40421. return false;
  40422. }
  40423. }
  40424. return true;
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. PostProcessRenderEffect.prototype._update = function () {
  40430. for (var renderPassName in this._renderPasses) {
  40431. this._renderPasses[renderPassName]._update();
  40432. }
  40433. };
  40434. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  40435. this._renderPasses[renderPass._name] = renderPass;
  40436. this._linkParameters();
  40437. };
  40438. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  40439. delete this._renderPasses[renderPass._name];
  40440. this._linkParameters();
  40441. };
  40442. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  40443. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  40444. this._linkParameters();
  40445. };
  40446. PostProcessRenderEffect.prototype.getPass = function (passName) {
  40447. for (var renderPassName in this._renderPasses) {
  40448. if (renderPassName === passName) {
  40449. return this._renderPasses[passName];
  40450. }
  40451. }
  40452. };
  40453. PostProcessRenderEffect.prototype.emptyPasses = function () {
  40454. this._renderPasses = {};
  40455. this._linkParameters();
  40456. };
  40457. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  40458. var cameraKey;
  40459. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40460. for (var i = 0; i < _cam.length; i++) {
  40461. var camera = _cam[i];
  40462. var cameraName = camera.name;
  40463. if (this._singleInstance) {
  40464. cameraKey = 0;
  40465. }
  40466. else {
  40467. cameraKey = cameraName;
  40468. }
  40469. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  40470. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  40471. if (!this._indicesForCamera[cameraName]) {
  40472. this._indicesForCamera[cameraName] = [];
  40473. }
  40474. this._indicesForCamera[cameraName].push(index);
  40475. if (this._cameras.indexOf(camera) === -1) {
  40476. this._cameras[cameraName] = camera;
  40477. }
  40478. for (var passName in this._renderPasses) {
  40479. this._renderPasses[passName]._incRefCount();
  40480. }
  40481. }
  40482. this._linkParameters();
  40483. };
  40484. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  40485. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40486. for (var i = 0; i < _cam.length; i++) {
  40487. var camera = _cam[i];
  40488. var cameraName = camera.name;
  40489. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40490. var index = this._cameras.indexOf(cameraName);
  40491. this._indicesForCamera.splice(index, 1);
  40492. this._cameras.splice(index, 1);
  40493. for (var passName in this._renderPasses) {
  40494. this._renderPasses[passName]._decRefCount();
  40495. }
  40496. }
  40497. };
  40498. PostProcessRenderEffect.prototype._enable = function (cameras) {
  40499. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40500. for (var i = 0; i < _cam.length; i++) {
  40501. var camera = _cam[i];
  40502. var cameraName = camera.name;
  40503. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  40504. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  40505. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  40506. }
  40507. }
  40508. for (var passName in this._renderPasses) {
  40509. this._renderPasses[passName]._incRefCount();
  40510. }
  40511. }
  40512. };
  40513. PostProcessRenderEffect.prototype._disable = function (cameras) {
  40514. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40515. for (var i = 0; i < _cam.length; i++) {
  40516. var camera = _cam[i];
  40517. var cameraName = camera.Name;
  40518. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  40519. for (var passName in this._renderPasses) {
  40520. this._renderPasses[passName]._decRefCount();
  40521. }
  40522. }
  40523. };
  40524. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  40525. if (this._singleInstance) {
  40526. return this._postProcesses[0];
  40527. }
  40528. else {
  40529. return this._postProcesses[camera.name];
  40530. }
  40531. };
  40532. PostProcessRenderEffect.prototype._linkParameters = function () {
  40533. var _this = this;
  40534. for (var index in this._postProcesses) {
  40535. if (this.applyParameters) {
  40536. this.applyParameters(this._postProcesses[index]);
  40537. }
  40538. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  40539. _this._linkTextures(effect);
  40540. });
  40541. }
  40542. };
  40543. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  40544. for (var renderPassName in this._renderPasses) {
  40545. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  40546. }
  40547. for (var renderEffectName in this._renderEffectAsPasses) {
  40548. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  40549. }
  40550. };
  40551. return PostProcessRenderEffect;
  40552. }());
  40553. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  40554. })(BABYLON || (BABYLON = {}));
  40555. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  40556. var BABYLON;
  40557. (function (BABYLON) {
  40558. var PostProcessRenderPipeline = (function () {
  40559. function PostProcessRenderPipeline(engine, name) {
  40560. this._engine = engine;
  40561. this._name = name;
  40562. this._renderEffects = new Array();
  40563. this._renderEffectsForIsolatedPass = new Array();
  40564. this._cameras = [];
  40565. }
  40566. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  40567. get: function () {
  40568. for (var renderEffectName in this._renderEffects) {
  40569. if (!this._renderEffects[renderEffectName].isSupported) {
  40570. return false;
  40571. }
  40572. }
  40573. return true;
  40574. },
  40575. enumerable: true,
  40576. configurable: true
  40577. });
  40578. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  40579. this._renderEffects[renderEffect._name] = renderEffect;
  40580. };
  40581. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  40582. var renderEffects = this._renderEffects[renderEffectName];
  40583. if (!renderEffects) {
  40584. return;
  40585. }
  40586. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40587. };
  40588. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  40589. var renderEffects = this._renderEffects[renderEffectName];
  40590. if (!renderEffects) {
  40591. return;
  40592. }
  40593. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  40594. };
  40595. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  40596. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40597. var indicesToDelete = [];
  40598. var i;
  40599. for (i = 0; i < _cam.length; i++) {
  40600. var camera = _cam[i];
  40601. var cameraName = camera.name;
  40602. if (this._cameras.indexOf(camera) === -1) {
  40603. this._cameras[cameraName] = camera;
  40604. }
  40605. else if (unique) {
  40606. indicesToDelete.push(i);
  40607. }
  40608. }
  40609. for (i = 0; i < indicesToDelete.length; i++) {
  40610. cameras.splice(indicesToDelete[i], 1);
  40611. }
  40612. for (var renderEffectName in this._renderEffects) {
  40613. this._renderEffects[renderEffectName]._attachCameras(_cam);
  40614. }
  40615. };
  40616. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  40617. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40618. for (var renderEffectName in this._renderEffects) {
  40619. this._renderEffects[renderEffectName]._detachCameras(_cam);
  40620. }
  40621. for (var i = 0; i < _cam.length; i++) {
  40622. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  40623. }
  40624. };
  40625. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  40626. var _this = this;
  40627. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40628. var pass = null;
  40629. var renderEffectName;
  40630. for (renderEffectName in this._renderEffects) {
  40631. pass = this._renderEffects[renderEffectName].getPass(passName);
  40632. if (pass != null) {
  40633. break;
  40634. }
  40635. }
  40636. if (pass === null) {
  40637. return;
  40638. }
  40639. for (renderEffectName in this._renderEffects) {
  40640. this._renderEffects[renderEffectName]._disable(_cam);
  40641. }
  40642. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  40643. for (var i = 0; i < _cam.length; i++) {
  40644. var camera = _cam[i];
  40645. var cameraName = camera.name;
  40646. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  40647. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  40648. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  40649. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  40650. }
  40651. };
  40652. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  40653. var _this = this;
  40654. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  40655. for (var i = 0; i < _cam.length; i++) {
  40656. var camera = _cam[i];
  40657. var cameraName = camera.name;
  40658. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  40659. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  40660. }
  40661. for (var renderEffectName in this._renderEffects) {
  40662. this._renderEffects[renderEffectName]._enable(_cam);
  40663. }
  40664. };
  40665. PostProcessRenderPipeline.prototype._update = function () {
  40666. for (var renderEffectName in this._renderEffects) {
  40667. this._renderEffects[renderEffectName]._update();
  40668. }
  40669. for (var i = 0; i < this._cameras.length; i++) {
  40670. var cameraName = this._cameras[i].name;
  40671. if (this._renderEffectsForIsolatedPass[cameraName]) {
  40672. this._renderEffectsForIsolatedPass[cameraName]._update();
  40673. }
  40674. }
  40675. };
  40676. PostProcessRenderPipeline.prototype._reset = function () {
  40677. this._renderEffects = new Array();
  40678. this._renderEffectsForIsolatedPass = new Array();
  40679. };
  40680. PostProcessRenderPipeline.prototype.dispose = function () {
  40681. // Must be implemented by children
  40682. };
  40683. return PostProcessRenderPipeline;
  40684. }());
  40685. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40686. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40687. __decorate([
  40688. BABYLON.serialize()
  40689. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  40690. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40691. })(BABYLON || (BABYLON = {}));
  40692. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40693. var BABYLON;
  40694. (function (BABYLON) {
  40695. var DefaultRenderingPipeline = (function (_super) {
  40696. __extends(DefaultRenderingPipeline, _super);
  40697. /**
  40698. * @constructor
  40699. * @param {string} name - The rendering pipeline name
  40700. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40701. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  40702. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40703. */
  40704. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  40705. var _this = _super.call(this, scene.getEngine(), name) || this;
  40706. _this.PassPostProcessId = "PassPostProcessEffect";
  40707. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  40708. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  40709. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  40710. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  40711. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  40712. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  40713. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  40714. // IAnimatable
  40715. _this.animations = [];
  40716. // Values
  40717. _this._bloomEnabled = false;
  40718. _this._fxaaEnabled = false;
  40719. _this._imageProcessingEnabled = true;
  40720. _this._bloomScale = 0.6;
  40721. /**
  40722. * Specifies the size of the bloom blur kernel, relative to the final output size
  40723. */
  40724. _this.bloomKernel = 64;
  40725. /**
  40726. * Specifies the weight of the bloom in the final rendering
  40727. */
  40728. _this._bloomWeight = 0.15;
  40729. _this._cameras = cameras || [];
  40730. // Initialize
  40731. _this._scene = scene;
  40732. var caps = _this._scene.getEngine().getCaps();
  40733. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  40734. // Misc
  40735. if (_this._hdr) {
  40736. if (caps.textureHalfFloatRender) {
  40737. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  40738. }
  40739. else if (caps.textureFloatRender) {
  40740. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40741. }
  40742. }
  40743. else {
  40744. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40745. }
  40746. // Attach
  40747. scene.postProcessRenderPipelineManager.addPipeline(_this);
  40748. _this._buildPipeline();
  40749. return _this;
  40750. }
  40751. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  40752. get: function () {
  40753. return this._bloomWeight;
  40754. },
  40755. set: function (value) {
  40756. if (this._bloomWeight === value) {
  40757. return;
  40758. }
  40759. this._bloomWeight = value;
  40760. if (this._hdr && this.copyBack) {
  40761. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  40762. }
  40763. },
  40764. enumerable: true,
  40765. configurable: true
  40766. });
  40767. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  40768. get: function () {
  40769. return this._bloomScale;
  40770. },
  40771. set: function (value) {
  40772. if (this._bloomScale === value) {
  40773. return;
  40774. }
  40775. this._bloomScale = value;
  40776. this._buildPipeline();
  40777. },
  40778. enumerable: true,
  40779. configurable: true
  40780. });
  40781. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  40782. get: function () {
  40783. return this._bloomEnabled;
  40784. },
  40785. set: function (enabled) {
  40786. if (this._bloomEnabled === enabled) {
  40787. return;
  40788. }
  40789. this._bloomEnabled = enabled;
  40790. this._buildPipeline();
  40791. },
  40792. enumerable: true,
  40793. configurable: true
  40794. });
  40795. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  40796. get: function () {
  40797. return this._fxaaEnabled;
  40798. },
  40799. set: function (enabled) {
  40800. if (this._fxaaEnabled === enabled) {
  40801. return;
  40802. }
  40803. this._fxaaEnabled = enabled;
  40804. this._buildPipeline();
  40805. },
  40806. enumerable: true,
  40807. configurable: true
  40808. });
  40809. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  40810. get: function () {
  40811. return this._imageProcessingEnabled;
  40812. },
  40813. set: function (enabled) {
  40814. if (this._imageProcessingEnabled === enabled) {
  40815. return;
  40816. }
  40817. this._imageProcessingEnabled = enabled;
  40818. this._buildPipeline();
  40819. },
  40820. enumerable: true,
  40821. configurable: true
  40822. });
  40823. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  40824. var _this = this;
  40825. var engine = this._scene.getEngine();
  40826. this._disposePostProcesses();
  40827. this._reset();
  40828. if (this.bloomEnabled) {
  40829. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40830. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  40831. if (!this._hdr) {
  40832. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40833. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  40834. this.highlights.autoClear = false;
  40835. this.highlights.alwaysForcePOT = true;
  40836. }
  40837. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40838. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  40839. this.blurX.alwaysForcePOT = true;
  40840. this.blurX.autoClear = false;
  40841. this.blurX.onActivateObservable.add(function () {
  40842. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  40843. _this.blurX.kernel = _this.bloomKernel * dw;
  40844. });
  40845. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40846. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  40847. this.blurY.alwaysForcePOT = true;
  40848. this.blurY.autoClear = false;
  40849. this.blurY.onActivateObservable.add(function () {
  40850. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  40851. _this.blurY.kernel = _this.bloomKernel * dh;
  40852. });
  40853. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40854. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  40855. this.copyBack.alwaysForcePOT = true;
  40856. if (this._hdr) {
  40857. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  40858. var w = this.bloomWeight;
  40859. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  40860. }
  40861. else {
  40862. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  40863. }
  40864. this.copyBack.autoClear = false;
  40865. }
  40866. if (this._imageProcessingEnabled) {
  40867. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40868. if (this._hdr) {
  40869. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  40870. }
  40871. }
  40872. if (this.fxaaEnabled) {
  40873. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40874. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  40875. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40876. }
  40877. else {
  40878. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40879. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  40880. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40881. }
  40882. if (this.bloomEnabled) {
  40883. if (this._hdr) {
  40884. this.copyBack.shareOutputWith(this.blurX);
  40885. if (this.imageProcessing) {
  40886. this.imageProcessing.shareOutputWith(this.pass);
  40887. this.imageProcessing.autoClear = false;
  40888. }
  40889. else if (this.fxaa) {
  40890. this.fxaa.shareOutputWith(this.pass);
  40891. }
  40892. else {
  40893. this.finalMerge.shareOutputWith(this.pass);
  40894. }
  40895. }
  40896. else {
  40897. if (this.fxaa) {
  40898. this.fxaa.shareOutputWith(this.pass);
  40899. }
  40900. else {
  40901. this.finalMerge.shareOutputWith(this.pass);
  40902. }
  40903. }
  40904. }
  40905. if (this._cameras !== null) {
  40906. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  40907. }
  40908. };
  40909. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  40910. for (var i = 0; i < this._cameras.length; i++) {
  40911. var camera = this._cameras[i];
  40912. if (this.pass) {
  40913. this.pass.dispose(camera);
  40914. }
  40915. if (this.highlights) {
  40916. this.highlights.dispose(camera);
  40917. }
  40918. if (this.blurX) {
  40919. this.blurX.dispose(camera);
  40920. }
  40921. if (this.blurY) {
  40922. this.blurY.dispose(camera);
  40923. }
  40924. if (this.copyBack) {
  40925. this.copyBack.dispose(camera);
  40926. }
  40927. if (this.imageProcessing) {
  40928. this.imageProcessing.dispose(camera);
  40929. }
  40930. if (this.fxaa) {
  40931. this.fxaa.dispose(camera);
  40932. }
  40933. if (this.finalMerge) {
  40934. this.finalMerge.dispose(camera);
  40935. }
  40936. }
  40937. this.pass = null;
  40938. this.highlights = null;
  40939. this.blurX = null;
  40940. this.blurY = null;
  40941. this.copyBack = null;
  40942. this.imageProcessing = null;
  40943. this.fxaa = null;
  40944. this.finalMerge = null;
  40945. };
  40946. // Dispose
  40947. DefaultRenderingPipeline.prototype.dispose = function () {
  40948. this._disposePostProcesses();
  40949. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  40950. _super.prototype.dispose.call(this);
  40951. };
  40952. // Serialize rendering pipeline
  40953. DefaultRenderingPipeline.prototype.serialize = function () {
  40954. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40955. serializationObject.customType = "DefaultRenderingPipeline";
  40956. return serializationObject;
  40957. };
  40958. // Parse serialized pipeline
  40959. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  40960. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  40961. };
  40962. return DefaultRenderingPipeline;
  40963. }(BABYLON.PostProcessRenderPipeline));
  40964. __decorate([
  40965. BABYLON.serialize()
  40966. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  40967. __decorate([
  40968. BABYLON.serialize()
  40969. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  40970. __decorate([
  40971. BABYLON.serialize()
  40972. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  40973. __decorate([
  40974. BABYLON.serialize()
  40975. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  40976. __decorate([
  40977. BABYLON.serialize()
  40978. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  40979. __decorate([
  40980. BABYLON.serialize()
  40981. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  40982. __decorate([
  40983. BABYLON.serialize()
  40984. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  40985. __decorate([
  40986. BABYLON.serialize()
  40987. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  40988. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  40989. })(BABYLON || (BABYLON = {}));
  40990. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  40991. var BABYLON;
  40992. (function (BABYLON) {
  40993. /**
  40994. * This groups together the common properties used for image processing either in direct forward pass
  40995. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40996. * or not.
  40997. */
  40998. var ImageProcessingConfiguration = (function () {
  40999. function ImageProcessingConfiguration() {
  41000. /**
  41001. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  41002. */
  41003. this.colorCurves = new BABYLON.ColorCurves();
  41004. this._colorCurvesEnabled = false;
  41005. this._colorGradingEnabled = false;
  41006. this._colorGradingWithGreenDepth = false;
  41007. this._colorGradingBGR = false;
  41008. this._exposure = 1.0;
  41009. this._toneMappingEnabled = false;
  41010. this._contrast = 1.0;
  41011. /**
  41012. * Vignette stretch size.
  41013. */
  41014. this.vignetteStretch = 0;
  41015. /**
  41016. * Vignette centre X Offset.
  41017. */
  41018. this.vignetteCentreX = 0;
  41019. /**
  41020. * Vignette centre Y Offset.
  41021. */
  41022. this.vignetteCentreY = 0;
  41023. /**
  41024. * Vignette weight or intensity of the vignette effect.
  41025. */
  41026. this.vignetteWeight = 1.5;
  41027. /**
  41028. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  41029. * if vignetteEnabled is set to true.
  41030. */
  41031. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41032. /**
  41033. * Camera field of view used by the Vignette effect.
  41034. */
  41035. this.vignetteCameraFov = 0.5;
  41036. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  41037. this._vignetteEnabled = false;
  41038. this._applyByPostProcess = false;
  41039. /**
  41040. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41041. * @type {BABYLON.Observable}
  41042. */
  41043. this.onUpdateParameters = new BABYLON.Observable();
  41044. }
  41045. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41046. /**
  41047. * Gets wether the color curves effect is enabled.
  41048. */
  41049. get: function () {
  41050. return this._colorCurvesEnabled;
  41051. },
  41052. /**
  41053. * Sets wether the color curves effect is enabled.
  41054. */
  41055. set: function (value) {
  41056. if (this._colorCurvesEnabled === value) {
  41057. return;
  41058. }
  41059. this._colorCurvesEnabled = value;
  41060. this._updateParameters();
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41066. /**
  41067. * Gets wether the color grading effect is enabled.
  41068. */
  41069. get: function () {
  41070. return this._colorGradingEnabled;
  41071. },
  41072. /**
  41073. * Sets wether the color grading effect is enabled.
  41074. */
  41075. set: function (value) {
  41076. if (this._colorGradingEnabled === value) {
  41077. return;
  41078. }
  41079. this._colorGradingEnabled = value;
  41080. this._updateParameters();
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41086. /**
  41087. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41088. */
  41089. get: function () {
  41090. return this._colorGradingWithGreenDepth;
  41091. },
  41092. /**
  41093. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41094. */
  41095. set: function (value) {
  41096. if (this._colorGradingWithGreenDepth === value) {
  41097. return;
  41098. }
  41099. this._colorGradingWithGreenDepth = value;
  41100. this._updateParameters();
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41106. /**
  41107. * Gets wether the color grading texture contains BGR values.
  41108. */
  41109. get: function () {
  41110. return this._colorGradingBGR;
  41111. },
  41112. /**
  41113. * Sets wether the color grading texture contains BGR values.
  41114. */
  41115. set: function (value) {
  41116. if (this._colorGradingBGR === value) {
  41117. return;
  41118. }
  41119. this._colorGradingBGR = value;
  41120. this._updateParameters();
  41121. },
  41122. enumerable: true,
  41123. configurable: true
  41124. });
  41125. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41126. /**
  41127. * Gets the Exposure used in the effect.
  41128. */
  41129. get: function () {
  41130. return this._exposure;
  41131. },
  41132. /**
  41133. * Sets the Exposure used in the effect.
  41134. */
  41135. set: function (value) {
  41136. if (this._exposure === value) {
  41137. return;
  41138. }
  41139. this._exposure = value;
  41140. this._updateParameters();
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41146. /**
  41147. * Gets wether the tone mapping effect is enabled.
  41148. */
  41149. get: function () {
  41150. return this._toneMappingEnabled;
  41151. },
  41152. /**
  41153. * Sets wether the tone mapping effect is enabled.
  41154. */
  41155. set: function (value) {
  41156. if (this._toneMappingEnabled === value) {
  41157. return;
  41158. }
  41159. this._toneMappingEnabled = value;
  41160. this._updateParameters();
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41166. /**
  41167. * Gets the contrast used in the effect.
  41168. */
  41169. get: function () {
  41170. return this._contrast;
  41171. },
  41172. /**
  41173. * Sets the contrast used in the effect.
  41174. */
  41175. set: function (value) {
  41176. if (this._contrast === value) {
  41177. return;
  41178. }
  41179. this._contrast = value;
  41180. this._updateParameters();
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41186. /**
  41187. * Gets the vignette blend mode allowing different kind of effect.
  41188. */
  41189. get: function () {
  41190. return this._vignetteBlendMode;
  41191. },
  41192. /**
  41193. * Sets the vignette blend mode allowing different kind of effect.
  41194. */
  41195. set: function (value) {
  41196. if (this._vignetteBlendMode === value) {
  41197. return;
  41198. }
  41199. this._vignetteBlendMode = value;
  41200. this._updateParameters();
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41206. /**
  41207. * Gets wether the vignette effect is enabled.
  41208. */
  41209. get: function () {
  41210. return this._vignetteEnabled;
  41211. },
  41212. /**
  41213. * Sets wether the vignette effect is enabled.
  41214. */
  41215. set: function (value) {
  41216. if (this._vignetteEnabled === value) {
  41217. return;
  41218. }
  41219. this._vignetteEnabled = value;
  41220. this._updateParameters();
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41226. /**
  41227. * Gets wether the image processing is applied through a post process or not.
  41228. */
  41229. get: function () {
  41230. return this._applyByPostProcess;
  41231. },
  41232. /**
  41233. * Sets wether the image processing is applied through a post process or not.
  41234. */
  41235. set: function (value) {
  41236. if (this._applyByPostProcess === value) {
  41237. return;
  41238. }
  41239. this._applyByPostProcess = value;
  41240. this._updateParameters();
  41241. },
  41242. enumerable: true,
  41243. configurable: true
  41244. });
  41245. /**
  41246. * Method called each time the image processing information changes requires to recompile the effect.
  41247. */
  41248. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41249. this.onUpdateParameters.notifyObservers(this);
  41250. };
  41251. /**
  41252. * Prepare the list of uniforms associated with the Image Processing effects.
  41253. * @param uniformsList The list of uniforms used in the effect
  41254. * @param defines the list of defines currently in use
  41255. */
  41256. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41257. if (defines.EXPOSURE) {
  41258. uniforms.push("exposureLinear");
  41259. }
  41260. if (defines.CONTRAST) {
  41261. uniforms.push("contrast");
  41262. }
  41263. if (defines.COLORGRADING) {
  41264. uniforms.push("colorTransformSettings");
  41265. }
  41266. if (defines.VIGNETTE) {
  41267. uniforms.push("vInverseScreenSize");
  41268. uniforms.push("vignetteSettings1");
  41269. uniforms.push("vignetteSettings2");
  41270. }
  41271. if (defines.COLORCURVES) {
  41272. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41273. }
  41274. };
  41275. /**
  41276. * Prepare the list of samplers associated with the Image Processing effects.
  41277. * @param uniformsList The list of uniforms used in the effect
  41278. * @param defines the list of defines currently in use
  41279. */
  41280. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41281. if (defines.COLORGRADING) {
  41282. samplersList.push("txColorTransform");
  41283. }
  41284. };
  41285. /**
  41286. * Prepare the list of defines associated to the shader.
  41287. * @param defines the list of defines to complete
  41288. */
  41289. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  41290. defines.VIGNETTE = this.vignetteEnabled;
  41291. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41292. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41293. defines.TONEMAPPING = this.toneMappingEnabled;
  41294. defines.CONTRAST = (this.contrast !== 1.0);
  41295. defines.EXPOSURE = (this.exposure !== 1.0);
  41296. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41297. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41298. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41299. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41300. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41301. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41302. };
  41303. /**
  41304. * Returns true if all the image processing information are ready.
  41305. */
  41306. ImageProcessingConfiguration.prototype.isReady = function () {
  41307. // Color Grading texure can not be none blocking.
  41308. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41309. };
  41310. /**
  41311. * Binds the image processing to the shader.
  41312. * @param effect The effect to bind to
  41313. */
  41314. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41315. if (aspectRatio === void 0) { aspectRatio = 1; }
  41316. // Color Curves
  41317. if (this._colorCurvesEnabled) {
  41318. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41319. }
  41320. // Vignette
  41321. if (this._vignetteEnabled) {
  41322. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41323. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41324. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41325. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41326. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41327. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41328. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41329. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41330. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41331. var vignettePower = -2.0 * this.vignetteWeight;
  41332. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41333. }
  41334. // Exposure
  41335. effect.setFloat("exposureLinear", this.exposure);
  41336. // Contrast
  41337. effect.setFloat("contrast", this.contrast);
  41338. // Color transform settings
  41339. if (this.colorGradingTexture) {
  41340. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41341. var textureSize = this.colorGradingTexture.getSize().height;
  41342. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41343. 0.5 / textureSize, // textureOffset
  41344. textureSize, // textureSize
  41345. this.colorGradingTexture.level // weight
  41346. );
  41347. }
  41348. };
  41349. /**
  41350. * Clones the current image processing instance.
  41351. * @return The cloned image processing
  41352. */
  41353. ImageProcessingConfiguration.prototype.clone = function () {
  41354. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41355. };
  41356. /**
  41357. * Serializes the current image processing instance to a json representation.
  41358. * @return a JSON representation
  41359. */
  41360. ImageProcessingConfiguration.prototype.serialize = function () {
  41361. return BABYLON.SerializationHelper.Serialize(this);
  41362. };
  41363. /**
  41364. * Parses the image processing from a json representation.
  41365. * @param source the JSON source to parse
  41366. * @return The parsed image processing
  41367. */
  41368. ImageProcessingConfiguration.Parse = function (source) {
  41369. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41370. };
  41371. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41372. /**
  41373. * Used to apply the vignette as a mix with the pixel color.
  41374. */
  41375. get: function () {
  41376. return this._VIGNETTEMODE_MULTIPLY;
  41377. },
  41378. enumerable: true,
  41379. configurable: true
  41380. });
  41381. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41382. /**
  41383. * Used to apply the vignette as a replacement of the pixel color.
  41384. */
  41385. get: function () {
  41386. return this._VIGNETTEMODE_OPAQUE;
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. return ImageProcessingConfiguration;
  41392. }());
  41393. // Static constants associated to the image processing.
  41394. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41395. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41396. __decorate([
  41397. BABYLON.serializeAsColorCurves()
  41398. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41399. __decorate([
  41400. BABYLON.serialize()
  41401. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41402. __decorate([
  41403. BABYLON.serializeAsTexture()
  41404. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41405. __decorate([
  41406. BABYLON.serialize()
  41407. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41408. __decorate([
  41409. BABYLON.serialize()
  41410. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41411. __decorate([
  41412. BABYLON.serialize()
  41413. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41414. __decorate([
  41415. BABYLON.serialize()
  41416. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41417. __decorate([
  41418. BABYLON.serialize()
  41419. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41420. __decorate([
  41421. BABYLON.serialize()
  41422. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41423. __decorate([
  41424. BABYLON.serialize()
  41425. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41426. __decorate([
  41427. BABYLON.serialize()
  41428. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41429. __decorate([
  41430. BABYLON.serialize()
  41431. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41432. __decorate([
  41433. BABYLON.serialize()
  41434. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41435. __decorate([
  41436. BABYLON.serializeAsColor4()
  41437. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41438. __decorate([
  41439. BABYLON.serialize()
  41440. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41441. __decorate([
  41442. BABYLON.serialize()
  41443. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41444. __decorate([
  41445. BABYLON.serialize()
  41446. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41447. __decorate([
  41448. BABYLON.serialize()
  41449. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41450. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41451. })(BABYLON || (BABYLON = {}));
  41452. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41453. /// <reference path="babylon.mesh.ts" />
  41454. var BABYLON;
  41455. (function (BABYLON) {
  41456. var GroundMesh = (function (_super) {
  41457. __extends(GroundMesh, _super);
  41458. function GroundMesh(name, scene) {
  41459. var _this = _super.call(this, name, scene) || this;
  41460. _this.generateOctree = false;
  41461. _this._worldInverse = new BABYLON.Matrix();
  41462. return _this;
  41463. }
  41464. GroundMesh.prototype.getClassName = function () {
  41465. return "GroundMesh";
  41466. };
  41467. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41468. get: function () {
  41469. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41470. },
  41471. enumerable: true,
  41472. configurable: true
  41473. });
  41474. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41475. get: function () {
  41476. return this._subdivisionsX;
  41477. },
  41478. enumerable: true,
  41479. configurable: true
  41480. });
  41481. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41482. get: function () {
  41483. return this._subdivisionsY;
  41484. },
  41485. enumerable: true,
  41486. configurable: true
  41487. });
  41488. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41489. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41490. this._subdivisionsX = chunksCount;
  41491. this._subdivisionsY = chunksCount;
  41492. this.subdivide(chunksCount);
  41493. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41494. };
  41495. /**
  41496. * Returns a height (y) value in the Worl system :
  41497. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41498. * Returns the ground y position if (x, z) are outside the ground surface.
  41499. */
  41500. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41501. var world = this.getWorldMatrix();
  41502. var invMat = BABYLON.Tmp.Matrix[5];
  41503. world.invertToRef(invMat);
  41504. var tmpVect = BABYLON.Tmp.Vector3[8];
  41505. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41506. x = tmpVect.x;
  41507. z = tmpVect.z;
  41508. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41509. return this.position.y;
  41510. }
  41511. if (!this._heightQuads || this._heightQuads.length == 0) {
  41512. this._initHeightQuads();
  41513. this._computeHeightQuads();
  41514. }
  41515. var facet = this._getFacetAt(x, z);
  41516. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41517. // return y in the World system
  41518. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41519. return tmpVect.y;
  41520. };
  41521. /**
  41522. * Returns a normalized vector (Vector3) orthogonal to the ground
  41523. * at the ground coordinates (x, z) expressed in the World system.
  41524. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41525. */
  41526. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41527. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41528. this.getNormalAtCoordinatesToRef(x, z, normal);
  41529. return normal;
  41530. };
  41531. /**
  41532. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41533. * at the ground coordinates (x, z) expressed in the World system.
  41534. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41535. * Returns the GroundMesh.
  41536. */
  41537. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41538. var world = this.getWorldMatrix();
  41539. var tmpMat = BABYLON.Tmp.Matrix[5];
  41540. world.invertToRef(tmpMat);
  41541. var tmpVect = BABYLON.Tmp.Vector3[8];
  41542. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41543. x = tmpVect.x;
  41544. z = tmpVect.z;
  41545. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41546. return this;
  41547. }
  41548. if (!this._heightQuads || this._heightQuads.length == 0) {
  41549. this._initHeightQuads();
  41550. this._computeHeightQuads();
  41551. }
  41552. var facet = this._getFacetAt(x, z);
  41553. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41554. return this;
  41555. };
  41556. /**
  41557. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41558. * if the ground has been updated.
  41559. * This can be used in the render loop.
  41560. * Returns the GroundMesh.
  41561. */
  41562. GroundMesh.prototype.updateCoordinateHeights = function () {
  41563. if (!this._heightQuads || this._heightQuads.length == 0) {
  41564. this._initHeightQuads();
  41565. }
  41566. this._computeHeightQuads();
  41567. return this;
  41568. };
  41569. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41570. GroundMesh.prototype._getFacetAt = function (x, z) {
  41571. // retrieve col and row from x, z coordinates in the ground local system
  41572. var subdivisionsX = this._subdivisionsX;
  41573. var subdivisionsY = this._subdivisionsY;
  41574. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41575. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41576. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41577. var facet;
  41578. if (z < quad.slope.x * x + quad.slope.y) {
  41579. facet = quad.facet1;
  41580. }
  41581. else {
  41582. facet = quad.facet2;
  41583. }
  41584. return facet;
  41585. };
  41586. // Creates and populates the heightMap array with "facet" elements :
  41587. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41588. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41589. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41590. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41591. // Returns the GroundMesh.
  41592. GroundMesh.prototype._initHeightQuads = function () {
  41593. var subdivisionsX = this._subdivisionsX;
  41594. var subdivisionsY = this._subdivisionsY;
  41595. this._heightQuads = new Array();
  41596. for (var row = 0; row < subdivisionsY; row++) {
  41597. for (var col = 0; col < subdivisionsX; col++) {
  41598. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  41599. this._heightQuads[row * subdivisionsX + col] = quad;
  41600. }
  41601. }
  41602. return this;
  41603. };
  41604. // Compute each quad element values and update the the heightMap array :
  41605. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41606. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41607. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41608. // Returns the GroundMesh.
  41609. GroundMesh.prototype._computeHeightQuads = function () {
  41610. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41611. var v1 = BABYLON.Tmp.Vector3[3];
  41612. var v2 = BABYLON.Tmp.Vector3[2];
  41613. var v3 = BABYLON.Tmp.Vector3[1];
  41614. var v4 = BABYLON.Tmp.Vector3[0];
  41615. var v1v2 = BABYLON.Tmp.Vector3[4];
  41616. var v1v3 = BABYLON.Tmp.Vector3[5];
  41617. var v1v4 = BABYLON.Tmp.Vector3[6];
  41618. var norm1 = BABYLON.Tmp.Vector3[7];
  41619. var norm2 = BABYLON.Tmp.Vector3[8];
  41620. var i = 0;
  41621. var j = 0;
  41622. var k = 0;
  41623. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41624. var h = 0;
  41625. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41626. var d2 = 0;
  41627. var subdivisionsX = this._subdivisionsX;
  41628. var subdivisionsY = this._subdivisionsY;
  41629. for (var row = 0; row < subdivisionsY; row++) {
  41630. for (var col = 0; col < subdivisionsX; col++) {
  41631. i = col * 3;
  41632. j = row * (subdivisionsX + 1) * 3;
  41633. k = (row + 1) * (subdivisionsX + 1) * 3;
  41634. v1.x = positions[j + i];
  41635. v1.y = positions[j + i + 1];
  41636. v1.z = positions[j + i + 2];
  41637. v2.x = positions[j + i + 3];
  41638. v2.y = positions[j + i + 4];
  41639. v2.z = positions[j + i + 5];
  41640. v3.x = positions[k + i];
  41641. v3.y = positions[k + i + 1];
  41642. v3.z = positions[k + i + 2];
  41643. v4.x = positions[k + i + 3];
  41644. v4.y = positions[k + i + 4];
  41645. v4.z = positions[k + i + 5];
  41646. // 2D slope V1V4
  41647. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41648. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41649. // facet equations :
  41650. // we compute each facet normal vector
  41651. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41652. // we compute the value d by applying the equation to v1 which belongs to the plane
  41653. // then we store the facet equation in a Vector4
  41654. v2.subtractToRef(v1, v1v2);
  41655. v3.subtractToRef(v1, v1v3);
  41656. v4.subtractToRef(v1, v1v4);
  41657. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41658. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41659. norm1.normalize();
  41660. norm2.normalize();
  41661. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41662. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41663. var quad = this._heightQuads[row * subdivisionsX + col];
  41664. quad.slope.copyFromFloats(cd, h);
  41665. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41666. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41667. }
  41668. }
  41669. return this;
  41670. };
  41671. GroundMesh.prototype.serialize = function (serializationObject) {
  41672. _super.prototype.serialize.call(this, serializationObject);
  41673. serializationObject.subdivisionsX = this._subdivisionsX;
  41674. serializationObject.subdivisionsY = this._subdivisionsY;
  41675. serializationObject.minX = this._minX;
  41676. serializationObject.maxX = this._maxX;
  41677. serializationObject.minZ = this._minZ;
  41678. serializationObject.maxZ = this._maxZ;
  41679. serializationObject.width = this._width;
  41680. serializationObject.height = this._height;
  41681. };
  41682. GroundMesh.Parse = function (parsedMesh, scene) {
  41683. var result = new GroundMesh(parsedMesh.name, scene);
  41684. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41685. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41686. result._minX = parsedMesh.minX;
  41687. result._maxX = parsedMesh.maxX;
  41688. result._minZ = parsedMesh.minZ;
  41689. result._maxZ = parsedMesh.maxZ;
  41690. result._width = parsedMesh.width;
  41691. result._height = parsedMesh.height;
  41692. return result;
  41693. };
  41694. return GroundMesh;
  41695. }(BABYLON.Mesh));
  41696. BABYLON.GroundMesh = GroundMesh;
  41697. })(BABYLON || (BABYLON = {}));
  41698. //# sourceMappingURL=babylon.groundMesh.js.map
  41699. var BABYLON;
  41700. (function (BABYLON) {
  41701. /**
  41702. * Creates an instance based on a source mesh.
  41703. */
  41704. var InstancedMesh = (function (_super) {
  41705. __extends(InstancedMesh, _super);
  41706. function InstancedMesh(name, source) {
  41707. var _this = _super.call(this, name, source.getScene()) || this;
  41708. source.instances.push(_this);
  41709. _this._sourceMesh = source;
  41710. _this.position.copyFrom(source.position);
  41711. _this.rotation.copyFrom(source.rotation);
  41712. _this.scaling.copyFrom(source.scaling);
  41713. if (source.rotationQuaternion) {
  41714. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41715. }
  41716. _this.infiniteDistance = source.infiniteDistance;
  41717. _this.setPivotMatrix(source.getPivotMatrix());
  41718. _this.refreshBoundingInfo();
  41719. _this._syncSubMeshes();
  41720. return _this;
  41721. }
  41722. /**
  41723. * Returns the string "InstancedMesh".
  41724. */
  41725. InstancedMesh.prototype.getClassName = function () {
  41726. return "InstancedMesh";
  41727. };
  41728. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41729. // Methods
  41730. get: function () {
  41731. return this._sourceMesh.receiveShadows;
  41732. },
  41733. enumerable: true,
  41734. configurable: true
  41735. });
  41736. Object.defineProperty(InstancedMesh.prototype, "material", {
  41737. get: function () {
  41738. return this._sourceMesh.material;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41744. get: function () {
  41745. return this._sourceMesh.visibility;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41751. get: function () {
  41752. return this._sourceMesh.skeleton;
  41753. },
  41754. enumerable: true,
  41755. configurable: true
  41756. });
  41757. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41758. get: function () {
  41759. return this._sourceMesh.renderingGroupId;
  41760. },
  41761. enumerable: true,
  41762. configurable: true
  41763. });
  41764. /**
  41765. * Returns the total number of vertices (integer).
  41766. */
  41767. InstancedMesh.prototype.getTotalVertices = function () {
  41768. return this._sourceMesh.getTotalVertices();
  41769. };
  41770. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41771. get: function () {
  41772. return this._sourceMesh;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. /**
  41778. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41779. */
  41780. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41781. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41782. };
  41783. /**
  41784. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41785. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41786. * The `data` are either a numeric array either a Float32Array.
  41787. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41788. * 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).
  41789. * Note that a new underlying VertexBuffer object is created each call.
  41790. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41791. *
  41792. * Possible `kind` values :
  41793. * - BABYLON.VertexBuffer.PositionKind
  41794. * - BABYLON.VertexBuffer.UVKind
  41795. * - BABYLON.VertexBuffer.UV2Kind
  41796. * - BABYLON.VertexBuffer.UV3Kind
  41797. * - BABYLON.VertexBuffer.UV4Kind
  41798. * - BABYLON.VertexBuffer.UV5Kind
  41799. * - BABYLON.VertexBuffer.UV6Kind
  41800. * - BABYLON.VertexBuffer.ColorKind
  41801. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41802. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41803. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41804. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41805. *
  41806. * Returns the Mesh.
  41807. */
  41808. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41809. if (this.sourceMesh) {
  41810. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41811. }
  41812. return this.sourceMesh;
  41813. };
  41814. /**
  41815. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41816. * If the mesh has no geometry, it is simply returned as it is.
  41817. * The `data` are either a numeric array either a Float32Array.
  41818. * No new underlying VertexBuffer object is created.
  41819. * 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.
  41820. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41821. *
  41822. * Possible `kind` values :
  41823. * - BABYLON.VertexBuffer.PositionKind
  41824. * - BABYLON.VertexBuffer.UVKind
  41825. * - BABYLON.VertexBuffer.UV2Kind
  41826. * - BABYLON.VertexBuffer.UV3Kind
  41827. * - BABYLON.VertexBuffer.UV4Kind
  41828. * - BABYLON.VertexBuffer.UV5Kind
  41829. * - BABYLON.VertexBuffer.UV6Kind
  41830. * - BABYLON.VertexBuffer.ColorKind
  41831. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41832. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41833. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41834. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41835. *
  41836. * Returns the Mesh.
  41837. */
  41838. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41839. if (this.sourceMesh) {
  41840. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41841. }
  41842. return this.sourceMesh;
  41843. };
  41844. /**
  41845. * Sets the mesh indices.
  41846. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41847. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41848. * This method creates a new index buffer each call.
  41849. * Returns the Mesh.
  41850. */
  41851. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41852. if (this.sourceMesh) {
  41853. this.sourceMesh.setIndices(indices, totalVertices);
  41854. }
  41855. return this.sourceMesh;
  41856. };
  41857. /**
  41858. * Boolean : True if the mesh owns the requested kind of data.
  41859. */
  41860. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41861. return this._sourceMesh.isVerticesDataPresent(kind);
  41862. };
  41863. /**
  41864. * Returns an array of indices (IndicesArray).
  41865. */
  41866. InstancedMesh.prototype.getIndices = function () {
  41867. return this._sourceMesh.getIndices();
  41868. };
  41869. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41870. get: function () {
  41871. return this._sourceMesh._positions;
  41872. },
  41873. enumerable: true,
  41874. configurable: true
  41875. });
  41876. /**
  41877. * Sets a new updated BoundingInfo to the mesh.
  41878. * Returns the mesh.
  41879. */
  41880. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41881. var meshBB = this._sourceMesh.getBoundingInfo();
  41882. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41883. this._updateBoundingInfo();
  41884. return this;
  41885. };
  41886. InstancedMesh.prototype._preActivate = function () {
  41887. if (this._currentLOD) {
  41888. this._currentLOD._preActivate();
  41889. }
  41890. return this;
  41891. };
  41892. InstancedMesh.prototype._activate = function (renderId) {
  41893. if (this._currentLOD) {
  41894. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41895. }
  41896. return this;
  41897. };
  41898. /**
  41899. * Returns the current associated LOD AbstractMesh.
  41900. */
  41901. InstancedMesh.prototype.getLOD = function (camera) {
  41902. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41903. if (this._currentLOD === this.sourceMesh) {
  41904. return this;
  41905. }
  41906. return this._currentLOD;
  41907. };
  41908. InstancedMesh.prototype._syncSubMeshes = function () {
  41909. this.releaseSubMeshes();
  41910. if (this._sourceMesh.subMeshes) {
  41911. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41912. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41913. }
  41914. }
  41915. return this;
  41916. };
  41917. InstancedMesh.prototype._generatePointsArray = function () {
  41918. return this._sourceMesh._generatePointsArray();
  41919. };
  41920. /**
  41921. * Creates a new InstancedMesh from the current mesh.
  41922. * - name (string) : the cloned mesh name
  41923. * - newParent (optional Node) : the optional Node to parent the clone to.
  41924. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41925. *
  41926. * Returns the clone.
  41927. */
  41928. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41929. var result = this._sourceMesh.createInstance(name);
  41930. // Deep copy
  41931. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41932. // Bounding info
  41933. this.refreshBoundingInfo();
  41934. // Parent
  41935. if (newParent) {
  41936. result.parent = newParent;
  41937. }
  41938. if (!doNotCloneChildren) {
  41939. // Children
  41940. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41941. var mesh = this.getScene().meshes[index];
  41942. if (mesh.parent === this) {
  41943. mesh.clone(mesh.name, result);
  41944. }
  41945. }
  41946. }
  41947. result.computeWorldMatrix(true);
  41948. return result;
  41949. };
  41950. /**
  41951. * Disposes the InstancedMesh.
  41952. * Returns nothing.
  41953. */
  41954. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41955. // Remove from mesh
  41956. var index = this._sourceMesh.instances.indexOf(this);
  41957. this._sourceMesh.instances.splice(index, 1);
  41958. _super.prototype.dispose.call(this, doNotRecurse);
  41959. };
  41960. return InstancedMesh;
  41961. }(BABYLON.AbstractMesh));
  41962. BABYLON.InstancedMesh = InstancedMesh;
  41963. })(BABYLON || (BABYLON = {}));
  41964. //# sourceMappingURL=babylon.instancedMesh.js.map
  41965. /// <reference path="babylon.mesh.ts" />
  41966. var BABYLON;
  41967. (function (BABYLON) {
  41968. var LinesMesh = (function (_super) {
  41969. __extends(LinesMesh, _super);
  41970. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41971. if (parent === void 0) { parent = null; }
  41972. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41973. _this.useVertexColor = useVertexColor;
  41974. _this.color = new BABYLON.Color3(1, 1, 1);
  41975. _this.alpha = 1;
  41976. if (source) {
  41977. _this.color = source.color.clone();
  41978. _this.alpha = source.alpha;
  41979. _this.useVertexColor = source.useVertexColor;
  41980. }
  41981. _this._intersectionThreshold = 0.1;
  41982. var options = {
  41983. attributes: [BABYLON.VertexBuffer.PositionKind],
  41984. uniforms: ["world", "viewProjection"],
  41985. needAlphaBlending: false,
  41986. };
  41987. if (!useVertexColor) {
  41988. options.uniforms.push("color");
  41989. options.needAlphaBlending = true;
  41990. }
  41991. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41992. return _this;
  41993. }
  41994. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41995. /**
  41996. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41997. * This margin is expressed in world space coordinates, so its value may vary.
  41998. * Default value is 0.1
  41999. * @returns the intersection Threshold value.
  42000. */
  42001. get: function () {
  42002. return this._intersectionThreshold;
  42003. },
  42004. /**
  42005. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42006. * This margin is expressed in world space coordinates, so its value may vary.
  42007. * @param value the new threshold to apply
  42008. */
  42009. set: function (value) {
  42010. if (this._intersectionThreshold === value) {
  42011. return;
  42012. }
  42013. this._intersectionThreshold = value;
  42014. if (this.geometry) {
  42015. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42016. }
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. /**
  42022. * Returns the string "LineMesh"
  42023. */
  42024. LinesMesh.prototype.getClassName = function () {
  42025. return "LinesMesh";
  42026. };
  42027. Object.defineProperty(LinesMesh.prototype, "material", {
  42028. get: function () {
  42029. return this._colorShader;
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42035. get: function () {
  42036. return false;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. LinesMesh.prototype.createInstance = function (name) {
  42042. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42043. return null;
  42044. };
  42045. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42046. // VBOs
  42047. this._geometry._bind(this._colorShader.getEffect());
  42048. // Color
  42049. if (!this.useVertexColor) {
  42050. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42051. }
  42052. return this;
  42053. };
  42054. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42055. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42056. return this;
  42057. }
  42058. var engine = this.getScene().getEngine();
  42059. // Draw order
  42060. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42061. return this;
  42062. };
  42063. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42064. this._colorShader.dispose();
  42065. _super.prototype.dispose.call(this, doNotRecurse);
  42066. };
  42067. /**
  42068. * Returns a new LineMesh object cloned from the current one.
  42069. */
  42070. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42071. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42072. };
  42073. return LinesMesh;
  42074. }(BABYLON.Mesh));
  42075. BABYLON.LinesMesh = LinesMesh;
  42076. })(BABYLON || (BABYLON = {}));
  42077. //# sourceMappingURL=babylon.linesMesh.js.map
  42078. var BABYLON;
  42079. (function (BABYLON) {
  42080. var StandardMaterialDefines = (function (_super) {
  42081. __extends(StandardMaterialDefines, _super);
  42082. function StandardMaterialDefines() {
  42083. var _this = _super.call(this) || this;
  42084. _this.MAINUV1 = false;
  42085. _this.MAINUV2 = false;
  42086. _this.DIFFUSE = false;
  42087. _this.DIFFUSEDIRECTUV = 0;
  42088. _this.AMBIENT = false;
  42089. _this.AMBIENTDIRECTUV = 0;
  42090. _this.OPACITY = false;
  42091. _this.OPACITYDIRECTUV = 0;
  42092. _this.OPACITYRGB = false;
  42093. _this.REFLECTION = false;
  42094. _this.EMISSIVE = false;
  42095. _this.EMISSIVEDIRECTUV = 0;
  42096. _this.SPECULAR = false;
  42097. _this.SPECULARDIRECTUV = 0;
  42098. _this.BUMP = false;
  42099. _this.BUMPDIRECTUV = 0;
  42100. _this.PARALLAX = false;
  42101. _this.PARALLAXOCCLUSION = false;
  42102. _this.SPECULAROVERALPHA = false;
  42103. _this.CLIPPLANE = false;
  42104. _this.ALPHATEST = false;
  42105. _this.ALPHAFROMDIFFUSE = false;
  42106. _this.POINTSIZE = false;
  42107. _this.FOG = false;
  42108. _this.SPECULARTERM = false;
  42109. _this.DIFFUSEFRESNEL = false;
  42110. _this.OPACITYFRESNEL = false;
  42111. _this.REFLECTIONFRESNEL = false;
  42112. _this.REFRACTIONFRESNEL = false;
  42113. _this.EMISSIVEFRESNEL = false;
  42114. _this.FRESNEL = false;
  42115. _this.NORMAL = false;
  42116. _this.UV1 = false;
  42117. _this.UV2 = false;
  42118. _this.VERTEXCOLOR = false;
  42119. _this.VERTEXALPHA = false;
  42120. _this.NUM_BONE_INFLUENCERS = 0;
  42121. _this.BonesPerMesh = 0;
  42122. _this.INSTANCES = false;
  42123. _this.GLOSSINESS = false;
  42124. _this.ROUGHNESS = false;
  42125. _this.EMISSIVEASILLUMINATION = false;
  42126. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42127. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42128. _this.LIGHTMAP = false;
  42129. _this.LIGHTMAPDIRECTUV = 0;
  42130. _this.USELIGHTMAPASSHADOWMAP = false;
  42131. _this.REFLECTIONMAP_3D = false;
  42132. _this.REFLECTIONMAP_SPHERICAL = false;
  42133. _this.REFLECTIONMAP_PLANAR = false;
  42134. _this.REFLECTIONMAP_CUBIC = false;
  42135. _this.REFLECTIONMAP_PROJECTION = false;
  42136. _this.REFLECTIONMAP_SKYBOX = false;
  42137. _this.REFLECTIONMAP_EXPLICIT = false;
  42138. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42139. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42140. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42141. _this.INVERTCUBICMAP = false;
  42142. _this.LOGARITHMICDEPTH = false;
  42143. _this.REFRACTION = false;
  42144. _this.REFRACTIONMAP_3D = false;
  42145. _this.REFLECTIONOVERALPHA = false;
  42146. _this.INVERTNORMALMAPX = false;
  42147. _this.INVERTNORMALMAPY = false;
  42148. _this.TWOSIDEDLIGHTING = false;
  42149. _this.SHADOWFLOAT = false;
  42150. _this.MORPHTARGETS = false;
  42151. _this.MORPHTARGETS_NORMAL = false;
  42152. _this.MORPHTARGETS_TANGENT = false;
  42153. _this.NUM_MORPH_INFLUENCERS = 0;
  42154. _this.USERIGHTHANDEDSYSTEM = false;
  42155. _this.IMAGEPROCESSING = false;
  42156. _this.VIGNETTE = false;
  42157. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42158. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42159. _this.TONEMAPPING = false;
  42160. _this.CONTRAST = false;
  42161. _this.COLORCURVES = false;
  42162. _this.COLORGRADING = false;
  42163. _this.SAMPLER3DGREENDEPTH = false;
  42164. _this.SAMPLER3DBGRMAP = false;
  42165. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42166. _this.EXPOSURE = false;
  42167. _this.rebuild();
  42168. return _this;
  42169. }
  42170. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42171. var modes = [
  42172. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42173. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42174. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42175. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42176. ];
  42177. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42178. var mode = modes_1[_i];
  42179. this[mode] = (mode === modeToEnable);
  42180. }
  42181. };
  42182. return StandardMaterialDefines;
  42183. }(BABYLON.MaterialDefines));
  42184. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42185. var StandardMaterial = (function (_super) {
  42186. __extends(StandardMaterial, _super);
  42187. function StandardMaterial(name, scene) {
  42188. var _this = _super.call(this, name, scene) || this;
  42189. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42190. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42191. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42192. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42193. _this.specularPower = 64;
  42194. _this._useAlphaFromDiffuseTexture = false;
  42195. _this._useEmissiveAsIllumination = false;
  42196. _this._linkEmissiveWithDiffuse = false;
  42197. _this._useSpecularOverAlpha = false;
  42198. _this._useReflectionOverAlpha = false;
  42199. _this._disableLighting = false;
  42200. _this._useParallax = false;
  42201. _this._useParallaxOcclusion = false;
  42202. _this.parallaxScaleBias = 0.05;
  42203. _this._roughness = 0;
  42204. _this.indexOfRefraction = 0.98;
  42205. _this.invertRefractionY = true;
  42206. _this._useLightmapAsShadowmap = false;
  42207. _this._useReflectionFresnelFromSpecular = false;
  42208. _this._useGlossinessFromSpecularMapAlpha = false;
  42209. _this._maxSimultaneousLights = 4;
  42210. /**
  42211. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42212. */
  42213. _this._invertNormalMapX = false;
  42214. /**
  42215. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42216. */
  42217. _this._invertNormalMapY = false;
  42218. /**
  42219. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42220. */
  42221. _this._twoSidedLighting = false;
  42222. _this._renderTargets = new BABYLON.SmartArray(16);
  42223. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42224. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42225. // Setup the default processing configuration to the scene.
  42226. _this._attachImageProcessingConfiguration(null);
  42227. _this.getRenderTargetTextures = function () {
  42228. _this._renderTargets.reset();
  42229. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42230. _this._renderTargets.push(_this._reflectionTexture);
  42231. }
  42232. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42233. _this._renderTargets.push(_this._refractionTexture);
  42234. }
  42235. return _this._renderTargets;
  42236. };
  42237. return _this;
  42238. }
  42239. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42240. /**
  42241. * Gets the image processing configuration used either in this material.
  42242. */
  42243. get: function () {
  42244. return this._imageProcessingConfiguration;
  42245. },
  42246. /**
  42247. * Sets the Default image processing configuration used either in the this material.
  42248. *
  42249. * If sets to null, the scene one is in use.
  42250. */
  42251. set: function (value) {
  42252. this._attachImageProcessingConfiguration(value);
  42253. // Ensure the effect will be rebuilt.
  42254. this._markAllSubMeshesAsTexturesDirty();
  42255. },
  42256. enumerable: true,
  42257. configurable: true
  42258. });
  42259. /**
  42260. * Attaches a new image processing configuration to the Standard Material.
  42261. * @param configuration
  42262. */
  42263. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42264. var _this = this;
  42265. if (configuration === this._imageProcessingConfiguration) {
  42266. return;
  42267. }
  42268. // Detaches observer.
  42269. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42270. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42271. }
  42272. // Pick the scene configuration if needed.
  42273. if (!configuration) {
  42274. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42275. }
  42276. else {
  42277. this._imageProcessingConfiguration = configuration;
  42278. }
  42279. // Attaches observer.
  42280. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42281. _this._markAllSubMeshesAsImageProcessingDirty();
  42282. });
  42283. };
  42284. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42285. /**
  42286. * Gets wether the color curves effect is enabled.
  42287. */
  42288. get: function () {
  42289. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42290. },
  42291. /**
  42292. * Sets wether the color curves effect is enabled.
  42293. */
  42294. set: function (value) {
  42295. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42296. },
  42297. enumerable: true,
  42298. configurable: true
  42299. });
  42300. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42301. /**
  42302. * Gets wether the color grading effect is enabled.
  42303. */
  42304. get: function () {
  42305. return this.imageProcessingConfiguration.colorGradingEnabled;
  42306. },
  42307. /**
  42308. * Gets wether the color grading effect is enabled.
  42309. */
  42310. set: function (value) {
  42311. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42312. },
  42313. enumerable: true,
  42314. configurable: true
  42315. });
  42316. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42317. /**
  42318. * Gets wether tonemapping is enabled or not.
  42319. */
  42320. get: function () {
  42321. return this._imageProcessingConfiguration.toneMappingEnabled;
  42322. },
  42323. /**
  42324. * Sets wether tonemapping is enabled or not
  42325. */
  42326. set: function (value) {
  42327. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42328. },
  42329. enumerable: true,
  42330. configurable: true
  42331. });
  42332. ;
  42333. ;
  42334. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42335. /**
  42336. * The camera exposure used on this material.
  42337. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42338. * This corresponds to a photographic exposure.
  42339. */
  42340. get: function () {
  42341. return this._imageProcessingConfiguration.exposure;
  42342. },
  42343. /**
  42344. * The camera exposure used on this material.
  42345. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42346. * This corresponds to a photographic exposure.
  42347. */
  42348. set: function (value) {
  42349. this._imageProcessingConfiguration.exposure = value;
  42350. },
  42351. enumerable: true,
  42352. configurable: true
  42353. });
  42354. ;
  42355. ;
  42356. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42357. /**
  42358. * Gets The camera contrast used on this material.
  42359. */
  42360. get: function () {
  42361. return this._imageProcessingConfiguration.contrast;
  42362. },
  42363. /**
  42364. * Sets The camera contrast used on this material.
  42365. */
  42366. set: function (value) {
  42367. this._imageProcessingConfiguration.contrast = value;
  42368. },
  42369. enumerable: true,
  42370. configurable: true
  42371. });
  42372. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42373. /**
  42374. * Gets the Color Grading 2D Lookup Texture.
  42375. */
  42376. get: function () {
  42377. return this._imageProcessingConfiguration.colorGradingTexture;
  42378. },
  42379. /**
  42380. * Sets the Color Grading 2D Lookup Texture.
  42381. */
  42382. set: function (value) {
  42383. this._imageProcessingConfiguration.colorGradingTexture = value;
  42384. },
  42385. enumerable: true,
  42386. configurable: true
  42387. });
  42388. StandardMaterial.prototype.getClassName = function () {
  42389. return "StandardMaterial";
  42390. };
  42391. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42392. get: function () {
  42393. return this._useLogarithmicDepth;
  42394. },
  42395. set: function (value) {
  42396. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42397. this._markAllSubMeshesAsMiscDirty();
  42398. },
  42399. enumerable: true,
  42400. configurable: true
  42401. });
  42402. StandardMaterial.prototype.needAlphaBlending = function () {
  42403. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42404. };
  42405. StandardMaterial.prototype.needAlphaTesting = function () {
  42406. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42407. };
  42408. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42409. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42410. };
  42411. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42412. return this._diffuseTexture;
  42413. };
  42414. /**
  42415. * Child classes can use it to update shaders
  42416. */
  42417. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42418. if (this.isFrozen) {
  42419. if (this._wasPreviouslyReady && subMesh.effect) {
  42420. return true;
  42421. }
  42422. }
  42423. if (!subMesh._materialDefines) {
  42424. subMesh._materialDefines = new StandardMaterialDefines();
  42425. }
  42426. var scene = this.getScene();
  42427. var defines = subMesh._materialDefines;
  42428. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42429. if (defines._renderId === scene.getRenderId()) {
  42430. return true;
  42431. }
  42432. }
  42433. var engine = scene.getEngine();
  42434. // Lights
  42435. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42436. // Textures
  42437. if (defines._areTexturesDirty) {
  42438. defines._needUVs = false;
  42439. defines.MAINUV1 = false;
  42440. defines.MAINUV2 = false;
  42441. if (scene.texturesEnabled) {
  42442. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42443. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42444. return false;
  42445. }
  42446. else {
  42447. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42448. }
  42449. }
  42450. else {
  42451. defines.DIFFUSE = false;
  42452. }
  42453. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42454. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42455. return false;
  42456. }
  42457. else {
  42458. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42459. }
  42460. }
  42461. else {
  42462. defines.AMBIENT = false;
  42463. }
  42464. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42465. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42466. return false;
  42467. }
  42468. else {
  42469. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42470. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42471. }
  42472. }
  42473. else {
  42474. defines.OPACITY = false;
  42475. }
  42476. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42477. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42478. return false;
  42479. }
  42480. else {
  42481. defines._needNormals = true;
  42482. defines.REFLECTION = true;
  42483. defines.ROUGHNESS = (this._roughness > 0);
  42484. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42485. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42486. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42487. switch (this._reflectionTexture.coordinatesMode) {
  42488. case BABYLON.Texture.CUBIC_MODE:
  42489. case BABYLON.Texture.INVCUBIC_MODE:
  42490. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42491. break;
  42492. case BABYLON.Texture.EXPLICIT_MODE:
  42493. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42494. break;
  42495. case BABYLON.Texture.PLANAR_MODE:
  42496. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42497. break;
  42498. case BABYLON.Texture.PROJECTION_MODE:
  42499. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42500. break;
  42501. case BABYLON.Texture.SKYBOX_MODE:
  42502. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42503. break;
  42504. case BABYLON.Texture.SPHERICAL_MODE:
  42505. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42506. break;
  42507. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42508. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42509. break;
  42510. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42511. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42512. break;
  42513. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42514. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42515. break;
  42516. }
  42517. }
  42518. }
  42519. else {
  42520. defines.REFLECTION = false;
  42521. }
  42522. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42523. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42524. return false;
  42525. }
  42526. else {
  42527. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42528. }
  42529. }
  42530. else {
  42531. defines.EMISSIVE = false;
  42532. }
  42533. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42534. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42535. return false;
  42536. }
  42537. else {
  42538. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42539. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42540. }
  42541. }
  42542. else {
  42543. defines.LIGHTMAP = false;
  42544. }
  42545. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42546. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42547. return false;
  42548. }
  42549. else {
  42550. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42551. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42552. }
  42553. }
  42554. else {
  42555. defines.SPECULAR = false;
  42556. }
  42557. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42558. // Bump texure can not be not blocking.
  42559. if (!this._bumpTexture.isReady()) {
  42560. return false;
  42561. }
  42562. else {
  42563. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42564. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  42565. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  42566. defines.PARALLAX = this._useParallax;
  42567. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42568. }
  42569. }
  42570. else {
  42571. defines.BUMP = false;
  42572. }
  42573. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42574. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42575. return false;
  42576. }
  42577. else {
  42578. defines._needUVs = true;
  42579. defines.REFRACTION = true;
  42580. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42581. }
  42582. }
  42583. else {
  42584. defines.REFRACTION = false;
  42585. }
  42586. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42587. }
  42588. else {
  42589. defines.DIFFUSE = false;
  42590. defines.AMBIENT = false;
  42591. defines.OPACITY = false;
  42592. defines.REFLECTION = false;
  42593. defines.EMISSIVE = false;
  42594. defines.LIGHTMAP = false;
  42595. defines.BUMP = false;
  42596. defines.REFRACTION = false;
  42597. }
  42598. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42599. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42600. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42601. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42602. }
  42603. if (defines._areImageProcessingDirty) {
  42604. if (!this._imageProcessingConfiguration.isReady()) {
  42605. return false;
  42606. }
  42607. this._imageProcessingConfiguration.prepareDefines(defines);
  42608. }
  42609. if (defines._areFresnelDirty) {
  42610. if (StandardMaterial.FresnelEnabled) {
  42611. // Fresnel
  42612. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42613. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42614. this._reflectionFresnelParameters) {
  42615. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42616. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42617. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42618. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42619. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42620. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42621. defines._needNormals = true;
  42622. defines.FRESNEL = true;
  42623. }
  42624. }
  42625. else {
  42626. defines.FRESNEL = false;
  42627. }
  42628. }
  42629. // Misc.
  42630. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  42631. // Attribs
  42632. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42633. // Values that need to be evaluated on every frame
  42634. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42635. if (scene._mirroredCameraPosition && defines.BUMP) {
  42636. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  42637. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  42638. defines.markAsUnprocessed();
  42639. }
  42640. // Get correct effect
  42641. if (defines.isDirty) {
  42642. defines.markAsProcessed();
  42643. scene.resetCachedMaterial();
  42644. // Fallbacks
  42645. var fallbacks = new BABYLON.EffectFallbacks();
  42646. if (defines.REFLECTION) {
  42647. fallbacks.addFallback(0, "REFLECTION");
  42648. }
  42649. if (defines.SPECULAR) {
  42650. fallbacks.addFallback(0, "SPECULAR");
  42651. }
  42652. if (defines.BUMP) {
  42653. fallbacks.addFallback(0, "BUMP");
  42654. }
  42655. if (defines.PARALLAX) {
  42656. fallbacks.addFallback(1, "PARALLAX");
  42657. }
  42658. if (defines.PARALLAXOCCLUSION) {
  42659. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42660. }
  42661. if (defines.SPECULAROVERALPHA) {
  42662. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42663. }
  42664. if (defines.FOG) {
  42665. fallbacks.addFallback(1, "FOG");
  42666. }
  42667. if (defines.POINTSIZE) {
  42668. fallbacks.addFallback(0, "POINTSIZE");
  42669. }
  42670. if (defines.LOGARITHMICDEPTH) {
  42671. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42672. }
  42673. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42674. if (defines.SPECULARTERM) {
  42675. fallbacks.addFallback(0, "SPECULARTERM");
  42676. }
  42677. if (defines.DIFFUSEFRESNEL) {
  42678. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42679. }
  42680. if (defines.OPACITYFRESNEL) {
  42681. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42682. }
  42683. if (defines.REFLECTIONFRESNEL) {
  42684. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42685. }
  42686. if (defines.EMISSIVEFRESNEL) {
  42687. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42688. }
  42689. if (defines.FRESNEL) {
  42690. fallbacks.addFallback(4, "FRESNEL");
  42691. }
  42692. //Attributes
  42693. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42694. if (defines.NORMAL) {
  42695. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42696. }
  42697. if (defines.UV1) {
  42698. attribs.push(BABYLON.VertexBuffer.UVKind);
  42699. }
  42700. if (defines.UV2) {
  42701. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42702. }
  42703. if (defines.VERTEXCOLOR) {
  42704. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42705. }
  42706. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42707. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42708. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42709. var shaderName = "default";
  42710. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42711. "vFogInfos", "vFogColor", "pointSize",
  42712. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42713. "mBones",
  42714. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42715. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42716. "logarithmicDepthConstant"
  42717. ];
  42718. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42719. var uniformBuffers = ["Material", "Scene"];
  42720. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42721. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42722. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42723. uniformsNames: uniforms,
  42724. uniformBuffersNames: uniformBuffers,
  42725. samplers: samplers,
  42726. defines: defines,
  42727. maxSimultaneousLights: this._maxSimultaneousLights
  42728. });
  42729. if (this.customShaderNameResolve) {
  42730. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42731. }
  42732. var join = defines.toString();
  42733. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42734. attributes: attribs,
  42735. uniformsNames: uniforms,
  42736. uniformBuffersNames: uniformBuffers,
  42737. samplers: samplers,
  42738. defines: join,
  42739. fallbacks: fallbacks,
  42740. onCompiled: this.onCompiled,
  42741. onError: this.onError,
  42742. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42743. }, engine), defines);
  42744. this.buildUniformLayout();
  42745. }
  42746. if (!subMesh.effect.isReady()) {
  42747. return false;
  42748. }
  42749. defines._renderId = scene.getRenderId();
  42750. this._wasPreviouslyReady = true;
  42751. return true;
  42752. };
  42753. StandardMaterial.prototype.buildUniformLayout = function () {
  42754. // Order is important !
  42755. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42756. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42757. this._uniformBuffer.addUniform("opacityParts", 4);
  42758. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42759. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42760. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42761. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42762. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42763. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42764. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42765. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42766. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42767. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42768. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42769. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42770. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42771. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42772. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42773. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42774. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42775. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42776. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42777. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42778. this._uniformBuffer.addUniform("specularMatrix", 16);
  42779. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42780. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42781. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42782. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42783. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42784. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42785. this._uniformBuffer.addUniform("pointSize", 1);
  42786. this._uniformBuffer.create();
  42787. };
  42788. StandardMaterial.prototype.unbind = function () {
  42789. if (this._activeEffect) {
  42790. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42791. this._activeEffect.setTexture("reflection2DSampler", null);
  42792. }
  42793. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42794. this._activeEffect.setTexture("refraction2DSampler", null);
  42795. }
  42796. }
  42797. _super.prototype.unbind.call(this);
  42798. };
  42799. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42800. var scene = this.getScene();
  42801. var defines = subMesh._materialDefines;
  42802. if (!defines) {
  42803. return;
  42804. }
  42805. var effect = subMesh.effect;
  42806. this._activeEffect = effect;
  42807. // Matrices
  42808. this.bindOnlyWorldMatrix(world);
  42809. // Bones
  42810. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42811. if (this._mustRebind(scene, effect, mesh.visibility)) {
  42812. this._uniformBuffer.bindToEffect(effect, "Material");
  42813. this.bindViewProjection(effect);
  42814. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42815. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42816. // Fresnel
  42817. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42818. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42819. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42820. }
  42821. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42822. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42823. }
  42824. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42825. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42826. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42827. }
  42828. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42829. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42830. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42831. }
  42832. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42833. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42834. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42835. }
  42836. }
  42837. // Textures
  42838. if (scene.texturesEnabled) {
  42839. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42840. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42841. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42842. }
  42843. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42844. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42845. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42846. }
  42847. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42848. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42849. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42850. }
  42851. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42852. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42853. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42854. }
  42855. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42856. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42857. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42858. }
  42859. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42860. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42861. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42862. }
  42863. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42864. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42865. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42866. }
  42867. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42868. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42869. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42870. }
  42871. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42872. var depth = 1.0;
  42873. if (!this._refractionTexture.isCube) {
  42874. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42875. if (this._refractionTexture.depth) {
  42876. depth = this._refractionTexture.depth;
  42877. }
  42878. }
  42879. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42880. }
  42881. }
  42882. // Point size
  42883. if (this.pointsCloud) {
  42884. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42885. }
  42886. if (defines.SPECULARTERM) {
  42887. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42888. }
  42889. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42890. // Diffuse
  42891. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42892. }
  42893. // Textures
  42894. if (scene.texturesEnabled) {
  42895. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42896. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42897. }
  42898. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42899. effect.setTexture("ambientSampler", this._ambientTexture);
  42900. }
  42901. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42902. effect.setTexture("opacitySampler", this._opacityTexture);
  42903. }
  42904. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42905. if (this._reflectionTexture.isCube) {
  42906. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42907. }
  42908. else {
  42909. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42910. }
  42911. }
  42912. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42913. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42914. }
  42915. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42916. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42917. }
  42918. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42919. effect.setTexture("specularSampler", this._specularTexture);
  42920. }
  42921. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42922. effect.setTexture("bumpSampler", this._bumpTexture);
  42923. }
  42924. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42925. var depth = 1.0;
  42926. if (this._refractionTexture.isCube) {
  42927. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42928. }
  42929. else {
  42930. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42931. }
  42932. }
  42933. }
  42934. // Clip plane
  42935. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42936. // Colors
  42937. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42938. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  42939. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42940. }
  42941. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  42942. // Lights
  42943. if (scene.lightsEnabled && !this._disableLighting) {
  42944. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42945. }
  42946. // View
  42947. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42948. this.bindView(effect);
  42949. }
  42950. // Fog
  42951. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42952. // Morph targets
  42953. if (defines.NUM_MORPH_INFLUENCERS) {
  42954. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42955. }
  42956. // Log. depth
  42957. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42958. // image processing
  42959. this._imageProcessingConfiguration.bind(this._activeEffect);
  42960. }
  42961. this._uniformBuffer.update();
  42962. this._afterBind(mesh, this._activeEffect);
  42963. };
  42964. StandardMaterial.prototype.getAnimatables = function () {
  42965. var results = [];
  42966. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42967. results.push(this._diffuseTexture);
  42968. }
  42969. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42970. results.push(this._ambientTexture);
  42971. }
  42972. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42973. results.push(this._opacityTexture);
  42974. }
  42975. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42976. results.push(this._reflectionTexture);
  42977. }
  42978. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42979. results.push(this._emissiveTexture);
  42980. }
  42981. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42982. results.push(this._specularTexture);
  42983. }
  42984. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42985. results.push(this._bumpTexture);
  42986. }
  42987. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42988. results.push(this._lightmapTexture);
  42989. }
  42990. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42991. results.push(this._refractionTexture);
  42992. }
  42993. return results;
  42994. };
  42995. StandardMaterial.prototype.getActiveTextures = function () {
  42996. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42997. if (this._diffuseTexture) {
  42998. activeTextures.push(this._diffuseTexture);
  42999. }
  43000. if (this._ambientTexture) {
  43001. activeTextures.push(this._ambientTexture);
  43002. }
  43003. if (this._opacityTexture) {
  43004. activeTextures.push(this._opacityTexture);
  43005. }
  43006. if (this._reflectionTexture) {
  43007. activeTextures.push(this._reflectionTexture);
  43008. }
  43009. if (this._emissiveTexture) {
  43010. activeTextures.push(this._emissiveTexture);
  43011. }
  43012. if (this._specularTexture) {
  43013. activeTextures.push(this._specularTexture);
  43014. }
  43015. if (this._bumpTexture) {
  43016. activeTextures.push(this._bumpTexture);
  43017. }
  43018. if (this._lightmapTexture) {
  43019. activeTextures.push(this._lightmapTexture);
  43020. }
  43021. if (this._refractionTexture) {
  43022. activeTextures.push(this._refractionTexture);
  43023. }
  43024. return activeTextures;
  43025. };
  43026. StandardMaterial.prototype.hasTexture = function (texture) {
  43027. if (_super.prototype.hasTexture.call(this, texture)) {
  43028. return true;
  43029. }
  43030. if (this._diffuseTexture === texture) {
  43031. return true;
  43032. }
  43033. if (this._ambientTexture === texture) {
  43034. return true;
  43035. }
  43036. if (this._opacityTexture === texture) {
  43037. return true;
  43038. }
  43039. if (this._reflectionTexture === texture) {
  43040. return true;
  43041. }
  43042. if (this._emissiveTexture === texture) {
  43043. return true;
  43044. }
  43045. if (this._specularTexture === texture) {
  43046. return true;
  43047. }
  43048. if (this._bumpTexture === texture) {
  43049. return true;
  43050. }
  43051. if (this._lightmapTexture === texture) {
  43052. return true;
  43053. }
  43054. if (this._refractionTexture === texture) {
  43055. return true;
  43056. }
  43057. return false;
  43058. };
  43059. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43060. if (forceDisposeTextures) {
  43061. if (this._diffuseTexture) {
  43062. this._diffuseTexture.dispose();
  43063. }
  43064. if (this._ambientTexture) {
  43065. this._ambientTexture.dispose();
  43066. }
  43067. if (this._opacityTexture) {
  43068. this._opacityTexture.dispose();
  43069. }
  43070. if (this._reflectionTexture) {
  43071. this._reflectionTexture.dispose();
  43072. }
  43073. if (this._emissiveTexture) {
  43074. this._emissiveTexture.dispose();
  43075. }
  43076. if (this._specularTexture) {
  43077. this._specularTexture.dispose();
  43078. }
  43079. if (this._bumpTexture) {
  43080. this._bumpTexture.dispose();
  43081. }
  43082. if (this._lightmapTexture) {
  43083. this._lightmapTexture.dispose();
  43084. }
  43085. if (this._refractionTexture) {
  43086. this._refractionTexture.dispose();
  43087. }
  43088. }
  43089. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43090. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43091. }
  43092. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43093. };
  43094. StandardMaterial.prototype.clone = function (name) {
  43095. var _this = this;
  43096. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43097. result.name = name;
  43098. result.id = name;
  43099. return result;
  43100. };
  43101. StandardMaterial.prototype.serialize = function () {
  43102. return BABYLON.SerializationHelper.Serialize(this);
  43103. };
  43104. // Statics
  43105. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43106. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43107. };
  43108. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43109. get: function () {
  43110. return StandardMaterial._DiffuseTextureEnabled;
  43111. },
  43112. set: function (value) {
  43113. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43114. return;
  43115. }
  43116. StandardMaterial._DiffuseTextureEnabled = value;
  43117. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43118. },
  43119. enumerable: true,
  43120. configurable: true
  43121. });
  43122. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43123. get: function () {
  43124. return StandardMaterial._AmbientTextureEnabled;
  43125. },
  43126. set: function (value) {
  43127. if (StandardMaterial._AmbientTextureEnabled === value) {
  43128. return;
  43129. }
  43130. StandardMaterial._AmbientTextureEnabled = value;
  43131. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43137. get: function () {
  43138. return StandardMaterial._OpacityTextureEnabled;
  43139. },
  43140. set: function (value) {
  43141. if (StandardMaterial._OpacityTextureEnabled === value) {
  43142. return;
  43143. }
  43144. StandardMaterial._OpacityTextureEnabled = value;
  43145. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43146. },
  43147. enumerable: true,
  43148. configurable: true
  43149. });
  43150. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43151. get: function () {
  43152. return StandardMaterial._ReflectionTextureEnabled;
  43153. },
  43154. set: function (value) {
  43155. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43156. return;
  43157. }
  43158. StandardMaterial._ReflectionTextureEnabled = value;
  43159. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43160. },
  43161. enumerable: true,
  43162. configurable: true
  43163. });
  43164. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43165. get: function () {
  43166. return StandardMaterial._EmissiveTextureEnabled;
  43167. },
  43168. set: function (value) {
  43169. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43170. return;
  43171. }
  43172. StandardMaterial._EmissiveTextureEnabled = value;
  43173. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43174. },
  43175. enumerable: true,
  43176. configurable: true
  43177. });
  43178. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43179. get: function () {
  43180. return StandardMaterial._SpecularTextureEnabled;
  43181. },
  43182. set: function (value) {
  43183. if (StandardMaterial._SpecularTextureEnabled === value) {
  43184. return;
  43185. }
  43186. StandardMaterial._SpecularTextureEnabled = value;
  43187. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43188. },
  43189. enumerable: true,
  43190. configurable: true
  43191. });
  43192. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43193. get: function () {
  43194. return StandardMaterial._BumpTextureEnabled;
  43195. },
  43196. set: function (value) {
  43197. if (StandardMaterial._BumpTextureEnabled === value) {
  43198. return;
  43199. }
  43200. StandardMaterial._BumpTextureEnabled = value;
  43201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43202. },
  43203. enumerable: true,
  43204. configurable: true
  43205. });
  43206. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43207. get: function () {
  43208. return StandardMaterial._LightmapTextureEnabled;
  43209. },
  43210. set: function (value) {
  43211. if (StandardMaterial._LightmapTextureEnabled === value) {
  43212. return;
  43213. }
  43214. StandardMaterial._LightmapTextureEnabled = value;
  43215. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43216. },
  43217. enumerable: true,
  43218. configurable: true
  43219. });
  43220. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43221. get: function () {
  43222. return StandardMaterial._RefractionTextureEnabled;
  43223. },
  43224. set: function (value) {
  43225. if (StandardMaterial._RefractionTextureEnabled === value) {
  43226. return;
  43227. }
  43228. StandardMaterial._RefractionTextureEnabled = value;
  43229. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43230. },
  43231. enumerable: true,
  43232. configurable: true
  43233. });
  43234. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43235. get: function () {
  43236. return StandardMaterial._ColorGradingTextureEnabled;
  43237. },
  43238. set: function (value) {
  43239. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43240. return;
  43241. }
  43242. StandardMaterial._ColorGradingTextureEnabled = value;
  43243. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43244. },
  43245. enumerable: true,
  43246. configurable: true
  43247. });
  43248. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43249. get: function () {
  43250. return StandardMaterial._FresnelEnabled;
  43251. },
  43252. set: function (value) {
  43253. if (StandardMaterial._FresnelEnabled === value) {
  43254. return;
  43255. }
  43256. StandardMaterial._FresnelEnabled = value;
  43257. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43258. },
  43259. enumerable: true,
  43260. configurable: true
  43261. });
  43262. return StandardMaterial;
  43263. }(BABYLON.PushMaterial));
  43264. // Flags used to enable or disable a type of texture for all Standard Materials
  43265. StandardMaterial._DiffuseTextureEnabled = true;
  43266. StandardMaterial._AmbientTextureEnabled = true;
  43267. StandardMaterial._OpacityTextureEnabled = true;
  43268. StandardMaterial._ReflectionTextureEnabled = true;
  43269. StandardMaterial._EmissiveTextureEnabled = true;
  43270. StandardMaterial._SpecularTextureEnabled = true;
  43271. StandardMaterial._BumpTextureEnabled = true;
  43272. StandardMaterial._LightmapTextureEnabled = true;
  43273. StandardMaterial._RefractionTextureEnabled = true;
  43274. StandardMaterial._ColorGradingTextureEnabled = true;
  43275. StandardMaterial._FresnelEnabled = true;
  43276. __decorate([
  43277. BABYLON.serializeAsTexture("diffuseTexture")
  43278. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43279. __decorate([
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43281. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43282. __decorate([
  43283. BABYLON.serializeAsTexture("ambientTexture")
  43284. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43285. __decorate([
  43286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43287. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43288. __decorate([
  43289. BABYLON.serializeAsTexture("opacityTexture")
  43290. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43291. __decorate([
  43292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43293. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43294. __decorate([
  43295. BABYLON.serializeAsTexture("reflectionTexture")
  43296. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43297. __decorate([
  43298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43299. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43300. __decorate([
  43301. BABYLON.serializeAsTexture("emissiveTexture")
  43302. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43303. __decorate([
  43304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43305. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43306. __decorate([
  43307. BABYLON.serializeAsTexture("specularTexture")
  43308. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43309. __decorate([
  43310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43311. ], StandardMaterial.prototype, "specularTexture", void 0);
  43312. __decorate([
  43313. BABYLON.serializeAsTexture("bumpTexture")
  43314. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43315. __decorate([
  43316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43317. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43318. __decorate([
  43319. BABYLON.serializeAsTexture("lightmapTexture")
  43320. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43321. __decorate([
  43322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43323. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43324. __decorate([
  43325. BABYLON.serializeAsTexture("refractionTexture")
  43326. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43327. __decorate([
  43328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43329. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43330. __decorate([
  43331. BABYLON.serializeAsColor3("ambient")
  43332. ], StandardMaterial.prototype, "ambientColor", void 0);
  43333. __decorate([
  43334. BABYLON.serializeAsColor3("diffuse")
  43335. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43336. __decorate([
  43337. BABYLON.serializeAsColor3("specular")
  43338. ], StandardMaterial.prototype, "specularColor", void 0);
  43339. __decorate([
  43340. BABYLON.serializeAsColor3("emissive")
  43341. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43342. __decorate([
  43343. BABYLON.serialize()
  43344. ], StandardMaterial.prototype, "specularPower", void 0);
  43345. __decorate([
  43346. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43347. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43348. __decorate([
  43349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43350. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43351. __decorate([
  43352. BABYLON.serialize("useEmissiveAsIllumination")
  43353. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43354. __decorate([
  43355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43356. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43357. __decorate([
  43358. BABYLON.serialize("linkEmissiveWithDiffuse")
  43359. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43360. __decorate([
  43361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43362. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43363. __decorate([
  43364. BABYLON.serialize("useSpecularOverAlpha")
  43365. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43366. __decorate([
  43367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43368. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43369. __decorate([
  43370. BABYLON.serialize("useReflectionOverAlpha")
  43371. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43372. __decorate([
  43373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43374. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43375. __decorate([
  43376. BABYLON.serialize("disableLighting")
  43377. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43378. __decorate([
  43379. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43380. ], StandardMaterial.prototype, "disableLighting", void 0);
  43381. __decorate([
  43382. BABYLON.serialize("useParallax")
  43383. ], StandardMaterial.prototype, "_useParallax", void 0);
  43384. __decorate([
  43385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43386. ], StandardMaterial.prototype, "useParallax", void 0);
  43387. __decorate([
  43388. BABYLON.serialize("useParallaxOcclusion")
  43389. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43390. __decorate([
  43391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43392. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43393. __decorate([
  43394. BABYLON.serialize()
  43395. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43396. __decorate([
  43397. BABYLON.serialize("roughness")
  43398. ], StandardMaterial.prototype, "_roughness", void 0);
  43399. __decorate([
  43400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43401. ], StandardMaterial.prototype, "roughness", void 0);
  43402. __decorate([
  43403. BABYLON.serialize()
  43404. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43408. __decorate([
  43409. BABYLON.serialize("useLightmapAsShadowmap")
  43410. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43411. __decorate([
  43412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43413. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43414. __decorate([
  43415. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43416. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43417. __decorate([
  43418. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43419. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43420. __decorate([
  43421. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43422. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43423. __decorate([
  43424. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43425. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43426. __decorate([
  43427. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43428. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43429. __decorate([
  43430. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43431. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43432. __decorate([
  43433. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43434. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43435. __decorate([
  43436. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43437. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43438. __decorate([
  43439. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43440. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43441. __decorate([
  43442. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43443. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43444. __decorate([
  43445. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43446. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43447. __decorate([
  43448. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43449. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43450. __decorate([
  43451. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43452. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43453. __decorate([
  43454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43455. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43456. __decorate([
  43457. BABYLON.serialize("maxSimultaneousLights")
  43458. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43459. __decorate([
  43460. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43461. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43462. __decorate([
  43463. BABYLON.serialize("invertNormalMapX")
  43464. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43465. __decorate([
  43466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43467. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43468. __decorate([
  43469. BABYLON.serialize("invertNormalMapY")
  43470. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43471. __decorate([
  43472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43473. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43474. __decorate([
  43475. BABYLON.serialize("twoSidedLighting")
  43476. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43477. __decorate([
  43478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43479. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43480. __decorate([
  43481. BABYLON.serialize()
  43482. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43483. BABYLON.StandardMaterial = StandardMaterial;
  43484. })(BABYLON || (BABYLON = {}));
  43485. //# sourceMappingURL=babylon.standardMaterial.js.map
  43486. var BABYLON;
  43487. (function (BABYLON) {
  43488. /**
  43489. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43490. * The underlying implementation relies on an associative array to ensure the best performances.
  43491. * The value can be anything including 'null' but except 'undefined'
  43492. */
  43493. var StringDictionary = (function () {
  43494. function StringDictionary() {
  43495. this._count = 0;
  43496. this._data = {};
  43497. }
  43498. /**
  43499. * This will clear this dictionary and copy the content from the 'source' one.
  43500. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43501. * @param source the dictionary to take the content from and copy to this dictionary
  43502. */
  43503. StringDictionary.prototype.copyFrom = function (source) {
  43504. var _this = this;
  43505. this.clear();
  43506. source.forEach(function (t, v) { return _this.add(t, v); });
  43507. };
  43508. /**
  43509. * Get a value based from its key
  43510. * @param key the given key to get the matching value from
  43511. * @return the value if found, otherwise undefined is returned
  43512. */
  43513. StringDictionary.prototype.get = function (key) {
  43514. var val = this._data[key];
  43515. if (val !== undefined) {
  43516. return val;
  43517. }
  43518. return undefined;
  43519. };
  43520. /**
  43521. * Get a value from its key or add it if it doesn't exist.
  43522. * This method will ensure you that a given key/data will be present in the dictionary.
  43523. * @param key the given key to get the matching value from
  43524. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43525. * The factory will only be invoked if there's no data for the given key.
  43526. * @return the value corresponding to the key.
  43527. */
  43528. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43529. var val = this.get(key);
  43530. if (val !== undefined) {
  43531. return val;
  43532. }
  43533. val = factory(key);
  43534. if (val) {
  43535. this.add(key, val);
  43536. }
  43537. return val;
  43538. };
  43539. /**
  43540. * Get a value from its key if present in the dictionary otherwise add it
  43541. * @param key the key to get the value from
  43542. * @param val if there's no such key/value pair in the dictionary add it with this value
  43543. * @return the value corresponding to the key
  43544. */
  43545. StringDictionary.prototype.getOrAdd = function (key, val) {
  43546. var curVal = this.get(key);
  43547. if (curVal !== undefined) {
  43548. return curVal;
  43549. }
  43550. this.add(key, val);
  43551. return val;
  43552. };
  43553. /**
  43554. * Check if there's a given key in the dictionary
  43555. * @param key the key to check for
  43556. * @return true if the key is present, false otherwise
  43557. */
  43558. StringDictionary.prototype.contains = function (key) {
  43559. return this._data[key] !== undefined;
  43560. };
  43561. /**
  43562. * Add a new key and its corresponding value
  43563. * @param key the key to add
  43564. * @param value the value corresponding to the key
  43565. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  43566. */
  43567. StringDictionary.prototype.add = function (key, value) {
  43568. if (this._data[key] !== undefined) {
  43569. return false;
  43570. }
  43571. this._data[key] = value;
  43572. ++this._count;
  43573. return true;
  43574. };
  43575. StringDictionary.prototype.set = function (key, value) {
  43576. if (this._data[key] === undefined) {
  43577. return false;
  43578. }
  43579. this._data[key] = value;
  43580. return true;
  43581. };
  43582. /**
  43583. * Get the element of the given key and remove it from the dictionary
  43584. * @param key
  43585. */
  43586. StringDictionary.prototype.getAndRemove = function (key) {
  43587. var val = this.get(key);
  43588. if (val !== undefined) {
  43589. delete this._data[key];
  43590. --this._count;
  43591. return val;
  43592. }
  43593. return null;
  43594. };
  43595. /**
  43596. * Remove a key/value from the dictionary.
  43597. * @param key the key to remove
  43598. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43599. */
  43600. StringDictionary.prototype.remove = function (key) {
  43601. if (this.contains(key)) {
  43602. delete this._data[key];
  43603. --this._count;
  43604. return true;
  43605. }
  43606. return false;
  43607. };
  43608. /**
  43609. * Clear the whole content of the dictionary
  43610. */
  43611. StringDictionary.prototype.clear = function () {
  43612. this._data = {};
  43613. this._count = 0;
  43614. };
  43615. Object.defineProperty(StringDictionary.prototype, "count", {
  43616. get: function () {
  43617. return this._count;
  43618. },
  43619. enumerable: true,
  43620. configurable: true
  43621. });
  43622. /**
  43623. * Execute a callback on each key/val of the dictionary.
  43624. * Note that you can remove any element in this dictionary in the callback implementation
  43625. * @param callback the callback to execute on a given key/value pair
  43626. */
  43627. StringDictionary.prototype.forEach = function (callback) {
  43628. for (var cur in this._data) {
  43629. var val = this._data[cur];
  43630. callback(cur, val);
  43631. }
  43632. };
  43633. /**
  43634. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43635. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43636. * Note that you can remove any element in this dictionary in the callback implementation
  43637. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43638. */
  43639. StringDictionary.prototype.first = function (callback) {
  43640. for (var cur in this._data) {
  43641. var val = this._data[cur];
  43642. var res = callback(cur, val);
  43643. if (res) {
  43644. return res;
  43645. }
  43646. }
  43647. return null;
  43648. };
  43649. return StringDictionary;
  43650. }());
  43651. BABYLON.StringDictionary = StringDictionary;
  43652. })(BABYLON || (BABYLON = {}));
  43653. //# sourceMappingURL=babylon.stringDictionary.js.map
  43654. var BABYLON;
  43655. (function (BABYLON) {
  43656. var DynamicFloatArrayElementInfo = (function () {
  43657. function DynamicFloatArrayElementInfo() {
  43658. }
  43659. return DynamicFloatArrayElementInfo;
  43660. }());
  43661. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  43662. /**
  43663. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  43664. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  43665. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  43666. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  43667. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  43668. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  43669. */
  43670. var DynamicFloatArray = (function () {
  43671. /**
  43672. * Construct an instance of the dynamic float array
  43673. * @param stride size of one element in float (i.e. not bytes!)
  43674. * @param initialElementCount the number of available entries at construction
  43675. */
  43676. function DynamicFloatArray(stride, initialElementCount) {
  43677. this.compareValueOffset = null;
  43678. this.sortingAscending = true;
  43679. this._stride = stride;
  43680. this.buffer = new Float32Array(stride * initialElementCount);
  43681. this._lastUsed = 0;
  43682. this._firstFree = 0;
  43683. this._allEntries = new Array(initialElementCount);
  43684. this._freeEntries = new Array(initialElementCount);
  43685. for (var i = 0; i < initialElementCount; i++) {
  43686. var element = new DynamicFloatArrayElementInfo();
  43687. element.offset = i * stride;
  43688. this._allEntries[i] = element;
  43689. this._freeEntries[initialElementCount - i - 1] = element;
  43690. }
  43691. }
  43692. /**
  43693. * Allocate an element in the array.
  43694. * @return the element info instance that contains the offset into the main buffer of the element's location.
  43695. * Beware, this offset may change when you call pack()
  43696. */
  43697. DynamicFloatArray.prototype.allocElement = function () {
  43698. if (this._freeEntries.length === 0) {
  43699. this._growBuffer();
  43700. }
  43701. var el = this._freeEntries.pop();
  43702. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43703. if (el.offset === this._firstFree) {
  43704. if (this._freeEntries.length > 0) {
  43705. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43706. }
  43707. else {
  43708. this._firstFree += this._stride;
  43709. }
  43710. }
  43711. return el;
  43712. };
  43713. /**
  43714. * Free the element corresponding to the given element info
  43715. * @param elInfo the element that describe the allocated element
  43716. */
  43717. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43718. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43719. this._freeEntries.push(elInfo);
  43720. };
  43721. /**
  43722. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43723. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  43724. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43725. */
  43726. DynamicFloatArray.prototype.pack = function () {
  43727. // no free slot? no need to pack
  43728. if (this._freeEntries.length === 0) {
  43729. return this.buffer;
  43730. }
  43731. // If the buffer is already packed the last used will always be lower than the first free
  43732. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  43733. if (this._lastUsed < this._firstFree) {
  43734. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43735. return elementsBuffer_1;
  43736. }
  43737. var s = this._stride;
  43738. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  43739. var lastFree = new DynamicFloatArrayElementInfo();
  43740. lastFree.offset = this.totalElementCount * s;
  43741. this._freeEntries.push(lastFree);
  43742. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43743. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43744. var firstFreeSlotOffset = sortedFree[0].offset;
  43745. var freeZoneSize = 1;
  43746. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43747. var prevOffset = sortedFree[0].offset;
  43748. for (var i = 1; i < sortedFree.length; i++) {
  43749. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  43750. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43751. break;
  43752. }
  43753. var curFree = sortedFree[i];
  43754. var curOffset = curFree.offset;
  43755. // Compute the distance between this offset and the previous
  43756. var distance = curOffset - prevOffset;
  43757. // If the distance is the stride size, they are adjacent, it good, move to the next
  43758. if (distance === s) {
  43759. // Free zone is one element bigger
  43760. ++freeZoneSize;
  43761. // as we're about to iterate to the next, the cur becomes the previous...
  43762. prevOffset = curOffset;
  43763. continue;
  43764. }
  43765. // Distance is bigger, which means there's x element between the previous free and this one
  43766. var usedRange = (distance / s) - 1;
  43767. // Two cases the free zone is smaller than the data to move or bigger
  43768. // Copy what can fit in the free zone
  43769. var curMoveOffset = curOffset - s;
  43770. var copyCount = Math.min(freeZoneSize, usedRange);
  43771. for (var j = 0; j < copyCount; j++) {
  43772. var freeI = firstFreeSlotOffset / s;
  43773. var curI = curMoveOffset / s;
  43774. var moveEl = sortedAll[curI];
  43775. this._moveElement(moveEl, firstFreeSlotOffset);
  43776. var replacedEl = sortedAll[freeI];
  43777. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43778. replacedEl.offset = curMoveOffset;
  43779. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43780. sortedAll[freeI] = moveEl;
  43781. sortedAll[curI] = replacedEl;
  43782. curMoveOffset -= s;
  43783. firstFreeSlotOffset += s;
  43784. }
  43785. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43786. if (freeZoneSize <= usedRange) {
  43787. firstFreeSlotOffset = curMoveOffset + s;
  43788. freeZoneSize = 1 + copyCount;
  43789. }
  43790. else {
  43791. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43792. }
  43793. // as we're about to iterate to the next, the cur becomes the previous...
  43794. prevOffset = curOffset;
  43795. }
  43796. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43797. this._lastUsed = firstFreeSlotOffset - s;
  43798. this._firstFree = firstFreeSlotOffset;
  43799. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43800. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43801. this._allEntries = sortedAll;
  43802. return elementsBuffer;
  43803. };
  43804. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43805. for (var i = 0; i < this._stride; i++) {
  43806. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43807. }
  43808. element.offset = destOffset;
  43809. };
  43810. DynamicFloatArray.prototype._growBuffer = function () {
  43811. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43812. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43813. var newBuffer = new Float32Array(newElCount * this._stride);
  43814. newBuffer.set(this.buffer);
  43815. var curCount = this.totalElementCount;
  43816. var addedCount = newElCount - this.totalElementCount;
  43817. for (var i = 0; i < addedCount; i++) {
  43818. var element = new DynamicFloatArrayElementInfo();
  43819. element.offset = (curCount + i) * this.stride;
  43820. this._allEntries.push(element);
  43821. this._freeEntries[addedCount - i - 1] = element;
  43822. }
  43823. this._firstFree = curCount * this.stride;
  43824. this.buffer = newBuffer;
  43825. };
  43826. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43827. /**
  43828. * Get the total count of entries that can fit in the current buffer
  43829. * @returns the elements count
  43830. */
  43831. get: function () {
  43832. return this._allEntries.length;
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43838. /**
  43839. * Get the count of free entries that can still be allocated without resizing the buffer
  43840. * @returns the free elements count
  43841. */
  43842. get: function () {
  43843. return this._freeEntries.length;
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43849. /**
  43850. * Get the count of allocated elements
  43851. * @returns the allocated elements count
  43852. */
  43853. get: function () {
  43854. return this._allEntries.length - this._freeEntries.length;
  43855. },
  43856. enumerable: true,
  43857. configurable: true
  43858. });
  43859. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43860. /**
  43861. * Return the size of one element in float
  43862. * @returns the size in float
  43863. */
  43864. get: function () {
  43865. return this._stride;
  43866. },
  43867. enumerable: true,
  43868. configurable: true
  43869. });
  43870. DynamicFloatArray.prototype.sort = function () {
  43871. var _this = this;
  43872. if (!this.compareValueOffset) {
  43873. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43874. }
  43875. var count = this.usedElementCount;
  43876. // Do we have to (re)create the sort table?
  43877. if (!this._sortTable || this._sortTable.length < count) {
  43878. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  43879. var newCount = Math.min(this.totalElementCount, count * 2);
  43880. this._sortTable = new Array(newCount);
  43881. }
  43882. if (!this._sortedTable || this._sortedTable.length !== count) {
  43883. this._sortedTable = new Array(count);
  43884. }
  43885. // Because, you know...
  43886. this.pack();
  43887. //let stride = this.stride;
  43888. //for (let i = 0; i < count; i++) {
  43889. // let si = this._sortTable[i];
  43890. // if (!si) {
  43891. // si = new SortInfo();
  43892. // this._sortTable[i] = si;
  43893. // }
  43894. // si.entry = this._allEntries[i];
  43895. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43896. // si.swapedOffset = null;
  43897. // this._sortedTable[i] = si;
  43898. //}
  43899. var curOffset = 0;
  43900. var stride = this.stride;
  43901. for (var i = 0; i < count; i++, curOffset += stride) {
  43902. var si = this._sortTable[i];
  43903. if (!si) {
  43904. si = new SortInfo();
  43905. this._sortTable[i] = si;
  43906. }
  43907. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43908. si.offset = curOffset;
  43909. si.swapedOffset = null;
  43910. this._sortedTable[i] = si;
  43911. }
  43912. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43913. if (this.sortingAscending) {
  43914. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43915. }
  43916. else {
  43917. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43918. }
  43919. var swapElements = function (src, dst) {
  43920. for (var i = 0; i < stride; i++) {
  43921. var tps = _this.buffer[dst + i];
  43922. _this.buffer[dst + i] = _this.buffer[src + i];
  43923. _this.buffer[src + i] = tps;
  43924. }
  43925. };
  43926. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  43927. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  43928. // and I still want something with a good algorithm complexity.
  43929. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  43930. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43931. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43932. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  43933. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43934. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  43935. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43936. for (var i = 0; i < count; i++) {
  43937. // Get the element to move
  43938. var sourceSI = this._sortedTable[i];
  43939. var destSI = this._sortTable[i];
  43940. var sourceOff = sourceSI.offset;
  43941. // If the source changed location, find the new one
  43942. if (sourceSI.swapedOffset) {
  43943. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43944. var curSI = sourceSI;
  43945. while (curSI.swapedOffset) {
  43946. curSI = this._sortTable[curSI.swapedOffset / stride];
  43947. }
  43948. // Finally get the right location
  43949. sourceOff = curSI.offset;
  43950. }
  43951. // Tag the element being replaced with its new location
  43952. destSI.swapedOffset = sourceOff;
  43953. // Swap elements (only if needed)
  43954. if (sourceOff !== destSI.offset) {
  43955. swapElements(sourceOff, destSI.offset);
  43956. }
  43957. // Update the offset in the corresponding DFAE
  43958. //sourceSI.entry.offset = destSI.entry.offset;
  43959. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43960. }
  43961. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43962. return true;
  43963. };
  43964. return DynamicFloatArray;
  43965. }());
  43966. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43967. var SortInfo = (function () {
  43968. function SortInfo() {
  43969. this.compareData = this.offset = this.swapedOffset = null;
  43970. }
  43971. return SortInfo;
  43972. }());
  43973. })(BABYLON || (BABYLON = {}));
  43974. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43975. var BABYLON;
  43976. (function (BABYLON) {
  43977. var Condition = (function () {
  43978. function Condition(actionManager) {
  43979. this._actionManager = actionManager;
  43980. }
  43981. Condition.prototype.isValid = function () {
  43982. return true;
  43983. };
  43984. Condition.prototype._getProperty = function (propertyPath) {
  43985. return this._actionManager._getProperty(propertyPath);
  43986. };
  43987. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43988. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43989. };
  43990. Condition.prototype.serialize = function () {
  43991. };
  43992. Condition.prototype._serialize = function (serializedCondition) {
  43993. return {
  43994. type: 2,
  43995. children: [],
  43996. name: serializedCondition.name,
  43997. properties: serializedCondition.properties
  43998. };
  43999. };
  44000. return Condition;
  44001. }());
  44002. BABYLON.Condition = Condition;
  44003. var ValueCondition = (function (_super) {
  44004. __extends(ValueCondition, _super);
  44005. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44006. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44007. var _this = _super.call(this, actionManager) || this;
  44008. _this.propertyPath = propertyPath;
  44009. _this.value = value;
  44010. _this.operator = operator;
  44011. _this._target = target;
  44012. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44013. _this._property = _this._getProperty(_this.propertyPath);
  44014. return _this;
  44015. }
  44016. Object.defineProperty(ValueCondition, "IsEqual", {
  44017. get: function () {
  44018. return ValueCondition._IsEqual;
  44019. },
  44020. enumerable: true,
  44021. configurable: true
  44022. });
  44023. Object.defineProperty(ValueCondition, "IsDifferent", {
  44024. get: function () {
  44025. return ValueCondition._IsDifferent;
  44026. },
  44027. enumerable: true,
  44028. configurable: true
  44029. });
  44030. Object.defineProperty(ValueCondition, "IsGreater", {
  44031. get: function () {
  44032. return ValueCondition._IsGreater;
  44033. },
  44034. enumerable: true,
  44035. configurable: true
  44036. });
  44037. Object.defineProperty(ValueCondition, "IsLesser", {
  44038. get: function () {
  44039. return ValueCondition._IsLesser;
  44040. },
  44041. enumerable: true,
  44042. configurable: true
  44043. });
  44044. // Methods
  44045. ValueCondition.prototype.isValid = function () {
  44046. switch (this.operator) {
  44047. case ValueCondition.IsGreater:
  44048. return this._effectiveTarget[this._property] > this.value;
  44049. case ValueCondition.IsLesser:
  44050. return this._effectiveTarget[this._property] < this.value;
  44051. case ValueCondition.IsEqual:
  44052. case ValueCondition.IsDifferent:
  44053. var check;
  44054. if (this.value.equals) {
  44055. check = this.value.equals(this._effectiveTarget[this._property]);
  44056. }
  44057. else {
  44058. check = this.value === this._effectiveTarget[this._property];
  44059. }
  44060. return this.operator === ValueCondition.IsEqual ? check : !check;
  44061. }
  44062. return false;
  44063. };
  44064. ValueCondition.prototype.serialize = function () {
  44065. return this._serialize({
  44066. name: "ValueCondition",
  44067. properties: [
  44068. BABYLON.Action._GetTargetProperty(this._target),
  44069. { name: "propertyPath", value: this.propertyPath },
  44070. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44071. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44072. ]
  44073. });
  44074. };
  44075. ValueCondition.GetOperatorName = function (operator) {
  44076. switch (operator) {
  44077. case ValueCondition._IsEqual: return "IsEqual";
  44078. case ValueCondition._IsDifferent: return "IsDifferent";
  44079. case ValueCondition._IsGreater: return "IsGreater";
  44080. case ValueCondition._IsLesser: return "IsLesser";
  44081. default: return "";
  44082. }
  44083. };
  44084. return ValueCondition;
  44085. }(Condition));
  44086. // Statics
  44087. ValueCondition._IsEqual = 0;
  44088. ValueCondition._IsDifferent = 1;
  44089. ValueCondition._IsGreater = 2;
  44090. ValueCondition._IsLesser = 3;
  44091. BABYLON.ValueCondition = ValueCondition;
  44092. var PredicateCondition = (function (_super) {
  44093. __extends(PredicateCondition, _super);
  44094. function PredicateCondition(actionManager, predicate) {
  44095. var _this = _super.call(this, actionManager) || this;
  44096. _this.predicate = predicate;
  44097. return _this;
  44098. }
  44099. PredicateCondition.prototype.isValid = function () {
  44100. return this.predicate();
  44101. };
  44102. return PredicateCondition;
  44103. }(Condition));
  44104. BABYLON.PredicateCondition = PredicateCondition;
  44105. var StateCondition = (function (_super) {
  44106. __extends(StateCondition, _super);
  44107. function StateCondition(actionManager, target, value) {
  44108. var _this = _super.call(this, actionManager) || this;
  44109. _this.value = value;
  44110. _this._target = target;
  44111. return _this;
  44112. }
  44113. // Methods
  44114. StateCondition.prototype.isValid = function () {
  44115. return this._target.state === this.value;
  44116. };
  44117. StateCondition.prototype.serialize = function () {
  44118. return this._serialize({
  44119. name: "StateCondition",
  44120. properties: [
  44121. BABYLON.Action._GetTargetProperty(this._target),
  44122. { name: "value", value: this.value }
  44123. ]
  44124. });
  44125. };
  44126. return StateCondition;
  44127. }(Condition));
  44128. BABYLON.StateCondition = StateCondition;
  44129. })(BABYLON || (BABYLON = {}));
  44130. //# sourceMappingURL=babylon.condition.js.map
  44131. var BABYLON;
  44132. (function (BABYLON) {
  44133. var Action = (function () {
  44134. function Action(triggerOptions, condition) {
  44135. this.triggerOptions = triggerOptions;
  44136. if (triggerOptions.parameter) {
  44137. this.trigger = triggerOptions.trigger;
  44138. this._triggerParameter = triggerOptions.parameter;
  44139. }
  44140. else {
  44141. this.trigger = triggerOptions;
  44142. }
  44143. this._nextActiveAction = this;
  44144. this._condition = condition;
  44145. }
  44146. // Methods
  44147. Action.prototype._prepare = function () {
  44148. };
  44149. Action.prototype.getTriggerParameter = function () {
  44150. return this._triggerParameter;
  44151. };
  44152. Action.prototype._executeCurrent = function (evt) {
  44153. if (this._nextActiveAction._condition) {
  44154. var condition = this._nextActiveAction._condition;
  44155. var currentRenderId = this._actionManager.getScene().getRenderId();
  44156. // We cache the current evaluation for the current frame
  44157. if (condition._evaluationId === currentRenderId) {
  44158. if (!condition._currentResult) {
  44159. return;
  44160. }
  44161. }
  44162. else {
  44163. condition._evaluationId = currentRenderId;
  44164. if (!condition.isValid()) {
  44165. condition._currentResult = false;
  44166. return;
  44167. }
  44168. condition._currentResult = true;
  44169. }
  44170. }
  44171. this._nextActiveAction.execute(evt);
  44172. this.skipToNextActiveAction();
  44173. };
  44174. Action.prototype.execute = function (evt) {
  44175. };
  44176. Action.prototype.skipToNextActiveAction = function () {
  44177. if (this._nextActiveAction._child) {
  44178. if (!this._nextActiveAction._child._actionManager) {
  44179. this._nextActiveAction._child._actionManager = this._actionManager;
  44180. }
  44181. this._nextActiveAction = this._nextActiveAction._child;
  44182. }
  44183. else {
  44184. this._nextActiveAction = this;
  44185. }
  44186. };
  44187. Action.prototype.then = function (action) {
  44188. this._child = action;
  44189. action._actionManager = this._actionManager;
  44190. action._prepare();
  44191. return action;
  44192. };
  44193. Action.prototype._getProperty = function (propertyPath) {
  44194. return this._actionManager._getProperty(propertyPath);
  44195. };
  44196. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44197. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44198. };
  44199. Action.prototype.serialize = function (parent) {
  44200. };
  44201. // Called by BABYLON.Action objects in serialize(...). Internal use
  44202. Action.prototype._serialize = function (serializedAction, parent) {
  44203. var serializationObject = {
  44204. type: 1,
  44205. children: [],
  44206. name: serializedAction.name,
  44207. properties: serializedAction.properties || []
  44208. };
  44209. // Serialize child
  44210. if (this._child) {
  44211. this._child.serialize(serializationObject);
  44212. }
  44213. // Check if "this" has a condition
  44214. if (this._condition) {
  44215. var serializedCondition = this._condition.serialize();
  44216. serializedCondition.children.push(serializationObject);
  44217. if (parent) {
  44218. parent.children.push(serializedCondition);
  44219. }
  44220. return serializedCondition;
  44221. }
  44222. if (parent) {
  44223. parent.children.push(serializationObject);
  44224. }
  44225. return serializationObject;
  44226. };
  44227. return Action;
  44228. }());
  44229. Action._SerializeValueAsString = function (value) {
  44230. if (typeof value === "number") {
  44231. return value.toString();
  44232. }
  44233. if (typeof value === "boolean") {
  44234. return value ? "true" : "false";
  44235. }
  44236. if (value instanceof BABYLON.Vector2) {
  44237. return value.x + ", " + value.y;
  44238. }
  44239. if (value instanceof BABYLON.Vector3) {
  44240. return value.x + ", " + value.y + ", " + value.z;
  44241. }
  44242. if (value instanceof BABYLON.Color3) {
  44243. return value.r + ", " + value.g + ", " + value.b;
  44244. }
  44245. if (value instanceof BABYLON.Color4) {
  44246. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44247. }
  44248. return value; // string
  44249. };
  44250. Action._GetTargetProperty = function (target) {
  44251. return {
  44252. name: "target",
  44253. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44254. : target instanceof BABYLON.Light ? "LightProperties"
  44255. : target instanceof BABYLON.Camera ? "CameraProperties"
  44256. : "SceneProperties",
  44257. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44258. };
  44259. };
  44260. BABYLON.Action = Action;
  44261. })(BABYLON || (BABYLON = {}));
  44262. //# sourceMappingURL=babylon.action.js.map
  44263. var BABYLON;
  44264. (function (BABYLON) {
  44265. /**
  44266. * ActionEvent is the event beint sent when an action is triggered.
  44267. */
  44268. var ActionEvent = (function () {
  44269. /**
  44270. * @constructor
  44271. * @param source The mesh or sprite that triggered the action.
  44272. * @param pointerX The X mouse cursor position at the time of the event
  44273. * @param pointerY The Y mouse cursor position at the time of the event
  44274. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44275. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44276. */
  44277. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44278. this.source = source;
  44279. this.pointerX = pointerX;
  44280. this.pointerY = pointerY;
  44281. this.meshUnderPointer = meshUnderPointer;
  44282. this.sourceEvent = sourceEvent;
  44283. this.additionalData = additionalData;
  44284. }
  44285. /**
  44286. * Helper function to auto-create an ActionEvent from a source mesh.
  44287. * @param source The source mesh that triggered the event
  44288. * @param evt {Event} The original (browser) event
  44289. */
  44290. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44291. var scene = source.getScene();
  44292. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44293. };
  44294. /**
  44295. * Helper function to auto-create an ActionEvent from a source mesh.
  44296. * @param source The source sprite that triggered the event
  44297. * @param scene Scene associated with the sprite
  44298. * @param evt {Event} The original (browser) event
  44299. */
  44300. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44301. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44302. };
  44303. /**
  44304. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44305. * @param scene the scene where the event occurred
  44306. * @param evt {Event} The original (browser) event
  44307. */
  44308. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44309. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44310. };
  44311. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44312. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44313. };
  44314. return ActionEvent;
  44315. }());
  44316. BABYLON.ActionEvent = ActionEvent;
  44317. /**
  44318. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44319. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44320. */
  44321. var ActionManager = (function () {
  44322. function ActionManager(scene) {
  44323. // Members
  44324. this.actions = new Array();
  44325. this.hoverCursor = '';
  44326. this._scene = scene;
  44327. scene._actionManagers.push(this);
  44328. }
  44329. Object.defineProperty(ActionManager, "NothingTrigger", {
  44330. get: function () {
  44331. return ActionManager._NothingTrigger;
  44332. },
  44333. enumerable: true,
  44334. configurable: true
  44335. });
  44336. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44337. get: function () {
  44338. return ActionManager._OnPickTrigger;
  44339. },
  44340. enumerable: true,
  44341. configurable: true
  44342. });
  44343. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44344. get: function () {
  44345. return ActionManager._OnLeftPickTrigger;
  44346. },
  44347. enumerable: true,
  44348. configurable: true
  44349. });
  44350. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44351. get: function () {
  44352. return ActionManager._OnRightPickTrigger;
  44353. },
  44354. enumerable: true,
  44355. configurable: true
  44356. });
  44357. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44358. get: function () {
  44359. return ActionManager._OnCenterPickTrigger;
  44360. },
  44361. enumerable: true,
  44362. configurable: true
  44363. });
  44364. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44365. get: function () {
  44366. return ActionManager._OnPickDownTrigger;
  44367. },
  44368. enumerable: true,
  44369. configurable: true
  44370. });
  44371. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44372. get: function () {
  44373. return ActionManager._OnDoublePickTrigger;
  44374. },
  44375. enumerable: true,
  44376. configurable: true
  44377. });
  44378. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44379. get: function () {
  44380. return ActionManager._OnPickUpTrigger;
  44381. },
  44382. enumerable: true,
  44383. configurable: true
  44384. });
  44385. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  44386. /// This trigger will only be raised if you also declared a OnPickDown
  44387. get: function () {
  44388. return ActionManager._OnPickOutTrigger;
  44389. },
  44390. enumerable: true,
  44391. configurable: true
  44392. });
  44393. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  44394. get: function () {
  44395. return ActionManager._OnLongPressTrigger;
  44396. },
  44397. enumerable: true,
  44398. configurable: true
  44399. });
  44400. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  44401. get: function () {
  44402. return ActionManager._OnPointerOverTrigger;
  44403. },
  44404. enumerable: true,
  44405. configurable: true
  44406. });
  44407. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  44408. get: function () {
  44409. return ActionManager._OnPointerOutTrigger;
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  44415. get: function () {
  44416. return ActionManager._OnEveryFrameTrigger;
  44417. },
  44418. enumerable: true,
  44419. configurable: true
  44420. });
  44421. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  44422. get: function () {
  44423. return ActionManager._OnIntersectionEnterTrigger;
  44424. },
  44425. enumerable: true,
  44426. configurable: true
  44427. });
  44428. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  44429. get: function () {
  44430. return ActionManager._OnIntersectionExitTrigger;
  44431. },
  44432. enumerable: true,
  44433. configurable: true
  44434. });
  44435. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  44436. get: function () {
  44437. return ActionManager._OnKeyDownTrigger;
  44438. },
  44439. enumerable: true,
  44440. configurable: true
  44441. });
  44442. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  44443. get: function () {
  44444. return ActionManager._OnKeyUpTrigger;
  44445. },
  44446. enumerable: true,
  44447. configurable: true
  44448. });
  44449. // Methods
  44450. ActionManager.prototype.dispose = function () {
  44451. var index = this._scene._actionManagers.indexOf(this);
  44452. for (var i = 0; i < this.actions.length; i++) {
  44453. var action = this.actions[i];
  44454. ActionManager.Triggers[action.trigger]--;
  44455. if (ActionManager.Triggers[action.trigger] === 0) {
  44456. delete ActionManager.Triggers[action.trigger];
  44457. }
  44458. }
  44459. if (index > -1) {
  44460. this._scene._actionManagers.splice(index, 1);
  44461. }
  44462. };
  44463. ActionManager.prototype.getScene = function () {
  44464. return this._scene;
  44465. };
  44466. /**
  44467. * Does this action manager handles actions of any of the given triggers
  44468. * @param {number[]} triggers - the triggers to be tested
  44469. * @return {boolean} whether one (or more) of the triggers is handeled
  44470. */
  44471. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  44472. for (var index = 0; index < this.actions.length; index++) {
  44473. var action = this.actions[index];
  44474. if (triggers.indexOf(action.trigger) > -1) {
  44475. return true;
  44476. }
  44477. }
  44478. return false;
  44479. };
  44480. /**
  44481. * Does this action manager handles actions of a given trigger
  44482. * @param {number} trigger - the trigger to be tested
  44483. * @return {boolean} whether the trigger is handeled
  44484. */
  44485. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  44486. for (var index = 0; index < this.actions.length; index++) {
  44487. var action = this.actions[index];
  44488. if (action.trigger === trigger) {
  44489. return true;
  44490. }
  44491. }
  44492. return false;
  44493. };
  44494. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  44495. /**
  44496. * Does this action manager has pointer triggers
  44497. * @return {boolean} whether or not it has pointer triggers
  44498. */
  44499. get: function () {
  44500. for (var index = 0; index < this.actions.length; index++) {
  44501. var action = this.actions[index];
  44502. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  44503. return true;
  44504. }
  44505. }
  44506. return false;
  44507. },
  44508. enumerable: true,
  44509. configurable: true
  44510. });
  44511. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  44512. /**
  44513. * Does this action manager has pick triggers
  44514. * @return {boolean} whether or not it has pick triggers
  44515. */
  44516. get: function () {
  44517. for (var index = 0; index < this.actions.length; index++) {
  44518. var action = this.actions[index];
  44519. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  44520. return true;
  44521. }
  44522. }
  44523. return false;
  44524. },
  44525. enumerable: true,
  44526. configurable: true
  44527. });
  44528. Object.defineProperty(ActionManager, "HasTriggers", {
  44529. /**
  44530. * Does exist one action manager with at least one trigger
  44531. * @return {boolean} whether or not it exists one action manager with one trigger
  44532. **/
  44533. get: function () {
  44534. for (var t in ActionManager.Triggers) {
  44535. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44536. return true;
  44537. }
  44538. }
  44539. return false;
  44540. },
  44541. enumerable: true,
  44542. configurable: true
  44543. });
  44544. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44545. /**
  44546. * Does exist one action manager with at least one pick trigger
  44547. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44548. **/
  44549. get: function () {
  44550. for (var t in ActionManager.Triggers) {
  44551. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44552. var t_int = parseInt(t);
  44553. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44554. return true;
  44555. }
  44556. }
  44557. }
  44558. return false;
  44559. },
  44560. enumerable: true,
  44561. configurable: true
  44562. });
  44563. /**
  44564. * Does exist one action manager that handles actions of a given trigger
  44565. * @param {number} trigger - the trigger to be tested
  44566. * @return {boolean} whether the trigger is handeled by at least one action manager
  44567. **/
  44568. ActionManager.HasSpecificTrigger = function (trigger) {
  44569. for (var t in ActionManager.Triggers) {
  44570. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44571. var t_int = parseInt(t);
  44572. if (t_int === trigger) {
  44573. return true;
  44574. }
  44575. }
  44576. }
  44577. return false;
  44578. };
  44579. /**
  44580. * Registers an action to this action manager
  44581. * @param {BABYLON.Action} action - the action to be registered
  44582. * @return {BABYLON.Action} the action amended (prepared) after registration
  44583. */
  44584. ActionManager.prototype.registerAction = function (action) {
  44585. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44586. if (this.getScene().actionManager !== this) {
  44587. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44588. return null;
  44589. }
  44590. }
  44591. this.actions.push(action);
  44592. if (ActionManager.Triggers[action.trigger]) {
  44593. ActionManager.Triggers[action.trigger]++;
  44594. }
  44595. else {
  44596. ActionManager.Triggers[action.trigger] = 1;
  44597. }
  44598. action._actionManager = this;
  44599. action._prepare();
  44600. return action;
  44601. };
  44602. /**
  44603. * Process a specific trigger
  44604. * @param {number} trigger - the trigger to process
  44605. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44606. */
  44607. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44608. for (var index = 0; index < this.actions.length; index++) {
  44609. var action = this.actions[index];
  44610. if (action.trigger === trigger) {
  44611. if (trigger === ActionManager.OnKeyUpTrigger
  44612. || trigger === ActionManager.OnKeyDownTrigger) {
  44613. var parameter = action.getTriggerParameter();
  44614. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44615. if (!parameter.toLowerCase) {
  44616. continue;
  44617. }
  44618. var lowerCase = parameter.toLowerCase();
  44619. if (lowerCase !== evt.sourceEvent.key) {
  44620. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44621. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44622. if (actualkey !== lowerCase) {
  44623. continue;
  44624. }
  44625. }
  44626. }
  44627. }
  44628. action._executeCurrent(evt);
  44629. }
  44630. }
  44631. };
  44632. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44633. var properties = propertyPath.split(".");
  44634. for (var index = 0; index < properties.length - 1; index++) {
  44635. target = target[properties[index]];
  44636. }
  44637. return target;
  44638. };
  44639. ActionManager.prototype._getProperty = function (propertyPath) {
  44640. var properties = propertyPath.split(".");
  44641. return properties[properties.length - 1];
  44642. };
  44643. ActionManager.prototype.serialize = function (name) {
  44644. var root = {
  44645. children: [],
  44646. name: name,
  44647. type: 3,
  44648. properties: [] // Empty for root but required
  44649. };
  44650. for (var i = 0; i < this.actions.length; i++) {
  44651. var triggerObject = {
  44652. type: 0,
  44653. children: [],
  44654. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44655. properties: []
  44656. };
  44657. var triggerOptions = this.actions[i].triggerOptions;
  44658. if (triggerOptions && typeof triggerOptions !== "number") {
  44659. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44660. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44661. }
  44662. else {
  44663. var parameter = {};
  44664. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44665. if (triggerOptions.parameter.mesh) {
  44666. parameter._meshId = triggerOptions.parameter.mesh.id;
  44667. }
  44668. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44669. }
  44670. }
  44671. // Serialize child action, recursively
  44672. this.actions[i].serialize(triggerObject);
  44673. // Add serialized trigger
  44674. root.children.push(triggerObject);
  44675. }
  44676. return root;
  44677. };
  44678. ActionManager.Parse = function (parsedActions, object, scene) {
  44679. var actionManager = new BABYLON.ActionManager(scene);
  44680. if (object === null)
  44681. scene.actionManager = actionManager;
  44682. else
  44683. object.actionManager = actionManager;
  44684. // instanciate a new object
  44685. var instanciate = function (name, params) {
  44686. var newInstance = Object.create(BABYLON[name].prototype);
  44687. newInstance.constructor.apply(newInstance, params);
  44688. return newInstance;
  44689. };
  44690. var parseParameter = function (name, value, target, propertyPath) {
  44691. if (propertyPath === null) {
  44692. // String, boolean or float
  44693. var floatValue = parseFloat(value);
  44694. if (value === "true" || value === "false")
  44695. return value === "true";
  44696. else
  44697. return isNaN(floatValue) ? value : floatValue;
  44698. }
  44699. var effectiveTarget = propertyPath.split(".");
  44700. var values = value.split(",");
  44701. // Get effective Target
  44702. for (var i = 0; i < effectiveTarget.length; i++) {
  44703. target = target[effectiveTarget[i]];
  44704. }
  44705. // Return appropriate value with its type
  44706. if (typeof (target) === "boolean")
  44707. return values[0] === "true";
  44708. if (typeof (target) === "string")
  44709. return values[0];
  44710. // Parameters with multiple values such as Vector3 etc.
  44711. var split = new Array();
  44712. for (var i = 0; i < values.length; i++)
  44713. split.push(parseFloat(values[i]));
  44714. if (target instanceof BABYLON.Vector3)
  44715. return BABYLON.Vector3.FromArray(split);
  44716. if (target instanceof BABYLON.Vector4)
  44717. return BABYLON.Vector4.FromArray(split);
  44718. if (target instanceof BABYLON.Color3)
  44719. return BABYLON.Color3.FromArray(split);
  44720. if (target instanceof BABYLON.Color4)
  44721. return BABYLON.Color4.FromArray(split);
  44722. return parseFloat(values[0]);
  44723. };
  44724. // traverse graph per trigger
  44725. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44726. if (combineArray === void 0) { combineArray = null; }
  44727. if (parsedAction.detached)
  44728. return;
  44729. var parameters = new Array();
  44730. var target = null;
  44731. var propertyPath = null;
  44732. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44733. // Parameters
  44734. if (parsedAction.type === 2)
  44735. parameters.push(actionManager);
  44736. else
  44737. parameters.push(trigger);
  44738. if (combine) {
  44739. var actions = new Array();
  44740. for (var j = 0; j < parsedAction.combine.length; j++) {
  44741. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44742. }
  44743. parameters.push(actions);
  44744. }
  44745. else {
  44746. for (var i = 0; i < parsedAction.properties.length; i++) {
  44747. var value = parsedAction.properties[i].value;
  44748. var name = parsedAction.properties[i].name;
  44749. var targetType = parsedAction.properties[i].targetType;
  44750. if (name === "target")
  44751. if (targetType !== null && targetType === "SceneProperties")
  44752. value = target = scene;
  44753. else
  44754. value = target = scene.getNodeByName(value);
  44755. else if (name === "parent")
  44756. value = scene.getNodeByName(value);
  44757. else if (name === "sound")
  44758. value = scene.getSoundByName(value);
  44759. else if (name !== "propertyPath") {
  44760. if (parsedAction.type === 2 && name === "operator")
  44761. value = BABYLON.ValueCondition[value];
  44762. else
  44763. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44764. }
  44765. else {
  44766. propertyPath = value;
  44767. }
  44768. parameters.push(value);
  44769. }
  44770. }
  44771. if (combineArray === null) {
  44772. parameters.push(condition);
  44773. }
  44774. else {
  44775. parameters.push(null);
  44776. }
  44777. // If interpolate value action
  44778. if (parsedAction.name === "InterpolateValueAction") {
  44779. var param = parameters[parameters.length - 2];
  44780. parameters[parameters.length - 1] = param;
  44781. parameters[parameters.length - 2] = condition;
  44782. }
  44783. // Action or condition(s) and not CombineAction
  44784. var newAction = instanciate(parsedAction.name, parameters);
  44785. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44786. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44787. if (action)
  44788. action.then(nothing);
  44789. else
  44790. actionManager.registerAction(nothing);
  44791. action = nothing;
  44792. }
  44793. if (combineArray === null) {
  44794. if (newAction instanceof BABYLON.Condition) {
  44795. condition = newAction;
  44796. newAction = action;
  44797. }
  44798. else {
  44799. condition = null;
  44800. if (action)
  44801. action.then(newAction);
  44802. else
  44803. actionManager.registerAction(newAction);
  44804. }
  44805. }
  44806. else {
  44807. combineArray.push(newAction);
  44808. }
  44809. for (var i = 0; i < parsedAction.children.length; i++)
  44810. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44811. };
  44812. // triggers
  44813. for (var i = 0; i < parsedActions.children.length; i++) {
  44814. var triggerParams;
  44815. var trigger = parsedActions.children[i];
  44816. if (trigger.properties.length > 0) {
  44817. var param = trigger.properties[0].value;
  44818. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44819. if (value._meshId) {
  44820. value.mesh = scene.getMeshByID(value._meshId);
  44821. }
  44822. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  44823. }
  44824. else
  44825. triggerParams = BABYLON.ActionManager[trigger.name];
  44826. for (var j = 0; j < trigger.children.length; j++) {
  44827. if (!trigger.detached)
  44828. traverse(trigger.children[j], triggerParams, null, null);
  44829. }
  44830. }
  44831. };
  44832. ActionManager.GetTriggerName = function (trigger) {
  44833. switch (trigger) {
  44834. case 0: return "NothingTrigger";
  44835. case 1: return "OnPickTrigger";
  44836. case 2: return "OnLeftPickTrigger";
  44837. case 3: return "OnRightPickTrigger";
  44838. case 4: return "OnCenterPickTrigger";
  44839. case 5: return "OnPickDownTrigger";
  44840. case 6: return "OnPickUpTrigger";
  44841. case 7: return "OnLongPressTrigger";
  44842. case 8: return "OnPointerOverTrigger";
  44843. case 9: return "OnPointerOutTrigger";
  44844. case 10: return "OnEveryFrameTrigger";
  44845. case 11: return "OnIntersectionEnterTrigger";
  44846. case 12: return "OnIntersectionExitTrigger";
  44847. case 13: return "OnKeyDownTrigger";
  44848. case 14: return "OnKeyUpTrigger";
  44849. case 15: return "OnPickOutTrigger";
  44850. default: return "";
  44851. }
  44852. };
  44853. return ActionManager;
  44854. }());
  44855. // Statics
  44856. ActionManager._NothingTrigger = 0;
  44857. ActionManager._OnPickTrigger = 1;
  44858. ActionManager._OnLeftPickTrigger = 2;
  44859. ActionManager._OnRightPickTrigger = 3;
  44860. ActionManager._OnCenterPickTrigger = 4;
  44861. ActionManager._OnPickDownTrigger = 5;
  44862. ActionManager._OnDoublePickTrigger = 6;
  44863. ActionManager._OnPickUpTrigger = 7;
  44864. ActionManager._OnLongPressTrigger = 8;
  44865. ActionManager._OnPointerOverTrigger = 9;
  44866. ActionManager._OnPointerOutTrigger = 10;
  44867. ActionManager._OnEveryFrameTrigger = 11;
  44868. ActionManager._OnIntersectionEnterTrigger = 12;
  44869. ActionManager._OnIntersectionExitTrigger = 13;
  44870. ActionManager._OnKeyDownTrigger = 14;
  44871. ActionManager._OnKeyUpTrigger = 15;
  44872. ActionManager._OnPickOutTrigger = 16;
  44873. ActionManager.Triggers = {};
  44874. BABYLON.ActionManager = ActionManager;
  44875. })(BABYLON || (BABYLON = {}));
  44876. //# sourceMappingURL=babylon.actionManager.js.map
  44877. var BABYLON;
  44878. (function (BABYLON) {
  44879. var InterpolateValueAction = (function (_super) {
  44880. __extends(InterpolateValueAction, _super);
  44881. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44882. if (duration === void 0) { duration = 1000; }
  44883. var _this = _super.call(this, triggerOptions, condition) || this;
  44884. _this.propertyPath = propertyPath;
  44885. _this.value = value;
  44886. _this.duration = duration;
  44887. _this.stopOtherAnimations = stopOtherAnimations;
  44888. _this.onInterpolationDone = onInterpolationDone;
  44889. _this._target = _this._effectiveTarget = target;
  44890. return _this;
  44891. }
  44892. InterpolateValueAction.prototype._prepare = function () {
  44893. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44894. this._property = this._getProperty(this.propertyPath);
  44895. };
  44896. InterpolateValueAction.prototype.execute = function () {
  44897. var scene = this._actionManager.getScene();
  44898. var keys = [
  44899. {
  44900. frame: 0,
  44901. value: this._effectiveTarget[this._property]
  44902. }, {
  44903. frame: 100,
  44904. value: this.value
  44905. }
  44906. ];
  44907. var dataType;
  44908. if (typeof this.value === "number") {
  44909. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44910. }
  44911. else if (this.value instanceof BABYLON.Color3) {
  44912. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44913. }
  44914. else if (this.value instanceof BABYLON.Vector3) {
  44915. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44916. }
  44917. else if (this.value instanceof BABYLON.Matrix) {
  44918. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44919. }
  44920. else if (this.value instanceof BABYLON.Quaternion) {
  44921. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44922. }
  44923. else {
  44924. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44925. return;
  44926. }
  44927. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44928. animation.setKeys(keys);
  44929. if (this.stopOtherAnimations) {
  44930. scene.stopAnimation(this._effectiveTarget);
  44931. }
  44932. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  44933. };
  44934. InterpolateValueAction.prototype.serialize = function (parent) {
  44935. return _super.prototype._serialize.call(this, {
  44936. name: "InterpolateValueAction",
  44937. properties: [
  44938. BABYLON.Action._GetTargetProperty(this._target),
  44939. { name: "propertyPath", value: this.propertyPath },
  44940. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44941. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44942. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44943. ]
  44944. }, parent);
  44945. };
  44946. return InterpolateValueAction;
  44947. }(BABYLON.Action));
  44948. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44949. })(BABYLON || (BABYLON = {}));
  44950. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44951. var BABYLON;
  44952. (function (BABYLON) {
  44953. var SwitchBooleanAction = (function (_super) {
  44954. __extends(SwitchBooleanAction, _super);
  44955. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44956. var _this = _super.call(this, triggerOptions, condition) || this;
  44957. _this.propertyPath = propertyPath;
  44958. _this._target = _this._effectiveTarget = target;
  44959. return _this;
  44960. }
  44961. SwitchBooleanAction.prototype._prepare = function () {
  44962. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44963. this._property = this._getProperty(this.propertyPath);
  44964. };
  44965. SwitchBooleanAction.prototype.execute = function () {
  44966. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44967. };
  44968. SwitchBooleanAction.prototype.serialize = function (parent) {
  44969. return _super.prototype._serialize.call(this, {
  44970. name: "SwitchBooleanAction",
  44971. properties: [
  44972. BABYLON.Action._GetTargetProperty(this._target),
  44973. { name: "propertyPath", value: this.propertyPath }
  44974. ]
  44975. }, parent);
  44976. };
  44977. return SwitchBooleanAction;
  44978. }(BABYLON.Action));
  44979. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44980. var SetStateAction = (function (_super) {
  44981. __extends(SetStateAction, _super);
  44982. function SetStateAction(triggerOptions, target, value, condition) {
  44983. var _this = _super.call(this, triggerOptions, condition) || this;
  44984. _this.value = value;
  44985. _this._target = target;
  44986. return _this;
  44987. }
  44988. SetStateAction.prototype.execute = function () {
  44989. this._target.state = this.value;
  44990. };
  44991. SetStateAction.prototype.serialize = function (parent) {
  44992. return _super.prototype._serialize.call(this, {
  44993. name: "SetStateAction",
  44994. properties: [
  44995. BABYLON.Action._GetTargetProperty(this._target),
  44996. { name: "value", value: this.value }
  44997. ]
  44998. }, parent);
  44999. };
  45000. return SetStateAction;
  45001. }(BABYLON.Action));
  45002. BABYLON.SetStateAction = SetStateAction;
  45003. var SetValueAction = (function (_super) {
  45004. __extends(SetValueAction, _super);
  45005. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45006. var _this = _super.call(this, triggerOptions, condition) || this;
  45007. _this.propertyPath = propertyPath;
  45008. _this.value = value;
  45009. _this._target = _this._effectiveTarget = target;
  45010. return _this;
  45011. }
  45012. SetValueAction.prototype._prepare = function () {
  45013. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45014. this._property = this._getProperty(this.propertyPath);
  45015. };
  45016. SetValueAction.prototype.execute = function () {
  45017. this._effectiveTarget[this._property] = this.value;
  45018. if (this._target.markAsDirty) {
  45019. this._target.markAsDirty(this._property);
  45020. }
  45021. };
  45022. SetValueAction.prototype.serialize = function (parent) {
  45023. return _super.prototype._serialize.call(this, {
  45024. name: "SetValueAction",
  45025. properties: [
  45026. BABYLON.Action._GetTargetProperty(this._target),
  45027. { name: "propertyPath", value: this.propertyPath },
  45028. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45029. ]
  45030. }, parent);
  45031. };
  45032. return SetValueAction;
  45033. }(BABYLON.Action));
  45034. BABYLON.SetValueAction = SetValueAction;
  45035. var IncrementValueAction = (function (_super) {
  45036. __extends(IncrementValueAction, _super);
  45037. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45038. var _this = _super.call(this, triggerOptions, condition) || this;
  45039. _this.propertyPath = propertyPath;
  45040. _this.value = value;
  45041. _this._target = _this._effectiveTarget = target;
  45042. return _this;
  45043. }
  45044. IncrementValueAction.prototype._prepare = function () {
  45045. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45046. this._property = this._getProperty(this.propertyPath);
  45047. if (typeof this._effectiveTarget[this._property] !== "number") {
  45048. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45049. }
  45050. };
  45051. IncrementValueAction.prototype.execute = function () {
  45052. this._effectiveTarget[this._property] += this.value;
  45053. if (this._target.markAsDirty) {
  45054. this._target.markAsDirty(this._property);
  45055. }
  45056. };
  45057. IncrementValueAction.prototype.serialize = function (parent) {
  45058. return _super.prototype._serialize.call(this, {
  45059. name: "IncrementValueAction",
  45060. properties: [
  45061. BABYLON.Action._GetTargetProperty(this._target),
  45062. { name: "propertyPath", value: this.propertyPath },
  45063. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45064. ]
  45065. }, parent);
  45066. };
  45067. return IncrementValueAction;
  45068. }(BABYLON.Action));
  45069. BABYLON.IncrementValueAction = IncrementValueAction;
  45070. var PlayAnimationAction = (function (_super) {
  45071. __extends(PlayAnimationAction, _super);
  45072. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45073. var _this = _super.call(this, triggerOptions, condition) || this;
  45074. _this.from = from;
  45075. _this.to = to;
  45076. _this.loop = loop;
  45077. _this._target = target;
  45078. return _this;
  45079. }
  45080. PlayAnimationAction.prototype._prepare = function () {
  45081. };
  45082. PlayAnimationAction.prototype.execute = function () {
  45083. var scene = this._actionManager.getScene();
  45084. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45085. };
  45086. PlayAnimationAction.prototype.serialize = function (parent) {
  45087. return _super.prototype._serialize.call(this, {
  45088. name: "PlayAnimationAction",
  45089. properties: [
  45090. BABYLON.Action._GetTargetProperty(this._target),
  45091. { name: "from", value: String(this.from) },
  45092. { name: "to", value: String(this.to) },
  45093. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45094. ]
  45095. }, parent);
  45096. };
  45097. return PlayAnimationAction;
  45098. }(BABYLON.Action));
  45099. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45100. var StopAnimationAction = (function (_super) {
  45101. __extends(StopAnimationAction, _super);
  45102. function StopAnimationAction(triggerOptions, target, condition) {
  45103. var _this = _super.call(this, triggerOptions, condition) || this;
  45104. _this._target = target;
  45105. return _this;
  45106. }
  45107. StopAnimationAction.prototype._prepare = function () {
  45108. };
  45109. StopAnimationAction.prototype.execute = function () {
  45110. var scene = this._actionManager.getScene();
  45111. scene.stopAnimation(this._target);
  45112. };
  45113. StopAnimationAction.prototype.serialize = function (parent) {
  45114. return _super.prototype._serialize.call(this, {
  45115. name: "StopAnimationAction",
  45116. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45117. }, parent);
  45118. };
  45119. return StopAnimationAction;
  45120. }(BABYLON.Action));
  45121. BABYLON.StopAnimationAction = StopAnimationAction;
  45122. var DoNothingAction = (function (_super) {
  45123. __extends(DoNothingAction, _super);
  45124. function DoNothingAction(triggerOptions, condition) {
  45125. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45126. return _super.call(this, triggerOptions, condition) || this;
  45127. }
  45128. DoNothingAction.prototype.execute = function () {
  45129. };
  45130. DoNothingAction.prototype.serialize = function (parent) {
  45131. return _super.prototype._serialize.call(this, {
  45132. name: "DoNothingAction",
  45133. properties: []
  45134. }, parent);
  45135. };
  45136. return DoNothingAction;
  45137. }(BABYLON.Action));
  45138. BABYLON.DoNothingAction = DoNothingAction;
  45139. var CombineAction = (function (_super) {
  45140. __extends(CombineAction, _super);
  45141. function CombineAction(triggerOptions, children, condition) {
  45142. var _this = _super.call(this, triggerOptions, condition) || this;
  45143. _this.children = children;
  45144. return _this;
  45145. }
  45146. CombineAction.prototype._prepare = function () {
  45147. for (var index = 0; index < this.children.length; index++) {
  45148. this.children[index]._actionManager = this._actionManager;
  45149. this.children[index]._prepare();
  45150. }
  45151. };
  45152. CombineAction.prototype.execute = function (evt) {
  45153. for (var index = 0; index < this.children.length; index++) {
  45154. this.children[index].execute(evt);
  45155. }
  45156. };
  45157. CombineAction.prototype.serialize = function (parent) {
  45158. var serializationObject = _super.prototype._serialize.call(this, {
  45159. name: "CombineAction",
  45160. properties: [],
  45161. combine: []
  45162. }, parent);
  45163. for (var i = 0; i < this.children.length; i++) {
  45164. serializationObject.combine.push(this.children[i].serialize(null));
  45165. }
  45166. return serializationObject;
  45167. };
  45168. return CombineAction;
  45169. }(BABYLON.Action));
  45170. BABYLON.CombineAction = CombineAction;
  45171. var ExecuteCodeAction = (function (_super) {
  45172. __extends(ExecuteCodeAction, _super);
  45173. function ExecuteCodeAction(triggerOptions, func, condition) {
  45174. var _this = _super.call(this, triggerOptions, condition) || this;
  45175. _this.func = func;
  45176. return _this;
  45177. }
  45178. ExecuteCodeAction.prototype.execute = function (evt) {
  45179. this.func(evt);
  45180. };
  45181. return ExecuteCodeAction;
  45182. }(BABYLON.Action));
  45183. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45184. var SetParentAction = (function (_super) {
  45185. __extends(SetParentAction, _super);
  45186. function SetParentAction(triggerOptions, target, parent, condition) {
  45187. var _this = _super.call(this, triggerOptions, condition) || this;
  45188. _this._target = target;
  45189. _this._parent = parent;
  45190. return _this;
  45191. }
  45192. SetParentAction.prototype._prepare = function () {
  45193. };
  45194. SetParentAction.prototype.execute = function () {
  45195. if (this._target.parent === this._parent) {
  45196. return;
  45197. }
  45198. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45199. invertParentWorldMatrix.invert();
  45200. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45201. this._target.parent = this._parent;
  45202. };
  45203. SetParentAction.prototype.serialize = function (parent) {
  45204. return _super.prototype._serialize.call(this, {
  45205. name: "SetParentAction",
  45206. properties: [
  45207. BABYLON.Action._GetTargetProperty(this._target),
  45208. BABYLON.Action._GetTargetProperty(this._parent),
  45209. ]
  45210. }, parent);
  45211. };
  45212. return SetParentAction;
  45213. }(BABYLON.Action));
  45214. BABYLON.SetParentAction = SetParentAction;
  45215. var PlaySoundAction = (function (_super) {
  45216. __extends(PlaySoundAction, _super);
  45217. function PlaySoundAction(triggerOptions, sound, condition) {
  45218. var _this = _super.call(this, triggerOptions, condition) || this;
  45219. _this._sound = sound;
  45220. return _this;
  45221. }
  45222. PlaySoundAction.prototype._prepare = function () {
  45223. };
  45224. PlaySoundAction.prototype.execute = function () {
  45225. if (this._sound !== undefined)
  45226. this._sound.play();
  45227. };
  45228. PlaySoundAction.prototype.serialize = function (parent) {
  45229. return _super.prototype._serialize.call(this, {
  45230. name: "PlaySoundAction",
  45231. properties: [{ name: "sound", value: this._sound.name }]
  45232. }, parent);
  45233. };
  45234. return PlaySoundAction;
  45235. }(BABYLON.Action));
  45236. BABYLON.PlaySoundAction = PlaySoundAction;
  45237. var StopSoundAction = (function (_super) {
  45238. __extends(StopSoundAction, _super);
  45239. function StopSoundAction(triggerOptions, sound, condition) {
  45240. var _this = _super.call(this, triggerOptions, condition) || this;
  45241. _this._sound = sound;
  45242. return _this;
  45243. }
  45244. StopSoundAction.prototype._prepare = function () {
  45245. };
  45246. StopSoundAction.prototype.execute = function () {
  45247. if (this._sound !== undefined)
  45248. this._sound.stop();
  45249. };
  45250. StopSoundAction.prototype.serialize = function (parent) {
  45251. return _super.prototype._serialize.call(this, {
  45252. name: "StopSoundAction",
  45253. properties: [{ name: "sound", value: this._sound.name }]
  45254. }, parent);
  45255. };
  45256. return StopSoundAction;
  45257. }(BABYLON.Action));
  45258. BABYLON.StopSoundAction = StopSoundAction;
  45259. })(BABYLON || (BABYLON = {}));
  45260. //# sourceMappingURL=babylon.directActions.js.map
  45261. var BABYLON;
  45262. (function (BABYLON) {
  45263. var Debug;
  45264. (function (Debug) {
  45265. /**
  45266. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  45267. */
  45268. var SkeletonViewer = (function () {
  45269. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  45270. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  45271. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  45272. this.skeleton = skeleton;
  45273. this.mesh = mesh;
  45274. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  45275. this.renderingGroupId = renderingGroupId;
  45276. this.color = BABYLON.Color3.White();
  45277. this._debugLines = [];
  45278. this._isEnabled = false;
  45279. this._scene = scene;
  45280. this.update();
  45281. this._renderFunction = this.update.bind(this);
  45282. }
  45283. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  45284. get: function () {
  45285. return this._isEnabled;
  45286. },
  45287. set: function (value) {
  45288. if (this._isEnabled === value) {
  45289. return;
  45290. }
  45291. this._isEnabled = value;
  45292. if (value) {
  45293. this._scene.registerBeforeRender(this._renderFunction);
  45294. }
  45295. else {
  45296. this._scene.unregisterBeforeRender(this._renderFunction);
  45297. }
  45298. },
  45299. enumerable: true,
  45300. configurable: true
  45301. });
  45302. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  45303. if (x === void 0) { x = 0; }
  45304. if (y === void 0) { y = 0; }
  45305. if (z === void 0) { z = 0; }
  45306. var tmat = BABYLON.Tmp.Matrix[0];
  45307. var parentBone = bone.getParent();
  45308. tmat.copyFrom(bone.getLocalMatrix());
  45309. if (x !== 0 || y !== 0 || z !== 0) {
  45310. var tmat2 = BABYLON.Tmp.Matrix[1];
  45311. BABYLON.Matrix.IdentityToRef(tmat2);
  45312. tmat2.m[12] = x;
  45313. tmat2.m[13] = y;
  45314. tmat2.m[14] = z;
  45315. tmat2.multiplyToRef(tmat, tmat);
  45316. }
  45317. if (parentBone) {
  45318. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  45319. }
  45320. tmat.multiplyToRef(meshMat, tmat);
  45321. position.x = tmat.m[12];
  45322. position.y = tmat.m[13];
  45323. position.z = tmat.m[14];
  45324. };
  45325. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  45326. var len = bones.length;
  45327. var meshPos = this.mesh.position;
  45328. for (var i = 0; i < len; i++) {
  45329. var bone = bones[i];
  45330. var points = this._debugLines[i];
  45331. if (!points) {
  45332. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45333. this._debugLines[i] = points;
  45334. }
  45335. this._getBonePosition(points[0], bone, meshMat);
  45336. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  45337. points[0].subtractInPlace(meshPos);
  45338. points[1].subtractInPlace(meshPos);
  45339. }
  45340. };
  45341. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  45342. var len = bones.length;
  45343. var boneNum = 0;
  45344. var meshPos = this.mesh.position;
  45345. for (var i = len - 1; i >= 0; i--) {
  45346. var childBone = bones[i];
  45347. var parentBone = childBone.getParent();
  45348. if (!parentBone) {
  45349. continue;
  45350. }
  45351. var points = this._debugLines[boneNum];
  45352. if (!points) {
  45353. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45354. this._debugLines[boneNum] = points;
  45355. }
  45356. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  45357. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  45358. points[0].subtractInPlace(meshPos);
  45359. points[1].subtractInPlace(meshPos);
  45360. boneNum++;
  45361. }
  45362. };
  45363. SkeletonViewer.prototype.update = function () {
  45364. if (this.autoUpdateBonesMatrices) {
  45365. this.skeleton.computeAbsoluteTransforms();
  45366. }
  45367. if (this.skeleton.bones[0].length === undefined) {
  45368. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45369. }
  45370. else {
  45371. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  45372. }
  45373. if (!this._debugMesh) {
  45374. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  45375. this._debugMesh.renderingGroupId = this.renderingGroupId;
  45376. }
  45377. else {
  45378. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  45379. }
  45380. this._debugMesh.position.copyFrom(this.mesh.position);
  45381. this._debugMesh.color = this.color;
  45382. };
  45383. SkeletonViewer.prototype.dispose = function () {
  45384. if (this._debugMesh) {
  45385. this.isEnabled = false;
  45386. this._debugMesh.dispose();
  45387. this._debugMesh = null;
  45388. }
  45389. };
  45390. return SkeletonViewer;
  45391. }());
  45392. Debug.SkeletonViewer = SkeletonViewer;
  45393. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45394. })(BABYLON || (BABYLON = {}));
  45395. //# sourceMappingURL=babylon.skeletonViewer.js.map
  45396. var BABYLON;
  45397. (function (BABYLON) {
  45398. var Debug;
  45399. (function (Debug) {
  45400. var AxesViewer = (function () {
  45401. function AxesViewer(scene, scaleLines) {
  45402. if (scaleLines === void 0) { scaleLines = 1; }
  45403. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45404. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45405. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  45406. this.scaleLines = 1;
  45407. this.scaleLines = scaleLines;
  45408. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  45409. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  45410. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  45411. this._xmesh.renderingGroupId = 2;
  45412. this._ymesh.renderingGroupId = 2;
  45413. this._zmesh.renderingGroupId = 2;
  45414. this._xmesh.material.checkReadyOnlyOnce = true;
  45415. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  45416. this._ymesh.material.checkReadyOnlyOnce = true;
  45417. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  45418. this._zmesh.material.checkReadyOnlyOnce = true;
  45419. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  45420. this.scene = scene;
  45421. }
  45422. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  45423. var scaleLines = this.scaleLines;
  45424. this._xmesh.position.copyFrom(position);
  45425. this._ymesh.position.copyFrom(position);
  45426. this._zmesh.position.copyFrom(position);
  45427. var point2 = this._xline[1];
  45428. point2.x = xaxis.x * scaleLines;
  45429. point2.y = xaxis.y * scaleLines;
  45430. point2.z = xaxis.z * scaleLines;
  45431. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  45432. point2 = this._yline[1];
  45433. point2.x = yaxis.x * scaleLines;
  45434. point2.y = yaxis.y * scaleLines;
  45435. point2.z = yaxis.z * scaleLines;
  45436. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  45437. point2 = this._zline[1];
  45438. point2.x = zaxis.x * scaleLines;
  45439. point2.y = zaxis.y * scaleLines;
  45440. point2.z = zaxis.z * scaleLines;
  45441. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  45442. };
  45443. AxesViewer.prototype.dispose = function () {
  45444. if (this._xmesh) {
  45445. this._xmesh.dispose();
  45446. this._ymesh.dispose();
  45447. this._zmesh.dispose();
  45448. this._xmesh = null;
  45449. this._ymesh = null;
  45450. this._zmesh = null;
  45451. this._xline = null;
  45452. this._yline = null;
  45453. this._zline = null;
  45454. this.scene = null;
  45455. }
  45456. };
  45457. return AxesViewer;
  45458. }());
  45459. Debug.AxesViewer = AxesViewer;
  45460. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45461. })(BABYLON || (BABYLON = {}));
  45462. //# sourceMappingURL=babylon.axesViewer.js.map
  45463. var BABYLON;
  45464. (function (BABYLON) {
  45465. var Debug;
  45466. (function (Debug) {
  45467. var BoneAxesViewer = (function (_super) {
  45468. __extends(BoneAxesViewer, _super);
  45469. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  45470. if (scaleLines === void 0) { scaleLines = 1; }
  45471. var _this = _super.call(this, scene, scaleLines) || this;
  45472. _this.pos = BABYLON.Vector3.Zero();
  45473. _this.xaxis = BABYLON.Vector3.Zero();
  45474. _this.yaxis = BABYLON.Vector3.Zero();
  45475. _this.zaxis = BABYLON.Vector3.Zero();
  45476. _this.mesh = mesh;
  45477. _this.bone = bone;
  45478. return _this;
  45479. }
  45480. BoneAxesViewer.prototype.update = function () {
  45481. var bone = this.bone;
  45482. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  45483. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  45484. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  45485. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  45486. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  45487. };
  45488. BoneAxesViewer.prototype.dispose = function () {
  45489. if (this.pos) {
  45490. this.pos = null;
  45491. this.xaxis = null;
  45492. this.yaxis = null;
  45493. this.zaxis = null;
  45494. this.mesh = null;
  45495. this.bone = null;
  45496. _super.prototype.dispose.call(this);
  45497. }
  45498. };
  45499. return BoneAxesViewer;
  45500. }(Debug.AxesViewer));
  45501. Debug.BoneAxesViewer = BoneAxesViewer;
  45502. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45503. })(BABYLON || (BABYLON = {}));
  45504. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  45505. var BABYLON;
  45506. (function (BABYLON) {
  45507. var RayHelper = (function () {
  45508. function RayHelper(ray) {
  45509. this.ray = ray;
  45510. }
  45511. RayHelper.CreateAndShow = function (ray, scene, color) {
  45512. var helper = new RayHelper(ray);
  45513. helper.show(scene, color);
  45514. return helper;
  45515. };
  45516. RayHelper.prototype.show = function (scene, color) {
  45517. if (!this._renderFunction) {
  45518. var ray = this.ray;
  45519. this._renderFunction = this._render.bind(this);
  45520. this._scene = scene;
  45521. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  45522. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  45523. this._scene.registerBeforeRender(this._renderFunction);
  45524. }
  45525. if (color) {
  45526. this._renderLine.color.copyFrom(color);
  45527. }
  45528. };
  45529. RayHelper.prototype.hide = function () {
  45530. if (this._renderFunction) {
  45531. this._scene.unregisterBeforeRender(this._renderFunction);
  45532. this._scene = null;
  45533. this._renderFunction = null;
  45534. this._renderLine.dispose();
  45535. this._renderLine = null;
  45536. this._renderPoints = null;
  45537. }
  45538. };
  45539. RayHelper.prototype._render = function () {
  45540. var ray = this.ray;
  45541. var point = this._renderPoints[1];
  45542. var len = Math.min(ray.length, 1000000);
  45543. point.copyFrom(ray.direction);
  45544. point.scaleInPlace(len);
  45545. point.addInPlace(ray.origin);
  45546. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  45547. };
  45548. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  45549. this._attachedToMesh = mesh;
  45550. var ray = this.ray;
  45551. if (!ray.direction) {
  45552. ray.direction = BABYLON.Vector3.Zero();
  45553. }
  45554. if (!ray.origin) {
  45555. ray.origin = BABYLON.Vector3.Zero();
  45556. }
  45557. if (length) {
  45558. ray.length = length;
  45559. }
  45560. if (!meshSpaceOrigin) {
  45561. meshSpaceOrigin = BABYLON.Vector3.Zero();
  45562. }
  45563. if (!meshSpaceDirection) {
  45564. // -1 so that this will work with Mesh.lookAt
  45565. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  45566. }
  45567. if (!this._meshSpaceDirection) {
  45568. this._meshSpaceDirection = meshSpaceDirection.clone();
  45569. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  45570. }
  45571. else {
  45572. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  45573. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  45574. }
  45575. if (!this._updateToMeshFunction) {
  45576. this._updateToMeshFunction = this._updateToMesh.bind(this);
  45577. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  45578. }
  45579. this._updateToMesh();
  45580. };
  45581. RayHelper.prototype.detachFromMesh = function () {
  45582. if (this._attachedToMesh) {
  45583. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  45584. this._attachedToMesh = null;
  45585. this._updateToMeshFunction = null;
  45586. }
  45587. };
  45588. RayHelper.prototype._updateToMesh = function () {
  45589. var ray = this.ray;
  45590. if (this._attachedToMesh._isDisposed) {
  45591. this.detachFromMesh();
  45592. return;
  45593. }
  45594. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  45595. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  45596. };
  45597. RayHelper.prototype.dispose = function () {
  45598. this.hide();
  45599. this.detachFromMesh();
  45600. this.ray = null;
  45601. };
  45602. return RayHelper;
  45603. }());
  45604. BABYLON.RayHelper = RayHelper;
  45605. })(BABYLON || (BABYLON = {}));
  45606. //# sourceMappingURL=babylon.rayHelper.js.map
  45607. var BABYLON;
  45608. (function (BABYLON) {
  45609. var DebugLayer = (function () {
  45610. function DebugLayer(scene) {
  45611. this._scene = scene;
  45612. }
  45613. /** Creates the inspector window. */
  45614. DebugLayer.prototype._createInspector = function (config) {
  45615. if (config === void 0) { config = {}; }
  45616. var popup = config.popup || false;
  45617. var initialTab = config.initialTab || 0;
  45618. var parentElement = config.parentElement || null;
  45619. if (!this._inspector) {
  45620. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  45621. } // else nothing to do,; instance is already existing
  45622. };
  45623. DebugLayer.prototype.isVisible = function () {
  45624. if (!this._inspector) {
  45625. return false;
  45626. }
  45627. return true;
  45628. };
  45629. DebugLayer.prototype.hide = function () {
  45630. if (this._inspector) {
  45631. try {
  45632. this._inspector.dispose();
  45633. }
  45634. catch (e) {
  45635. // If the inspector has been removed directly from the inspector tool
  45636. }
  45637. this._inspector = null;
  45638. }
  45639. };
  45640. DebugLayer.prototype.show = function (config) {
  45641. if (config === void 0) { config = {}; }
  45642. if (typeof INSPECTOR == 'undefined') {
  45643. // Load inspector and add it to the DOM
  45644. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  45645. }
  45646. else {
  45647. // Otherwise creates the inspector
  45648. this._createInspector(config);
  45649. }
  45650. };
  45651. return DebugLayer;
  45652. }());
  45653. // Get protocol used - http or https
  45654. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  45655. BABYLON.DebugLayer = DebugLayer;
  45656. })(BABYLON || (BABYLON = {}));
  45657. //# sourceMappingURL=babylon.debugLayer.js.map
  45658. var BABYLON;
  45659. (function (BABYLON) {
  45660. var Debug;
  45661. (function (Debug) {
  45662. var PhysicsViewer = (function () {
  45663. function PhysicsViewer(scene) {
  45664. this._impostors = [];
  45665. this._meshes = [];
  45666. this._numMeshes = 0;
  45667. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45668. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  45669. }
  45670. PhysicsViewer.prototype._updateDebugMeshes = function () {
  45671. var plugin = this._physicsEnginePlugin;
  45672. for (var i = 0; i < this._numMeshes; i++) {
  45673. if (this._impostors[i].isDisposed) {
  45674. this.hideImpostor(this._impostors[i--]);
  45675. }
  45676. else {
  45677. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  45678. }
  45679. }
  45680. };
  45681. PhysicsViewer.prototype.showImpostor = function (impostor) {
  45682. for (var i = 0; i < this._numMeshes; i++) {
  45683. if (this._impostors[i] == impostor) {
  45684. return;
  45685. }
  45686. }
  45687. var debugMesh = this._getDebugMesh(impostor, this._scene);
  45688. if (debugMesh) {
  45689. this._impostors[this._numMeshes] = impostor;
  45690. this._meshes[this._numMeshes] = debugMesh;
  45691. if (this._numMeshes === 0) {
  45692. this._renderFunction = this._updateDebugMeshes.bind(this);
  45693. this._scene.registerBeforeRender(this._renderFunction);
  45694. }
  45695. this._numMeshes++;
  45696. }
  45697. };
  45698. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  45699. var removed = false;
  45700. for (var i = 0; i < this._numMeshes; i++) {
  45701. if (this._impostors[i] == impostor) {
  45702. this._scene.removeMesh(this._meshes[i]);
  45703. this._meshes[i].dispose();
  45704. this._numMeshes--;
  45705. if (this._numMeshes > 0) {
  45706. this._meshes[i] = this._meshes[this._numMeshes];
  45707. this._impostors[i] = this._impostors[this._numMeshes];
  45708. this._meshes[this._numMeshes] = null;
  45709. this._impostors[this._numMeshes] = null;
  45710. }
  45711. else {
  45712. this._meshes[0] = null;
  45713. this._impostors[0] = null;
  45714. }
  45715. removed = true;
  45716. break;
  45717. }
  45718. }
  45719. if (removed && this._numMeshes === 0) {
  45720. this._scene.unregisterBeforeRender(this._renderFunction);
  45721. }
  45722. };
  45723. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  45724. if (!this._debugMaterial) {
  45725. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  45726. this._debugMaterial.wireframe = true;
  45727. }
  45728. return this._debugMaterial;
  45729. };
  45730. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  45731. if (!this._debugBoxMesh) {
  45732. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  45733. this._debugBoxMesh.renderingGroupId = 1;
  45734. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  45735. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  45736. scene.removeMesh(this._debugBoxMesh);
  45737. }
  45738. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  45739. };
  45740. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  45741. if (!this._debugSphereMesh) {
  45742. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  45743. this._debugSphereMesh.renderingGroupId = 1;
  45744. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  45745. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  45746. scene.removeMesh(this._debugSphereMesh);
  45747. }
  45748. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  45749. };
  45750. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  45751. var body = impostor.physicsBody;
  45752. var shape = body.shapes[0];
  45753. var mesh;
  45754. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  45755. mesh = this._getDebugBoxMesh(scene);
  45756. impostor.getBoxSizeToRef(mesh.scaling);
  45757. }
  45758. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  45759. mesh = this._getDebugSphereMesh(scene);
  45760. var radius = impostor.getRadius();
  45761. mesh.scaling.x = radius * 2;
  45762. mesh.scaling.y = radius * 2;
  45763. mesh.scaling.z = radius * 2;
  45764. }
  45765. return mesh;
  45766. };
  45767. PhysicsViewer.prototype.dispose = function () {
  45768. for (var i = 0; i < this._numMeshes; i++) {
  45769. this.hideImpostor(this._impostors[i]);
  45770. }
  45771. if (this._debugBoxMesh) {
  45772. this._debugBoxMesh.dispose();
  45773. }
  45774. if (this._debugSphereMesh) {
  45775. this._debugSphereMesh.dispose();
  45776. }
  45777. if (this._debugMaterial) {
  45778. this._debugMaterial.dispose();
  45779. }
  45780. this._impostors.length = 0;
  45781. this._scene = null;
  45782. this._physicsEnginePlugin = null;
  45783. };
  45784. return PhysicsViewer;
  45785. }());
  45786. Debug.PhysicsViewer = PhysicsViewer;
  45787. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45788. })(BABYLON || (BABYLON = {}));
  45789. //# sourceMappingURL=babylon.physicsViewer.js.map
  45790. var BABYLON;
  45791. (function (BABYLON) {
  45792. var BoundingBoxRenderer = (function () {
  45793. function BoundingBoxRenderer(scene) {
  45794. this.frontColor = new BABYLON.Color3(1, 1, 1);
  45795. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  45796. this.showBackLines = true;
  45797. this.renderList = new BABYLON.SmartArray(32);
  45798. this._vertexBuffers = {};
  45799. this._scene = scene;
  45800. }
  45801. BoundingBoxRenderer.prototype._prepareRessources = function () {
  45802. if (this._colorShader) {
  45803. return;
  45804. }
  45805. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  45806. attributes: [BABYLON.VertexBuffer.PositionKind],
  45807. uniforms: ["world", "viewProjection", "color"]
  45808. });
  45809. var engine = this._scene.getEngine();
  45810. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  45811. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  45812. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  45813. };
  45814. BoundingBoxRenderer.prototype.reset = function () {
  45815. this.renderList.reset();
  45816. };
  45817. BoundingBoxRenderer.prototype.render = function () {
  45818. if (this.renderList.length === 0) {
  45819. return;
  45820. }
  45821. this._prepareRessources();
  45822. if (!this._colorShader.isReady()) {
  45823. return;
  45824. }
  45825. var engine = this._scene.getEngine();
  45826. engine.setDepthWrite(false);
  45827. this._colorShader._preBind();
  45828. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  45829. var boundingBox = this.renderList.data[boundingBoxIndex];
  45830. var min = boundingBox.minimum;
  45831. var max = boundingBox.maximum;
  45832. var diff = max.subtract(min);
  45833. var median = min.add(diff.scale(0.5));
  45834. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  45835. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  45836. .multiply(boundingBox.getWorldMatrix());
  45837. // VBOs
  45838. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  45839. if (this.showBackLines) {
  45840. // Back
  45841. engine.setDepthFunctionToGreaterOrEqual();
  45842. this._scene.resetCachedMaterial();
  45843. this._colorShader.setColor4("color", this.backColor.toColor4());
  45844. this._colorShader.bind(worldMatrix);
  45845. // Draw order
  45846. engine.draw(false, 0, 24);
  45847. }
  45848. // Front
  45849. engine.setDepthFunctionToLess();
  45850. this._scene.resetCachedMaterial();
  45851. this._colorShader.setColor4("color", this.frontColor.toColor4());
  45852. this._colorShader.bind(worldMatrix);
  45853. // Draw order
  45854. engine.draw(false, 0, 24);
  45855. }
  45856. this._colorShader.unbind();
  45857. engine.setDepthFunctionToLessOrEqual();
  45858. engine.setDepthWrite(true);
  45859. };
  45860. BoundingBoxRenderer.prototype.dispose = function () {
  45861. if (!this._colorShader) {
  45862. return;
  45863. }
  45864. this.renderList.dispose();
  45865. this._colorShader.dispose();
  45866. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45867. if (buffer) {
  45868. buffer.dispose();
  45869. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45870. }
  45871. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45872. };
  45873. return BoundingBoxRenderer;
  45874. }());
  45875. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  45876. })(BABYLON || (BABYLON = {}));
  45877. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  45878. var BABYLON;
  45879. (function (BABYLON) {
  45880. var TextureTools = (function () {
  45881. function TextureTools() {
  45882. }
  45883. /**
  45884. * Uses the GPU to create a copy texture rescaled at a given size
  45885. * @param texture Texture to copy from
  45886. * @param width Desired width
  45887. * @param height Desired height
  45888. * @return Generated texture
  45889. */
  45890. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  45891. if (useBilinearMode === void 0) { useBilinearMode = true; }
  45892. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  45893. var scene = texture.getScene();
  45894. var engine = scene.getEngine();
  45895. rtt.wrapU = texture.wrapU;
  45896. rtt.wrapV = texture.wrapV;
  45897. rtt.uOffset = texture.uOffset;
  45898. rtt.vOffset = texture.vOffset;
  45899. rtt.uScale = texture.uScale;
  45900. rtt.vScale = texture.vScale;
  45901. rtt.uAng = texture.uAng;
  45902. rtt.vAng = texture.vAng;
  45903. rtt.wAng = texture.wAng;
  45904. rtt.coordinatesIndex = texture.coordinatesIndex;
  45905. rtt.level = texture.level;
  45906. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  45907. rtt._texture.isReady = false;
  45908. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45909. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45910. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45911. passPostProcess.getEffect().executeWhenCompiled(function () {
  45912. passPostProcess.onApply = function (effect) {
  45913. effect.setTexture("textureSampler", texture);
  45914. };
  45915. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  45916. engine.unBindFramebuffer(rtt.getInternalTexture());
  45917. rtt.disposeFramebufferObjects();
  45918. passPostProcess.dispose();
  45919. rtt._texture.isReady = true;
  45920. });
  45921. return rtt;
  45922. };
  45923. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  45924. if (!scene._environmentBRDFTexture) {
  45925. var texture = new BABYLON.Texture(this._environmentBRDFBase64Texture, scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45926. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45927. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45928. scene._environmentBRDFTexture = texture;
  45929. }
  45930. return scene._environmentBRDFTexture;
  45931. };
  45932. return TextureTools;
  45933. }());
  45934. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  45935. BABYLON.TextureTools = TextureTools;
  45936. })(BABYLON || (BABYLON = {}));
  45937. //# sourceMappingURL=babylon.textureTools.js.map
  45938. var BABYLON;
  45939. (function (BABYLON) {
  45940. var SphericalPolynomial = (function () {
  45941. function SphericalPolynomial() {
  45942. this.x = BABYLON.Vector3.Zero();
  45943. this.y = BABYLON.Vector3.Zero();
  45944. this.z = BABYLON.Vector3.Zero();
  45945. this.xx = BABYLON.Vector3.Zero();
  45946. this.yy = BABYLON.Vector3.Zero();
  45947. this.zz = BABYLON.Vector3.Zero();
  45948. this.xy = BABYLON.Vector3.Zero();
  45949. this.yz = BABYLON.Vector3.Zero();
  45950. this.zx = BABYLON.Vector3.Zero();
  45951. }
  45952. SphericalPolynomial.prototype.addAmbient = function (color) {
  45953. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  45954. this.xx = this.xx.add(colorVector);
  45955. this.yy = this.yy.add(colorVector);
  45956. this.zz = this.zz.add(colorVector);
  45957. };
  45958. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  45959. var result = new SphericalPolynomial();
  45960. result.x = harmonics.L11.scale(1.02333);
  45961. result.y = harmonics.L1_1.scale(1.02333);
  45962. result.z = harmonics.L10.scale(1.02333);
  45963. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  45964. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  45965. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  45966. result.yz = harmonics.L2_1.scale(0.858086);
  45967. result.zx = harmonics.L21.scale(0.858086);
  45968. result.xy = harmonics.L2_2.scale(0.858086);
  45969. result.scale(1.0 / Math.PI);
  45970. return result;
  45971. };
  45972. SphericalPolynomial.prototype.scale = function (scale) {
  45973. this.x = this.x.scale(scale);
  45974. this.y = this.y.scale(scale);
  45975. this.z = this.z.scale(scale);
  45976. this.xx = this.xx.scale(scale);
  45977. this.yy = this.yy.scale(scale);
  45978. this.zz = this.zz.scale(scale);
  45979. this.yz = this.yz.scale(scale);
  45980. this.zx = this.zx.scale(scale);
  45981. this.xy = this.xy.scale(scale);
  45982. };
  45983. return SphericalPolynomial;
  45984. }());
  45985. BABYLON.SphericalPolynomial = SphericalPolynomial;
  45986. var SphericalHarmonics = (function () {
  45987. function SphericalHarmonics() {
  45988. this.L00 = BABYLON.Vector3.Zero();
  45989. this.L1_1 = BABYLON.Vector3.Zero();
  45990. this.L10 = BABYLON.Vector3.Zero();
  45991. this.L11 = BABYLON.Vector3.Zero();
  45992. this.L2_2 = BABYLON.Vector3.Zero();
  45993. this.L2_1 = BABYLON.Vector3.Zero();
  45994. this.L20 = BABYLON.Vector3.Zero();
  45995. this.L21 = BABYLON.Vector3.Zero();
  45996. this.L22 = BABYLON.Vector3.Zero();
  45997. }
  45998. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  45999. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  46000. var c = colorVector.scale(deltaSolidAngle);
  46001. this.L00 = this.L00.add(c.scale(0.282095));
  46002. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  46003. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  46004. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  46005. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  46006. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  46007. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  46008. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  46009. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  46010. };
  46011. SphericalHarmonics.prototype.scale = function (scale) {
  46012. this.L00 = this.L00.scale(scale);
  46013. this.L1_1 = this.L1_1.scale(scale);
  46014. this.L10 = this.L10.scale(scale);
  46015. this.L11 = this.L11.scale(scale);
  46016. this.L2_2 = this.L2_2.scale(scale);
  46017. this.L2_1 = this.L2_1.scale(scale);
  46018. this.L20 = this.L20.scale(scale);
  46019. this.L21 = this.L21.scale(scale);
  46020. this.L22 = this.L22.scale(scale);
  46021. };
  46022. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  46023. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  46024. //
  46025. // E_lm = A_l * L_lm
  46026. //
  46027. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  46028. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  46029. // the scaling factors are given in equation 9.
  46030. // Constant (Band 0)
  46031. this.L00 = this.L00.scale(3.141593);
  46032. // Linear (Band 1)
  46033. this.L1_1 = this.L1_1.scale(2.094395);
  46034. this.L10 = this.L10.scale(2.094395);
  46035. this.L11 = this.L11.scale(2.094395);
  46036. // Quadratic (Band 2)
  46037. this.L2_2 = this.L2_2.scale(0.785398);
  46038. this.L2_1 = this.L2_1.scale(0.785398);
  46039. this.L20 = this.L20.scale(0.785398);
  46040. this.L21 = this.L21.scale(0.785398);
  46041. this.L22 = this.L22.scale(0.785398);
  46042. };
  46043. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  46044. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  46045. // L = (1/pi) * E * rho
  46046. //
  46047. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  46048. this.scale(1.0 / Math.PI);
  46049. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  46050. // (The pixel shader must apply albedo after texture fetches, etc).
  46051. };
  46052. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  46053. var result = new SphericalHarmonics();
  46054. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  46055. result.L1_1 = polynomial.y.scale(0.977204);
  46056. result.L10 = polynomial.z.scale(0.977204);
  46057. result.L11 = polynomial.x.scale(0.977204);
  46058. result.L2_2 = polynomial.xy.scale(1.16538);
  46059. result.L2_1 = polynomial.yz.scale(1.16538);
  46060. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  46061. result.L21 = polynomial.zx.scale(1.16538);
  46062. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  46063. result.scale(Math.PI);
  46064. return result;
  46065. };
  46066. return SphericalHarmonics;
  46067. }());
  46068. BABYLON.SphericalHarmonics = SphericalHarmonics;
  46069. })(BABYLON || (BABYLON = {}));
  46070. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  46071. var BABYLON;
  46072. (function (BABYLON) {
  46073. var Internals;
  46074. (function (Internals) {
  46075. var FileFaceOrientation = (function () {
  46076. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  46077. this.name = name;
  46078. this.worldAxisForNormal = worldAxisForNormal;
  46079. this.worldAxisForFileX = worldAxisForFileX;
  46080. this.worldAxisForFileY = worldAxisForFileY;
  46081. }
  46082. return FileFaceOrientation;
  46083. }());
  46084. ;
  46085. /**
  46086. * Helper class dealing with the extraction of spherical polynomial dataArray
  46087. * from a cube map.
  46088. */
  46089. var CubeMapToSphericalPolynomialTools = (function () {
  46090. function CubeMapToSphericalPolynomialTools() {
  46091. }
  46092. /**
  46093. * Converts a texture to the according Spherical Polynomial data.
  46094. * This extracts the first 3 orders only as they are the only one used in the lighting.
  46095. *
  46096. * @param texture The texture to extract the information from.
  46097. * @return The Spherical Polynomial data.
  46098. */
  46099. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  46100. if (!texture.isCube) {
  46101. // Only supports cube Textures currently.
  46102. return null;
  46103. }
  46104. var size = texture.getSize().width;
  46105. var right = texture.readPixels(0);
  46106. var left = texture.readPixels(1);
  46107. var up = texture.readPixels(2);
  46108. var down = texture.readPixels(3);
  46109. var front = texture.readPixels(4);
  46110. var back = texture.readPixels(5);
  46111. var gammaSpace = texture.gammaSpace;
  46112. // Always read as RGBA.
  46113. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  46114. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46115. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46116. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46117. }
  46118. var cubeInfo = {
  46119. size: size,
  46120. right: right,
  46121. left: left,
  46122. up: up,
  46123. down: down,
  46124. front: front,
  46125. back: back,
  46126. format: format,
  46127. type: type,
  46128. gammaSpace: gammaSpace,
  46129. };
  46130. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  46131. };
  46132. /**
  46133. * Converts a cubemap to the according Spherical Polynomial data.
  46134. * This extracts the first 3 orders only as they are the only one used in the lighting.
  46135. *
  46136. * @param cubeInfo The Cube map to extract the information from.
  46137. * @return The Spherical Polynomial data.
  46138. */
  46139. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  46140. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  46141. var totalSolidAngle = 0.0;
  46142. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  46143. var du = 2.0 / cubeInfo.size;
  46144. var dv = du;
  46145. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  46146. var minUV = du * 0.5 - 1.0;
  46147. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46148. var fileFace = this.FileFaces[faceIndex];
  46149. var dataArray = cubeInfo[fileFace.name];
  46150. var v = minUV;
  46151. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  46152. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  46153. // Because SP is still linear, so summation is fine in that basis.
  46154. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  46155. for (var y = 0; y < cubeInfo.size; y++) {
  46156. var u = minUV;
  46157. for (var x = 0; x < cubeInfo.size; x++) {
  46158. // World direction (not normalised)
  46159. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  46160. worldDirection.normalize();
  46161. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  46162. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  46163. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  46164. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  46165. // Handle Integer types.
  46166. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46167. r /= 255;
  46168. g /= 255;
  46169. b /= 255;
  46170. }
  46171. // Handle Gamma space textures.
  46172. if (cubeInfo.gammaSpace) {
  46173. r = Math.pow(BABYLON.MathTools.Clamp(r), BABYLON.ToLinearSpace);
  46174. g = Math.pow(BABYLON.MathTools.Clamp(g), BABYLON.ToLinearSpace);
  46175. b = Math.pow(BABYLON.MathTools.Clamp(b), BABYLON.ToLinearSpace);
  46176. }
  46177. var color = new BABYLON.Color3(r, g, b);
  46178. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  46179. totalSolidAngle += deltaSolidAngle;
  46180. u += du;
  46181. }
  46182. v += dv;
  46183. }
  46184. }
  46185. // Solid angle for entire sphere is 4*pi
  46186. var sphereSolidAngle = 4.0 * Math.PI;
  46187. // Adjust the solid angle to allow for how many faces we processed.
  46188. var facesProcessed = 6.0;
  46189. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  46190. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  46191. // This is needed because the numerical integration over the cube uses a
  46192. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  46193. // and also to compensate for accumulative error due to float precision in the summation.
  46194. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  46195. sphericalHarmonics.scale(correctionFactor);
  46196. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  46197. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  46198. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  46199. };
  46200. return CubeMapToSphericalPolynomialTools;
  46201. }());
  46202. CubeMapToSphericalPolynomialTools.FileFaces = [
  46203. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  46204. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  46205. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  46206. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  46207. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  46208. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  46209. ];
  46210. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  46211. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46212. })(BABYLON || (BABYLON = {}));
  46213. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  46214. var BABYLON;
  46215. (function (BABYLON) {
  46216. var Internals;
  46217. (function (Internals) {
  46218. /**
  46219. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  46220. */
  46221. var PanoramaToCubeMapTools = (function () {
  46222. function PanoramaToCubeMapTools() {
  46223. }
  46224. /**
  46225. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  46226. *
  46227. * @param float32Array The source data.
  46228. * @param inputWidth The width of the input panorama.
  46229. * @param inputhHeight The height of the input panorama.
  46230. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  46231. * @return The cubemap data
  46232. */
  46233. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  46234. if (!float32Array) {
  46235. throw "ConvertPanoramaToCubemap: input cannot be null";
  46236. }
  46237. if (float32Array.length != inputWidth * inputHeight * 3) {
  46238. throw "ConvertPanoramaToCubemap: input size is wrong";
  46239. }
  46240. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  46241. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  46242. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  46243. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  46244. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  46245. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  46246. return {
  46247. front: textureFront,
  46248. back: textureBack,
  46249. left: textureLeft,
  46250. right: textureRight,
  46251. up: textureUp,
  46252. down: textureDown,
  46253. size: size,
  46254. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  46255. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  46256. gammaSpace: false,
  46257. };
  46258. };
  46259. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  46260. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  46261. var textureArray = new Float32Array(buffer);
  46262. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  46263. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  46264. var dy = 1 / texSize;
  46265. var fy = 0;
  46266. for (var y = 0; y < texSize; y++) {
  46267. var xv1 = faceData[0];
  46268. var xv2 = faceData[2];
  46269. for (var x = 0; x < texSize; x++) {
  46270. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  46271. v.normalize();
  46272. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  46273. // 3 channels per pixels
  46274. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  46275. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  46276. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  46277. xv1 = xv1.add(rotDX1);
  46278. xv2 = xv2.add(rotDX2);
  46279. }
  46280. fy += dy;
  46281. }
  46282. return textureArray;
  46283. };
  46284. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  46285. var theta = Math.atan2(vDir.z, vDir.x);
  46286. var phi = Math.acos(vDir.y);
  46287. while (theta < -Math.PI)
  46288. theta += 2 * Math.PI;
  46289. while (theta > Math.PI)
  46290. theta -= 2 * Math.PI;
  46291. var dx = theta / Math.PI;
  46292. var dy = phi / Math.PI;
  46293. // recenter.
  46294. dx = dx * 0.5 + 0.5;
  46295. var px = Math.round(dx * inputWidth);
  46296. if (px < 0)
  46297. px = 0;
  46298. else if (px >= inputWidth)
  46299. px = inputWidth - 1;
  46300. var py = Math.round(dy * inputHeight);
  46301. if (py < 0)
  46302. py = 0;
  46303. else if (py >= inputHeight)
  46304. py = inputHeight - 1;
  46305. var inputY = (inputHeight - py - 1);
  46306. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  46307. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  46308. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  46309. return {
  46310. r: r,
  46311. g: g,
  46312. b: b
  46313. };
  46314. };
  46315. return PanoramaToCubeMapTools;
  46316. }());
  46317. PanoramaToCubeMapTools.FACE_FRONT = [
  46318. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  46319. new BABYLON.Vector3(1.0, -1.0, -1.0),
  46320. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  46321. new BABYLON.Vector3(1.0, 1.0, -1.0)
  46322. ];
  46323. PanoramaToCubeMapTools.FACE_BACK = [
  46324. new BABYLON.Vector3(1.0, -1.0, 1.0),
  46325. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  46326. new BABYLON.Vector3(1.0, 1.0, 1.0),
  46327. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  46328. ];
  46329. PanoramaToCubeMapTools.FACE_RIGHT = [
  46330. new BABYLON.Vector3(1.0, -1.0, -1.0),
  46331. new BABYLON.Vector3(1.0, -1.0, 1.0),
  46332. new BABYLON.Vector3(1.0, 1.0, -1.0),
  46333. new BABYLON.Vector3(1.0, 1.0, 1.0)
  46334. ];
  46335. PanoramaToCubeMapTools.FACE_LEFT = [
  46336. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  46337. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  46338. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  46339. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  46340. ];
  46341. PanoramaToCubeMapTools.FACE_DOWN = [
  46342. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  46343. new BABYLON.Vector3(1.0, 1.0, -1.0),
  46344. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  46345. new BABYLON.Vector3(1.0, 1.0, 1.0)
  46346. ];
  46347. PanoramaToCubeMapTools.FACE_UP = [
  46348. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  46349. new BABYLON.Vector3(1.0, -1.0, 1.0),
  46350. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  46351. new BABYLON.Vector3(1.0, -1.0, -1.0)
  46352. ];
  46353. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  46354. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46355. })(BABYLON || (BABYLON = {}));
  46356. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  46357. var BABYLON;
  46358. (function (BABYLON) {
  46359. var Internals;
  46360. (function (Internals) {
  46361. ;
  46362. /**
  46363. * This groups tools to convert HDR texture to native colors array.
  46364. */
  46365. var HDRTools = (function () {
  46366. function HDRTools() {
  46367. }
  46368. HDRTools.Ldexp = function (mantissa, exponent) {
  46369. if (exponent > 1023) {
  46370. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  46371. }
  46372. if (exponent < -1074) {
  46373. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  46374. }
  46375. return mantissa * Math.pow(2, exponent);
  46376. };
  46377. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  46378. if (exponent > 0) {
  46379. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  46380. float32array[index + 0] = red * exponent;
  46381. float32array[index + 1] = green * exponent;
  46382. float32array[index + 2] = blue * exponent;
  46383. }
  46384. else {
  46385. float32array[index + 0] = 0;
  46386. float32array[index + 1] = 0;
  46387. float32array[index + 2] = 0;
  46388. }
  46389. };
  46390. HDRTools.readStringLine = function (uint8array, startIndex) {
  46391. var line = "";
  46392. var character = "";
  46393. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  46394. character = String.fromCharCode(uint8array[i]);
  46395. if (character == "\n") {
  46396. break;
  46397. }
  46398. line += character;
  46399. }
  46400. return line;
  46401. };
  46402. /**
  46403. * Reads header information from an RGBE texture stored in a native array.
  46404. * More information on this format are available here:
  46405. * https://en.wikipedia.org/wiki/RGBE_image_format
  46406. *
  46407. * @param uint8array The binary file stored in native array.
  46408. * @return The header information.
  46409. */
  46410. HDRTools.RGBE_ReadHeader = function (uint8array) {
  46411. var height = 0;
  46412. var width = 0;
  46413. var line = this.readStringLine(uint8array, 0);
  46414. if (line[0] != '#' || line[1] != '?') {
  46415. throw "Bad HDR Format.";
  46416. }
  46417. var endOfHeader = false;
  46418. var findFormat = false;
  46419. var lineIndex = 0;
  46420. do {
  46421. lineIndex += (line.length + 1);
  46422. line = this.readStringLine(uint8array, lineIndex);
  46423. if (line == "FORMAT=32-bit_rle_rgbe") {
  46424. findFormat = true;
  46425. }
  46426. else if (line.length == 0) {
  46427. endOfHeader = true;
  46428. }
  46429. } while (!endOfHeader);
  46430. if (!findFormat) {
  46431. throw "HDR Bad header format, unsupported FORMAT";
  46432. }
  46433. lineIndex += (line.length + 1);
  46434. line = this.readStringLine(uint8array, lineIndex);
  46435. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  46436. var match = sizeRegexp.exec(line);
  46437. // TODO. Support +Y and -X if needed.
  46438. if (match.length < 3) {
  46439. throw "HDR Bad header format, no size";
  46440. }
  46441. width = parseInt(match[2]);
  46442. height = parseInt(match[1]);
  46443. if (width < 8 || width > 0x7fff) {
  46444. throw "HDR Bad header format, unsupported size";
  46445. }
  46446. lineIndex += (line.length + 1);
  46447. return {
  46448. height: height,
  46449. width: width,
  46450. dataPosition: lineIndex
  46451. };
  46452. };
  46453. /**
  46454. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  46455. * This RGBE texture needs to store the information as a panorama.
  46456. *
  46457. * More information on this format are available here:
  46458. * https://en.wikipedia.org/wiki/RGBE_image_format
  46459. *
  46460. * @param buffer The binary file stored in an array buffer.
  46461. * @param size The expected size of the extracted cubemap.
  46462. * @return The Cube Map information.
  46463. */
  46464. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  46465. var uint8array = new Uint8Array(buffer);
  46466. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  46467. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  46468. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  46469. return cubeMapData;
  46470. };
  46471. /**
  46472. * Returns the pixels data extracted from an RGBE texture.
  46473. * This pixels will be stored left to right up to down in the R G B order in one array.
  46474. *
  46475. * More information on this format are available here:
  46476. * https://en.wikipedia.org/wiki/RGBE_image_format
  46477. *
  46478. * @param uint8array The binary file stored in an array buffer.
  46479. * @param hdrInfo The header information of the file.
  46480. * @return The pixels data in RGB right to left up to down order.
  46481. */
  46482. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  46483. // Keep for multi format supports.
  46484. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  46485. };
  46486. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  46487. var num_scanlines = hdrInfo.height;
  46488. var scanline_width = hdrInfo.width;
  46489. var a, b, c, d, count;
  46490. var dataIndex = hdrInfo.dataPosition;
  46491. var index = 0, endIndex = 0, i = 0;
  46492. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  46493. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  46494. // 3 channels of 4 bytes per pixel in float.
  46495. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  46496. var resultArray = new Float32Array(resultBuffer);
  46497. // read in each successive scanline
  46498. while (num_scanlines > 0) {
  46499. a = uint8array[dataIndex++];
  46500. b = uint8array[dataIndex++];
  46501. c = uint8array[dataIndex++];
  46502. d = uint8array[dataIndex++];
  46503. if (a != 2 || b != 2 || (c & 0x80)) {
  46504. // this file is not run length encoded
  46505. throw "HDR Bad header format, not RLE";
  46506. }
  46507. if (((c << 8) | d) != scanline_width) {
  46508. throw "HDR Bad header format, wrong scan line width";
  46509. }
  46510. index = 0;
  46511. // read each of the four channels for the scanline into the buffer
  46512. for (i = 0; i < 4; i++) {
  46513. endIndex = (i + 1) * scanline_width;
  46514. while (index < endIndex) {
  46515. a = uint8array[dataIndex++];
  46516. b = uint8array[dataIndex++];
  46517. if (a > 128) {
  46518. // a run of the same value
  46519. count = a - 128;
  46520. if ((count == 0) || (count > endIndex - index)) {
  46521. throw "HDR Bad Format, bad scanline data (run)";
  46522. }
  46523. while (count-- > 0) {
  46524. scanLineArray[index++] = b;
  46525. }
  46526. }
  46527. else {
  46528. // a non-run
  46529. count = a;
  46530. if ((count == 0) || (count > endIndex - index)) {
  46531. throw "HDR Bad Format, bad scanline data (non-run)";
  46532. }
  46533. scanLineArray[index++] = b;
  46534. if (--count > 0) {
  46535. for (var j = 0; j < count; j++) {
  46536. scanLineArray[index++] = uint8array[dataIndex++];
  46537. }
  46538. }
  46539. }
  46540. }
  46541. }
  46542. // now convert data from buffer into floats
  46543. for (i = 0; i < scanline_width; i++) {
  46544. a = scanLineArray[i];
  46545. b = scanLineArray[i + scanline_width];
  46546. c = scanLineArray[i + 2 * scanline_width];
  46547. d = scanLineArray[i + 3 * scanline_width];
  46548. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  46549. }
  46550. num_scanlines--;
  46551. }
  46552. return resultArray;
  46553. };
  46554. return HDRTools;
  46555. }());
  46556. Internals.HDRTools = HDRTools;
  46557. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46558. })(BABYLON || (BABYLON = {}));
  46559. //# sourceMappingURL=babylon.hdr.js.map
  46560. var BABYLON;
  46561. (function (BABYLON) {
  46562. /**
  46563. * This represents a texture coming from an HDR input.
  46564. *
  46565. * The only supported format is currently panorama picture stored in RGBE format.
  46566. * Example of such files can be found on HDRLib: http://hdrlib.com/
  46567. */
  46568. var HDRCubeTexture = (function (_super) {
  46569. __extends(HDRCubeTexture, _super);
  46570. /**
  46571. * Instantiates an HDRTexture from the following parameters.
  46572. *
  46573. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  46574. * @param scene The scene the texture will be used in
  46575. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  46576. * @param noMipmap Forces to not generate the mipmap if true
  46577. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  46578. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  46579. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  46580. */
  46581. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  46582. if (noMipmap === void 0) { noMipmap = false; }
  46583. if (generateHarmonics === void 0) { generateHarmonics = true; }
  46584. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  46585. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  46586. if (onLoad === void 0) { onLoad = null; }
  46587. if (onError === void 0) { onError = null; }
  46588. var _this = _super.call(this, scene) || this;
  46589. _this._useInGammaSpace = false;
  46590. _this._generateHarmonics = true;
  46591. _this._isBABYLONPreprocessed = false;
  46592. _this._onLoad = null;
  46593. _this._onError = null;
  46594. /**
  46595. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  46596. */
  46597. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46598. /**
  46599. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  46600. * This is usefull at run time to apply the good shader.
  46601. */
  46602. _this.isPMREM = false;
  46603. _this._isBlocking = true;
  46604. if (!url) {
  46605. return _this;
  46606. }
  46607. _this.name = url;
  46608. _this.url = url;
  46609. _this.hasAlpha = false;
  46610. _this.isCube = true;
  46611. _this._textureMatrix = BABYLON.Matrix.Identity();
  46612. _this._onLoad = onLoad;
  46613. _this._onError = onError;
  46614. _this.gammaSpace = false;
  46615. if (size) {
  46616. _this._isBABYLONPreprocessed = false;
  46617. _this._noMipmap = noMipmap;
  46618. _this._size = size;
  46619. _this._useInGammaSpace = useInGammaSpace;
  46620. _this._usePMREMGenerator = usePMREMGenerator &&
  46621. scene.getEngine().getCaps().textureLOD &&
  46622. _this.getScene().getEngine().getCaps().textureFloat &&
  46623. !_this._useInGammaSpace;
  46624. }
  46625. else {
  46626. _this._isBABYLONPreprocessed = true;
  46627. _this._noMipmap = false;
  46628. _this._useInGammaSpace = false;
  46629. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  46630. _this.getScene().getEngine().getCaps().textureFloat &&
  46631. !_this._useInGammaSpace;
  46632. }
  46633. _this.isPMREM = _this._usePMREMGenerator;
  46634. _this._texture = _this._getFromCache(url, _this._noMipmap);
  46635. if (!_this._texture) {
  46636. if (!scene.useDelayedTextureLoading) {
  46637. _this.loadTexture();
  46638. }
  46639. else {
  46640. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46641. }
  46642. }
  46643. return _this;
  46644. }
  46645. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  46646. /**
  46647. * Gets wether or not the texture is blocking during loading.
  46648. */
  46649. get: function () {
  46650. return this._isBlocking;
  46651. },
  46652. /**
  46653. * Sets wether or not the texture is blocking during loading.
  46654. */
  46655. set: function (value) {
  46656. this._isBlocking = value;
  46657. },
  46658. enumerable: true,
  46659. configurable: true
  46660. });
  46661. /**
  46662. * Occurs when the file is a preprocessed .babylon.hdr file.
  46663. */
  46664. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  46665. var _this = this;
  46666. var mipLevels = 0;
  46667. var floatArrayView = null;
  46668. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  46669. var mips = [];
  46670. var startIndex = 30;
  46671. for (var level = 0; level < mipLevels; level++) {
  46672. mips.push([]);
  46673. // Fill each pixel of the mip level.
  46674. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  46675. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46676. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  46677. mips[level].push(faceData);
  46678. startIndex += faceSize;
  46679. }
  46680. }
  46681. return mips;
  46682. } : null;
  46683. var callback = function (buffer) {
  46684. // Create Native Array Views
  46685. var intArrayView = new Int32Array(buffer);
  46686. floatArrayView = new Float32Array(buffer);
  46687. // Fill header.
  46688. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  46689. _this._size = intArrayView[1]; // CubeMap max mip face size.
  46690. // Update Texture Information.
  46691. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  46692. // Fill polynomial information.
  46693. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  46694. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  46695. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  46696. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  46697. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  46698. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  46699. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  46700. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  46701. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  46702. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  46703. _this.sphericalPolynomial = sphericalPolynomial;
  46704. // Fill pixel data.
  46705. mipLevels = intArrayView[29]; // Number of mip levels.
  46706. var startIndex = 30;
  46707. var data = [];
  46708. var faceSize = Math.pow(_this._size, 2) * 3;
  46709. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46710. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  46711. startIndex += faceSize;
  46712. }
  46713. var results = [];
  46714. var byteArray = null;
  46715. // Push each faces.
  46716. for (var k = 0; k < 6; k++) {
  46717. var dataFace = null;
  46718. // To be deprecated.
  46719. if (version === 1) {
  46720. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  46721. dataFace = data[j];
  46722. }
  46723. // If special cases.
  46724. if (!mipmapGenerator) {
  46725. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46726. // 3 channels of 1 bytes per pixel in bytes.
  46727. var byteBuffer = new ArrayBuffer(faceSize);
  46728. byteArray = new Uint8Array(byteBuffer);
  46729. }
  46730. for (var i = 0; i < _this._size * _this._size; i++) {
  46731. // Put in gamma space if requested.
  46732. if (_this._useInGammaSpace) {
  46733. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46734. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46735. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46736. }
  46737. // Convert to int texture for fallback.
  46738. if (byteArray) {
  46739. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46740. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46741. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46742. // May use luminance instead if the result is not accurate.
  46743. var max = Math.max(Math.max(r, g), b);
  46744. if (max > 255) {
  46745. var scale = 255 / max;
  46746. r *= scale;
  46747. g *= scale;
  46748. b *= scale;
  46749. }
  46750. byteArray[(i * 3) + 0] = r;
  46751. byteArray[(i * 3) + 1] = g;
  46752. byteArray[(i * 3) + 2] = b;
  46753. }
  46754. }
  46755. }
  46756. // Fill the array accordingly.
  46757. if (byteArray) {
  46758. results.push(byteArray);
  46759. }
  46760. else {
  46761. results.push(dataFace);
  46762. }
  46763. }
  46764. return results;
  46765. };
  46766. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  46767. };
  46768. /**
  46769. * Occurs when the file is raw .hdr file.
  46770. */
  46771. HDRCubeTexture.prototype.loadHDRTexture = function () {
  46772. var _this = this;
  46773. var callback = function (buffer) {
  46774. // Extract the raw linear data.
  46775. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  46776. // Generate harmonics if needed.
  46777. if (_this._generateHarmonics) {
  46778. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  46779. _this.sphericalPolynomial = sphericalPolynomial;
  46780. }
  46781. var results = [];
  46782. var byteArray = null;
  46783. // Push each faces.
  46784. for (var j = 0; j < 6; j++) {
  46785. // Create uintarray fallback.
  46786. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46787. // 3 channels of 1 bytes per pixel in bytes.
  46788. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  46789. byteArray = new Uint8Array(byteBuffer);
  46790. }
  46791. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  46792. // If special cases.
  46793. if (_this._useInGammaSpace || byteArray) {
  46794. for (var i = 0; i < _this._size * _this._size; i++) {
  46795. // Put in gamma space if requested.
  46796. if (_this._useInGammaSpace) {
  46797. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46798. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46799. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46800. }
  46801. // Convert to int texture for fallback.
  46802. if (byteArray) {
  46803. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46804. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46805. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46806. // May use luminance instead if the result is not accurate.
  46807. var max = Math.max(Math.max(r, g), b);
  46808. if (max > 255) {
  46809. var scale = 255 / max;
  46810. r *= scale;
  46811. g *= scale;
  46812. b *= scale;
  46813. }
  46814. byteArray[(i * 3) + 0] = r;
  46815. byteArray[(i * 3) + 1] = g;
  46816. byteArray[(i * 3) + 2] = b;
  46817. }
  46818. }
  46819. }
  46820. if (byteArray) {
  46821. results.push(byteArray);
  46822. }
  46823. else {
  46824. results.push(dataFace);
  46825. }
  46826. }
  46827. return results;
  46828. };
  46829. var mipmapGenerator = null;
  46830. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  46831. // if (!this._noMipmap &&
  46832. // this._usePMREMGenerator) {
  46833. // mipmapGenerator = (data: ArrayBufferView[]) => {
  46834. // // Custom setup of the generator matching with the PBR shader values.
  46835. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  46836. // this._size,
  46837. // this._size,
  46838. // 0,
  46839. // 3,
  46840. // this.getScene().getEngine().getCaps().textureFloat,
  46841. // 2048,
  46842. // 0.25,
  46843. // false,
  46844. // true);
  46845. // return generator.filterCubeMap();
  46846. // };
  46847. // }
  46848. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  46849. };
  46850. /**
  46851. * Starts the loading process of the texture.
  46852. */
  46853. HDRCubeTexture.prototype.loadTexture = function () {
  46854. if (this._isBABYLONPreprocessed) {
  46855. this.loadBabylonTexture();
  46856. }
  46857. else {
  46858. this.loadHDRTexture();
  46859. }
  46860. };
  46861. HDRCubeTexture.prototype.clone = function () {
  46862. var size = this._isBABYLONPreprocessed ? null : this._size;
  46863. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  46864. // Base texture
  46865. newTexture.level = this.level;
  46866. newTexture.wrapU = this.wrapU;
  46867. newTexture.wrapV = this.wrapV;
  46868. newTexture.coordinatesIndex = this.coordinatesIndex;
  46869. newTexture.coordinatesMode = this.coordinatesMode;
  46870. return newTexture;
  46871. };
  46872. // Methods
  46873. HDRCubeTexture.prototype.delayLoad = function () {
  46874. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  46875. return;
  46876. }
  46877. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  46878. this._texture = this._getFromCache(this.url, this._noMipmap);
  46879. if (!this._texture) {
  46880. this.loadTexture();
  46881. }
  46882. };
  46883. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  46884. return this._textureMatrix;
  46885. };
  46886. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  46887. this._textureMatrix = value;
  46888. };
  46889. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  46890. var texture = null;
  46891. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  46892. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  46893. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  46894. texture.name = parsedTexture.name;
  46895. texture.hasAlpha = parsedTexture.hasAlpha;
  46896. texture.level = parsedTexture.level;
  46897. texture.coordinatesMode = parsedTexture.coordinatesMode;
  46898. texture.isBlocking = parsedTexture.isBlocking;
  46899. }
  46900. return texture;
  46901. };
  46902. HDRCubeTexture.prototype.serialize = function () {
  46903. if (!this.name) {
  46904. return null;
  46905. }
  46906. var serializationObject = {};
  46907. serializationObject.name = this.name;
  46908. serializationObject.hasAlpha = this.hasAlpha;
  46909. serializationObject.isCube = true;
  46910. serializationObject.level = this.level;
  46911. serializationObject.size = this._size;
  46912. serializationObject.coordinatesMode = this.coordinatesMode;
  46913. serializationObject.useInGammaSpace = this._useInGammaSpace;
  46914. serializationObject.generateHarmonics = this._generateHarmonics;
  46915. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  46916. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  46917. serializationObject.customType = "BABYLON.HDRCubeTexture";
  46918. serializationObject.noMipmap = this._noMipmap;
  46919. serializationObject.isBlocking = this._isBlocking;
  46920. return serializationObject;
  46921. };
  46922. /**
  46923. * Saves as a file the data contained in the texture in a binary format.
  46924. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  46925. * as the spherical used in the lighting.
  46926. * @param url The HDR file url.
  46927. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  46928. * @param onError Method called if any error happens during download.
  46929. * @return The packed binary data.
  46930. */
  46931. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  46932. if (onError === void 0) { onError = null; }
  46933. var callback = function (buffer) {
  46934. var data = new Blob([buffer], { type: 'application/octet-stream' });
  46935. // Returns a URL you can use as a href.
  46936. var objUrl = window.URL.createObjectURL(data);
  46937. // Simulates a link to it and click to dowload.
  46938. var a = document.createElement("a");
  46939. document.body.appendChild(a);
  46940. a.style.display = "none";
  46941. a.href = objUrl;
  46942. a.download = "envmap.babylon.hdr";
  46943. a.click();
  46944. };
  46945. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  46946. };
  46947. /**
  46948. * Serializes the data contained in the texture in a binary format.
  46949. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  46950. * as the spherical used in the lighting.
  46951. * @param url The HDR file url.
  46952. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  46953. * @param onError Method called if any error happens during download.
  46954. * @return The packed binary data.
  46955. */
  46956. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  46957. if (onError === void 0) { onError = null; }
  46958. // Needs the url tho create the texture.
  46959. if (!url) {
  46960. return null;
  46961. }
  46962. // Check Power of two size.
  46963. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  46964. return null;
  46965. }
  46966. // Coming Back in 3.1.
  46967. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  46968. return null;
  46969. };
  46970. return HDRCubeTexture;
  46971. }(BABYLON.BaseTexture));
  46972. HDRCubeTexture._facesMapping = [
  46973. "right",
  46974. "left",
  46975. "up",
  46976. "down",
  46977. "front",
  46978. "back"
  46979. ];
  46980. BABYLON.HDRCubeTexture = HDRCubeTexture;
  46981. })(BABYLON || (BABYLON = {}));
  46982. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  46983. var BABYLON;
  46984. (function (BABYLON) {
  46985. var DefaultLoadingScreen = (function () {
  46986. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  46987. if (_loadingText === void 0) { _loadingText = ""; }
  46988. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  46989. var _this = this;
  46990. this._renderingCanvas = _renderingCanvas;
  46991. this._loadingText = _loadingText;
  46992. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  46993. // Resize
  46994. this._resizeLoadingUI = function () {
  46995. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  46996. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  46997. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  46998. _this._loadingDiv.style.left = canvasRect.left + "px";
  46999. _this._loadingDiv.style.top = canvasRect.top + "px";
  47000. _this._loadingDiv.style.width = canvasRect.width + "px";
  47001. _this._loadingDiv.style.height = canvasRect.height + "px";
  47002. };
  47003. }
  47004. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47005. if (this._loadingDiv) {
  47006. // Do not add a loading screen if there is already one
  47007. return;
  47008. }
  47009. this._loadingDiv = document.createElement("div");
  47010. this._loadingDiv.id = "babylonjsLoadingDiv";
  47011. this._loadingDiv.style.opacity = "0";
  47012. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47013. // Loading text
  47014. this._loadingTextDiv = document.createElement("div");
  47015. this._loadingTextDiv.style.position = "absolute";
  47016. this._loadingTextDiv.style.left = "0";
  47017. this._loadingTextDiv.style.top = "50%";
  47018. this._loadingTextDiv.style.marginTop = "80px";
  47019. this._loadingTextDiv.style.width = "100%";
  47020. this._loadingTextDiv.style.height = "20px";
  47021. this._loadingTextDiv.style.fontFamily = "Arial";
  47022. this._loadingTextDiv.style.fontSize = "14px";
  47023. this._loadingTextDiv.style.color = "white";
  47024. this._loadingTextDiv.style.textAlign = "center";
  47025. this._loadingTextDiv.innerHTML = "Loading";
  47026. this._loadingDiv.appendChild(this._loadingTextDiv);
  47027. //set the predefined text
  47028. this._loadingTextDiv.innerHTML = this._loadingText;
  47029. // Generating keyframes
  47030. var style = document.createElement('style');
  47031. style.type = 'text/css';
  47032. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  47033. style.innerHTML = keyFrames;
  47034. document.getElementsByTagName('head')[0].appendChild(style);
  47035. // Loading img
  47036. var imgBack = new Image();
  47037. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  47038. imgBack.style.position = "absolute";
  47039. imgBack.style.left = "50%";
  47040. imgBack.style.top = "50%";
  47041. imgBack.style.marginLeft = "-60px";
  47042. imgBack.style.marginTop = "-60px";
  47043. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47044. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47045. imgBack.style.transformOrigin = "50% 50%";
  47046. imgBack.style.webkitTransformOrigin = "50% 50%";
  47047. this._loadingDiv.appendChild(imgBack);
  47048. this._resizeLoadingUI();
  47049. window.addEventListener("resize", this._resizeLoadingUI);
  47050. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47051. document.body.appendChild(this._loadingDiv);
  47052. this._loadingDiv.style.opacity = "1";
  47053. };
  47054. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47055. var _this = this;
  47056. if (!this._loadingDiv) {
  47057. return;
  47058. }
  47059. var onTransitionEnd = function () {
  47060. if (!_this._loadingDiv) {
  47061. return;
  47062. }
  47063. document.body.removeChild(_this._loadingDiv);
  47064. window.removeEventListener("resize", _this._resizeLoadingUI);
  47065. _this._loadingDiv = null;
  47066. };
  47067. this._loadingDiv.style.opacity = "0";
  47068. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47069. };
  47070. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47071. set: function (text) {
  47072. this._loadingText = text;
  47073. if (this._loadingTextDiv) {
  47074. this._loadingTextDiv.innerHTML = this._loadingText;
  47075. }
  47076. },
  47077. enumerable: true,
  47078. configurable: true
  47079. });
  47080. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47081. get: function () {
  47082. return this._loadingDivBackgroundColor;
  47083. },
  47084. set: function (color) {
  47085. this._loadingDivBackgroundColor = color;
  47086. if (!this._loadingDiv) {
  47087. return;
  47088. }
  47089. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47090. },
  47091. enumerable: true,
  47092. configurable: true
  47093. });
  47094. return DefaultLoadingScreen;
  47095. }());
  47096. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47097. })(BABYLON || (BABYLON = {}));
  47098. //# sourceMappingURL=babylon.loadingScreen.js.map
  47099. var BABYLON;
  47100. (function (BABYLON) {
  47101. var SceneLoader = (function () {
  47102. function SceneLoader() {
  47103. }
  47104. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47105. get: function () {
  47106. return 0;
  47107. },
  47108. enumerable: true,
  47109. configurable: true
  47110. });
  47111. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47112. get: function () {
  47113. return 1;
  47114. },
  47115. enumerable: true,
  47116. configurable: true
  47117. });
  47118. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47119. get: function () {
  47120. return 2;
  47121. },
  47122. enumerable: true,
  47123. configurable: true
  47124. });
  47125. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47126. get: function () {
  47127. return 3;
  47128. },
  47129. enumerable: true,
  47130. configurable: true
  47131. });
  47132. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47133. get: function () {
  47134. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47135. },
  47136. set: function (value) {
  47137. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47138. },
  47139. enumerable: true,
  47140. configurable: true
  47141. });
  47142. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47143. get: function () {
  47144. return SceneLoader._ShowLoadingScreen;
  47145. },
  47146. set: function (value) {
  47147. SceneLoader._ShowLoadingScreen = value;
  47148. },
  47149. enumerable: true,
  47150. configurable: true
  47151. });
  47152. Object.defineProperty(SceneLoader, "loggingLevel", {
  47153. get: function () {
  47154. return SceneLoader._loggingLevel;
  47155. },
  47156. set: function (value) {
  47157. SceneLoader._loggingLevel = value;
  47158. },
  47159. enumerable: true,
  47160. configurable: true
  47161. });
  47162. SceneLoader._getDefaultPlugin = function () {
  47163. return SceneLoader._registeredPlugins[".babylon"];
  47164. };
  47165. SceneLoader._getPluginForExtension = function (extension) {
  47166. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47167. if (registeredPlugin) {
  47168. return registeredPlugin;
  47169. }
  47170. return SceneLoader._getDefaultPlugin();
  47171. };
  47172. SceneLoader._getPluginForDirectLoad = function (data) {
  47173. for (var extension in SceneLoader._registeredPlugins) {
  47174. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47175. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47176. return SceneLoader._registeredPlugins[extension];
  47177. }
  47178. }
  47179. return SceneLoader._getDefaultPlugin();
  47180. };
  47181. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47182. if (sceneFilename.name) {
  47183. sceneFilename = sceneFilename.name;
  47184. }
  47185. var dotPosition = sceneFilename.lastIndexOf(".");
  47186. var queryStringPosition = sceneFilename.indexOf("?");
  47187. if (queryStringPosition === -1) {
  47188. queryStringPosition = sceneFilename.length;
  47189. }
  47190. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47191. return SceneLoader._getPluginForExtension(extension);
  47192. };
  47193. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47194. SceneLoader._getDirectLoad = function (sceneFilename) {
  47195. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47196. return sceneFilename.substr(5);
  47197. }
  47198. return null;
  47199. };
  47200. // Public functions
  47201. SceneLoader.GetPluginForExtension = function (extension) {
  47202. return SceneLoader._getPluginForExtension(extension).plugin;
  47203. };
  47204. SceneLoader.RegisterPlugin = function (plugin) {
  47205. if (typeof plugin.extensions === "string") {
  47206. var extension = plugin.extensions;
  47207. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47208. plugin: plugin,
  47209. isBinary: false
  47210. };
  47211. }
  47212. else {
  47213. var extensions = plugin.extensions;
  47214. Object.keys(extensions).forEach(function (extension) {
  47215. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47216. plugin: plugin,
  47217. isBinary: extensions[extension].isBinary
  47218. };
  47219. });
  47220. }
  47221. };
  47222. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47223. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47224. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47225. return;
  47226. }
  47227. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47228. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47229. return;
  47230. }
  47231. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47232. var loadingToken = {};
  47233. scene._addPendingData(loadingToken);
  47234. var manifestChecked = function (success) {
  47235. scene.database = database;
  47236. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  47237. var plugin = registeredPlugin.plugin;
  47238. var useArrayBuffer = registeredPlugin.isBinary;
  47239. var importMeshFromData = function (data) {
  47240. var meshes = [];
  47241. var particleSystems = [];
  47242. var skeletons = [];
  47243. if (scene.isDisposed) {
  47244. if (onerror) {
  47245. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  47246. }
  47247. return;
  47248. }
  47249. try {
  47250. if (plugin.importMesh) {
  47251. var syncedPlugin = plugin;
  47252. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  47253. if (onerror) {
  47254. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47255. }
  47256. scene._removePendingData(loadingToken);
  47257. return;
  47258. }
  47259. if (onsuccess) {
  47260. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47261. onsuccess(meshes, particleSystems, skeletons);
  47262. scene._removePendingData(loadingToken);
  47263. }
  47264. }
  47265. else {
  47266. var asyncedPlugin = plugin;
  47267. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47268. if (onsuccess) {
  47269. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47270. onsuccess(meshes, particleSystems, skeletons);
  47271. scene._removePendingData(loadingToken);
  47272. }
  47273. }, function () {
  47274. if (onerror) {
  47275. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47276. }
  47277. scene._removePendingData(loadingToken);
  47278. });
  47279. }
  47280. }
  47281. catch (e) {
  47282. if (onerror) {
  47283. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  47284. }
  47285. scene._removePendingData(loadingToken);
  47286. }
  47287. };
  47288. if (directLoad) {
  47289. importMeshFromData(directLoad);
  47290. return;
  47291. }
  47292. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  47293. importMeshFromData(data);
  47294. }, progressCallBack, database, useArrayBuffer, function () {
  47295. if (onerror) {
  47296. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  47297. }
  47298. });
  47299. };
  47300. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  47301. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47302. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47303. }
  47304. else {
  47305. // If the scene is a data stream or offline support is not enabled, it's a direct load
  47306. manifestChecked(true);
  47307. }
  47308. };
  47309. /**
  47310. * Load a scene
  47311. * @param rootUrl a string that defines the root url for scene and resources
  47312. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47313. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47314. */
  47315. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  47316. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  47317. };
  47318. /**
  47319. * Append a scene
  47320. * @param rootUrl a string that defines the root url for scene and resources
  47321. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47322. * @param scene is the instance of BABYLON.Scene to append to
  47323. */
  47324. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47325. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47326. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47327. return;
  47328. }
  47329. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47330. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47331. var plugin = registeredPlugin.plugin;
  47332. var useArrayBuffer = registeredPlugin.isBinary;
  47333. var database;
  47334. var loadingToken = {};
  47335. scene._addPendingData(loadingToken);
  47336. if (SceneLoader.ShowLoadingScreen) {
  47337. scene.getEngine().displayLoadingUI();
  47338. }
  47339. var loadSceneFromData = function (data) {
  47340. scene.database = database;
  47341. if (plugin.load) {
  47342. var syncedPlugin = plugin;
  47343. if (!syncedPlugin.load(scene, data, rootUrl)) {
  47344. if (onerror) {
  47345. onerror(scene);
  47346. }
  47347. scene._removePendingData(loadingToken);
  47348. scene.getEngine().hideLoadingUI();
  47349. return;
  47350. }
  47351. if (onsuccess) {
  47352. onsuccess(scene);
  47353. }
  47354. scene._removePendingData(loadingToken);
  47355. }
  47356. else {
  47357. var asyncedPlugin = plugin;
  47358. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47359. if (onsuccess) {
  47360. onsuccess(scene);
  47361. }
  47362. scene._removePendingData(loadingToken);
  47363. }, function () {
  47364. if (onerror) {
  47365. onerror(scene);
  47366. }
  47367. scene._removePendingData(loadingToken);
  47368. scene.getEngine().hideLoadingUI();
  47369. });
  47370. }
  47371. if (SceneLoader.ShowLoadingScreen) {
  47372. scene.executeWhenReady(function () {
  47373. scene.getEngine().hideLoadingUI();
  47374. });
  47375. }
  47376. };
  47377. var manifestChecked = function (success) {
  47378. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  47379. };
  47380. if (directLoad) {
  47381. loadSceneFromData(directLoad);
  47382. return;
  47383. }
  47384. if (rootUrl.indexOf("file:") === -1) {
  47385. if (scene.getEngine().enableOfflineSupport) {
  47386. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47387. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47388. }
  47389. else {
  47390. manifestChecked(true);
  47391. }
  47392. }
  47393. else {
  47394. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  47395. }
  47396. };
  47397. return SceneLoader;
  47398. }());
  47399. // Flags
  47400. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47401. SceneLoader._ShowLoadingScreen = true;
  47402. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47403. // Members
  47404. SceneLoader._registeredPlugins = {};
  47405. BABYLON.SceneLoader = SceneLoader;
  47406. ;
  47407. })(BABYLON || (BABYLON = {}));
  47408. //# sourceMappingURL=babylon.sceneLoader.js.map
  47409. var BABYLON;
  47410. (function (BABYLON) {
  47411. var Internals;
  47412. (function (Internals) {
  47413. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47414. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47415. var parsedMaterial = parsedData.materials[index];
  47416. if (parsedMaterial.id === id) {
  47417. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47418. }
  47419. }
  47420. return null;
  47421. };
  47422. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47423. names = (names instanceof Array) ? names : [names];
  47424. for (var i in names) {
  47425. if (mesh.name === names[i]) {
  47426. hierarchyIds.push(mesh.id);
  47427. return true;
  47428. }
  47429. }
  47430. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47431. hierarchyIds.push(mesh.id);
  47432. return true;
  47433. }
  47434. return false;
  47435. };
  47436. var logOperation = function (operation, producer) {
  47437. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47438. };
  47439. BABYLON.SceneLoader.RegisterPlugin({
  47440. extensions: ".babylon",
  47441. canDirectLoad: function (data) {
  47442. if (data.indexOf("babylon") !== -1) {
  47443. return true;
  47444. }
  47445. return false;
  47446. },
  47447. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47448. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47449. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47450. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47451. // and avoid problems with multiple concurrent .babylon loads.
  47452. var log = "importMesh has failed JSON parse";
  47453. try {
  47454. var parsedData = JSON.parse(data);
  47455. log = "";
  47456. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47457. var loadedSkeletonsIds = [];
  47458. var loadedMaterialsIds = [];
  47459. var hierarchyIds = [];
  47460. var index;
  47461. var cache;
  47462. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47463. var parsedMesh = parsedData.meshes[index];
  47464. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47465. if (meshesNames instanceof Array) {
  47466. // Remove found mesh name from list.
  47467. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47468. }
  47469. //Geometry?
  47470. if (parsedMesh.geometryId) {
  47471. //does the file contain geometries?
  47472. if (parsedData.geometries) {
  47473. //find the correct geometry and add it to the scene
  47474. var found = false;
  47475. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47476. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  47477. return;
  47478. }
  47479. else {
  47480. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47481. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47482. switch (geometryType) {
  47483. case "boxes":
  47484. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47485. break;
  47486. case "spheres":
  47487. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47488. break;
  47489. case "cylinders":
  47490. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47491. break;
  47492. case "toruses":
  47493. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47494. break;
  47495. case "grounds":
  47496. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47497. break;
  47498. case "planes":
  47499. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47500. break;
  47501. case "torusKnots":
  47502. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47503. break;
  47504. case "vertexData":
  47505. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47506. break;
  47507. }
  47508. found = true;
  47509. }
  47510. });
  47511. }
  47512. });
  47513. if (!found) {
  47514. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47515. }
  47516. }
  47517. }
  47518. // Material ?
  47519. if (parsedMesh.materialId) {
  47520. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47521. if (!materialFound && parsedData.multiMaterials) {
  47522. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47523. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47524. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47525. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47526. var subMatId = parsedMultiMaterial.materials[matIndex];
  47527. loadedMaterialsIds.push(subMatId);
  47528. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47529. log += "\n\tMaterial " + mat.toString(fullDetails);
  47530. }
  47531. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47532. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47533. materialFound = true;
  47534. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47535. break;
  47536. }
  47537. }
  47538. }
  47539. if (!materialFound) {
  47540. loadedMaterialsIds.push(parsedMesh.materialId);
  47541. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47542. if (!mat) {
  47543. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47544. }
  47545. else {
  47546. log += "\n\tMaterial " + mat.toString(fullDetails);
  47547. }
  47548. }
  47549. }
  47550. // Skeleton ?
  47551. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  47552. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47553. if (!skeletonAlreadyLoaded) {
  47554. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47555. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47556. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47557. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47558. skeletons.push(skeleton);
  47559. loadedSkeletonsIds.push(parsedSkeleton.id);
  47560. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47561. }
  47562. }
  47563. }
  47564. }
  47565. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47566. meshes.push(mesh);
  47567. log += "\n\tMesh " + mesh.toString(fullDetails);
  47568. }
  47569. }
  47570. // Connecting parents
  47571. var currentMesh;
  47572. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47573. currentMesh = scene.meshes[index];
  47574. if (currentMesh._waitingParentId) {
  47575. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47576. currentMesh._waitingParentId = undefined;
  47577. }
  47578. }
  47579. // freeze and compute world matrix application
  47580. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47581. currentMesh = scene.meshes[index];
  47582. if (currentMesh._waitingFreezeWorldMatrix) {
  47583. currentMesh.freezeWorldMatrix();
  47584. currentMesh._waitingFreezeWorldMatrix = undefined;
  47585. }
  47586. else {
  47587. currentMesh.computeWorldMatrix(true);
  47588. }
  47589. }
  47590. // Particles
  47591. if (parsedData.particleSystems) {
  47592. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47593. var parsedParticleSystem = parsedData.particleSystems[index];
  47594. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47595. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47596. }
  47597. }
  47598. }
  47599. return true;
  47600. }
  47601. catch (err) {
  47602. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47603. log = null;
  47604. throw err;
  47605. }
  47606. finally {
  47607. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47608. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47609. }
  47610. }
  47611. },
  47612. load: function (scene, data, rootUrl) {
  47613. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47614. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47615. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47616. // and avoid problems with multiple concurrent .babylon loads.
  47617. var log = "importScene has failed JSON parse";
  47618. try {
  47619. var parsedData = JSON.parse(data);
  47620. log = "";
  47621. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47622. // Scene
  47623. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47624. scene.autoClear = parsedData.autoClear;
  47625. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47626. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47627. if (parsedData.gravity) {
  47628. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47629. }
  47630. // Fog
  47631. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47632. scene.fogMode = parsedData.fogMode;
  47633. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47634. scene.fogStart = parsedData.fogStart;
  47635. scene.fogEnd = parsedData.fogEnd;
  47636. scene.fogDensity = parsedData.fogDensity;
  47637. log += "\tFog mode for scene: ";
  47638. switch (scene.fogMode) {
  47639. // getters not compiling, so using hardcoded
  47640. case 1:
  47641. log += "exp\n";
  47642. break;
  47643. case 2:
  47644. log += "exp2\n";
  47645. break;
  47646. case 3:
  47647. log += "linear\n";
  47648. break;
  47649. }
  47650. }
  47651. //Physics
  47652. if (parsedData.physicsEnabled) {
  47653. var physicsPlugin;
  47654. if (parsedData.physicsEngine === "cannon") {
  47655. physicsPlugin = new BABYLON.CannonJSPlugin();
  47656. }
  47657. else if (parsedData.physicsEngine === "oimo") {
  47658. physicsPlugin = new BABYLON.OimoJSPlugin();
  47659. }
  47660. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47661. //else - default engine, which is currently oimo
  47662. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47663. scene.enablePhysics(physicsGravity, physicsPlugin);
  47664. }
  47665. // Metadata
  47666. if (parsedData.metadata !== undefined) {
  47667. scene.metadata = parsedData.metadata;
  47668. }
  47669. //collisions, if defined. otherwise, default is true
  47670. if (parsedData.collisionsEnabled != undefined) {
  47671. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47672. }
  47673. scene.workerCollisions = !!parsedData.workerCollisions;
  47674. var index;
  47675. var cache;
  47676. // Lights
  47677. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47678. var parsedLight = parsedData.lights[index];
  47679. var light = BABYLON.Light.Parse(parsedLight, scene);
  47680. log += (index === 0 ? "\n\tLights:" : "");
  47681. log += "\n\t\t" + light.toString(fullDetails);
  47682. }
  47683. // Animations
  47684. if (parsedData.animations) {
  47685. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47686. var parsedAnimation = parsedData.animations[index];
  47687. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47688. scene.animations.push(animation);
  47689. log += (index === 0 ? "\n\tAnimations:" : "");
  47690. log += "\n\t\t" + animation.toString(fullDetails);
  47691. }
  47692. }
  47693. if (parsedData.autoAnimate) {
  47694. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47695. }
  47696. // Materials
  47697. if (parsedData.materials) {
  47698. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47699. var parsedMaterial = parsedData.materials[index];
  47700. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47701. log += (index === 0 ? "\n\tMaterials:" : "");
  47702. log += "\n\t\t" + mat.toString(fullDetails);
  47703. }
  47704. }
  47705. if (parsedData.multiMaterials) {
  47706. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47707. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47708. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47709. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47710. log += "\n\t\t" + mmat.toString(fullDetails);
  47711. }
  47712. }
  47713. // Morph targets
  47714. if (parsedData.morphTargetManagers) {
  47715. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47716. var managerData = _a[_i];
  47717. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47718. }
  47719. }
  47720. // Skeletons
  47721. if (parsedData.skeletons) {
  47722. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47723. var parsedSkeleton = parsedData.skeletons[index];
  47724. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47725. log += (index === 0 ? "\n\tSkeletons:" : "");
  47726. log += "\n\t\t" + skeleton.toString(fullDetails);
  47727. }
  47728. }
  47729. // Geometries
  47730. var geometries = parsedData.geometries;
  47731. if (geometries) {
  47732. // Boxes
  47733. var boxes = geometries.boxes;
  47734. if (boxes) {
  47735. for (index = 0, cache = boxes.length; index < cache; index++) {
  47736. var parsedBox = boxes[index];
  47737. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47738. }
  47739. }
  47740. // Spheres
  47741. var spheres = geometries.spheres;
  47742. if (spheres) {
  47743. for (index = 0, cache = spheres.length; index < cache; index++) {
  47744. var parsedSphere = spheres[index];
  47745. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47746. }
  47747. }
  47748. // Cylinders
  47749. var cylinders = geometries.cylinders;
  47750. if (cylinders) {
  47751. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47752. var parsedCylinder = cylinders[index];
  47753. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47754. }
  47755. }
  47756. // Toruses
  47757. var toruses = geometries.toruses;
  47758. if (toruses) {
  47759. for (index = 0, cache = toruses.length; index < cache; index++) {
  47760. var parsedTorus = toruses[index];
  47761. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47762. }
  47763. }
  47764. // Grounds
  47765. var grounds = geometries.grounds;
  47766. if (grounds) {
  47767. for (index = 0, cache = grounds.length; index < cache; index++) {
  47768. var parsedGround = grounds[index];
  47769. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47770. }
  47771. }
  47772. // Planes
  47773. var planes = geometries.planes;
  47774. if (planes) {
  47775. for (index = 0, cache = planes.length; index < cache; index++) {
  47776. var parsedPlane = planes[index];
  47777. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47778. }
  47779. }
  47780. // TorusKnots
  47781. var torusKnots = geometries.torusKnots;
  47782. if (torusKnots) {
  47783. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47784. var parsedTorusKnot = torusKnots[index];
  47785. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47786. }
  47787. }
  47788. // VertexData
  47789. var vertexData = geometries.vertexData;
  47790. if (vertexData) {
  47791. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47792. var parsedVertexData = vertexData[index];
  47793. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47794. }
  47795. }
  47796. }
  47797. // Meshes
  47798. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47799. var parsedMesh = parsedData.meshes[index];
  47800. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47801. log += (index === 0 ? "\n\tMeshes:" : "");
  47802. log += "\n\t\t" + mesh.toString(fullDetails);
  47803. }
  47804. // Cameras
  47805. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47806. var parsedCamera = parsedData.cameras[index];
  47807. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47808. log += (index === 0 ? "\n\tCameras:" : "");
  47809. log += "\n\t\t" + camera.toString(fullDetails);
  47810. }
  47811. if (parsedData.activeCameraID) {
  47812. scene.setActiveCameraByID(parsedData.activeCameraID);
  47813. }
  47814. // Browsing all the graph to connect the dots
  47815. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47816. var camera = scene.cameras[index];
  47817. if (camera._waitingParentId) {
  47818. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  47819. camera._waitingParentId = undefined;
  47820. }
  47821. }
  47822. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47823. var light = scene.lights[index];
  47824. if (light._waitingParentId) {
  47825. light.parent = scene.getLastEntryByID(light._waitingParentId);
  47826. light._waitingParentId = undefined;
  47827. }
  47828. }
  47829. // Sounds
  47830. var loadedSounds = [];
  47831. var loadedSound;
  47832. if (BABYLON.AudioEngine && parsedData.sounds) {
  47833. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  47834. var parsedSound = parsedData.sounds[index];
  47835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  47836. if (!parsedSound.url)
  47837. parsedSound.url = parsedSound.name;
  47838. if (!loadedSounds[parsedSound.url]) {
  47839. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  47840. loadedSounds[parsedSound.url] = loadedSound;
  47841. }
  47842. else {
  47843. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  47844. }
  47845. }
  47846. else {
  47847. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  47848. }
  47849. }
  47850. }
  47851. loadedSounds = [];
  47852. // Connect parents & children and parse actions
  47853. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47854. var mesh = scene.meshes[index];
  47855. if (mesh._waitingParentId) {
  47856. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  47857. mesh._waitingParentId = undefined;
  47858. }
  47859. if (mesh._waitingActions) {
  47860. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  47861. mesh._waitingActions = undefined;
  47862. }
  47863. }
  47864. // freeze world matrix application
  47865. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47866. var currentMesh = scene.meshes[index];
  47867. if (currentMesh._waitingFreezeWorldMatrix) {
  47868. currentMesh.freezeWorldMatrix();
  47869. currentMesh._waitingFreezeWorldMatrix = undefined;
  47870. }
  47871. else {
  47872. currentMesh.computeWorldMatrix(true);
  47873. }
  47874. }
  47875. // Particles Systems
  47876. if (parsedData.particleSystems) {
  47877. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47878. var parsedParticleSystem = parsedData.particleSystems[index];
  47879. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  47880. }
  47881. }
  47882. // Lens flares
  47883. if (parsedData.lensFlareSystems) {
  47884. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  47885. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  47886. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  47887. }
  47888. }
  47889. // Shadows
  47890. if (parsedData.shadowGenerators) {
  47891. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  47892. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  47893. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  47894. }
  47895. }
  47896. // Lights exclusions / inclusions
  47897. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47898. var light = scene.lights[index];
  47899. // Excluded check
  47900. if (light._excludedMeshesIds.length > 0) {
  47901. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  47902. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  47903. if (excludedMesh) {
  47904. light.excludedMeshes.push(excludedMesh);
  47905. }
  47906. }
  47907. light._excludedMeshesIds = [];
  47908. }
  47909. // Included check
  47910. if (light._includedOnlyMeshesIds.length > 0) {
  47911. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  47912. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  47913. if (includedOnlyMesh) {
  47914. light.includedOnlyMeshes.push(includedOnlyMesh);
  47915. }
  47916. }
  47917. light._includedOnlyMeshesIds = [];
  47918. }
  47919. }
  47920. // Actions (scene)
  47921. if (parsedData.actions) {
  47922. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  47923. }
  47924. // Finish
  47925. return true;
  47926. }
  47927. catch (err) {
  47928. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  47929. log = null;
  47930. throw err;
  47931. }
  47932. finally {
  47933. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47934. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47935. }
  47936. }
  47937. }
  47938. });
  47939. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  47940. })(BABYLON || (BABYLON = {}));
  47941. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  47942. var BABYLON;
  47943. (function (BABYLON) {
  47944. var FilesInput = (function () {
  47945. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  47946. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  47947. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  47948. this._engine = p_engine;
  47949. this._canvas = p_canvas;
  47950. this._currentScene = p_scene;
  47951. this._sceneLoadedCallback = p_sceneLoadedCallback;
  47952. this._progressCallback = p_progressCallback;
  47953. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  47954. this._textureLoadingCallback = p_textureLoadingCallback;
  47955. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  47956. }
  47957. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  47958. var _this = this;
  47959. if (p_elementToMonitor) {
  47960. this._elementToMonitor = p_elementToMonitor;
  47961. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  47962. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  47963. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  47964. }
  47965. };
  47966. FilesInput.prototype.renderFunction = function () {
  47967. if (this._additionnalRenderLoopLogicCallback) {
  47968. this._additionnalRenderLoopLogicCallback();
  47969. }
  47970. if (this._currentScene) {
  47971. if (this._textureLoadingCallback) {
  47972. var remaining = this._currentScene.getWaitingItemsCount();
  47973. if (remaining > 0) {
  47974. this._textureLoadingCallback(remaining);
  47975. }
  47976. }
  47977. this._currentScene.render();
  47978. }
  47979. };
  47980. FilesInput.prototype.drag = function (e) {
  47981. e.stopPropagation();
  47982. e.preventDefault();
  47983. };
  47984. FilesInput.prototype.drop = function (eventDrop) {
  47985. eventDrop.stopPropagation();
  47986. eventDrop.preventDefault();
  47987. this.loadFiles(eventDrop);
  47988. };
  47989. FilesInput.prototype.loadFiles = function (event) {
  47990. if (this._startingProcessingFilesCallback)
  47991. this._startingProcessingFilesCallback();
  47992. // Handling data transfer via drag'n'drop
  47993. if (event && event.dataTransfer && event.dataTransfer.files) {
  47994. this._filesToLoad = event.dataTransfer.files;
  47995. }
  47996. // Handling files from input files
  47997. if (event && event.target && event.target.files) {
  47998. this._filesToLoad = event.target.files;
  47999. }
  48000. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48001. for (var i = 0; i < this._filesToLoad.length; i++) {
  48002. var name_1 = this._filesToLoad[i].name.toLowerCase();
  48003. var extension = name_1.split('.').pop();
  48004. var type = this._filesToLoad[i].type;
  48005. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48006. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  48007. this._sceneFileToLoad = this._filesToLoad[i];
  48008. }
  48009. else {
  48010. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  48011. }
  48012. }
  48013. this.reload();
  48014. }
  48015. };
  48016. FilesInput.prototype.reload = function () {
  48017. var _this = this;
  48018. var that = this;
  48019. // If a ".babylon" file has been provided
  48020. if (this._sceneFileToLoad) {
  48021. if (this._currentScene) {
  48022. if (BABYLON.Tools.errorsCount > 0) {
  48023. BABYLON.Tools.ClearLogCache();
  48024. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48025. }
  48026. this._engine.stopRenderLoop();
  48027. this._currentScene.dispose();
  48028. }
  48029. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48030. that._currentScene = newScene;
  48031. // Wait for textures and shaders to be ready
  48032. that._currentScene.executeWhenReady(function () {
  48033. if (that._sceneLoadedCallback) {
  48034. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  48035. }
  48036. that._engine.runRenderLoop(function () { that.renderFunction(); });
  48037. });
  48038. }, function (progress) {
  48039. if (_this._progressCallback) {
  48040. _this._progressCallback(progress);
  48041. }
  48042. });
  48043. }
  48044. else {
  48045. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48046. }
  48047. };
  48048. return FilesInput;
  48049. }());
  48050. FilesInput.FilesToLoad = new Array();
  48051. BABYLON.FilesInput = FilesInput;
  48052. })(BABYLON || (BABYLON = {}));
  48053. //# sourceMappingURL=babylon.filesInput.js.map
  48054. BABYLON.Effect.ShadersStore={"postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#ifdef BUMP\nvec3 originalNormalW=normalW;\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#ifdef BUMP\noriginalNormalW=gl_FrontFacing ? originalNormalW : -originalNormalW;;\n#endif\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(V,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nenvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular*=surfaceReflectivityColor;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","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<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\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\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=vec3(1.0,1.0,1.0);\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#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\ngl_FragColor=color;\n}"};
  48055. 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","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","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 vec3 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","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\nvec3 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","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\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;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\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}","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)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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 darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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 min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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);\n\n\n\n\n\nreturn esm;\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\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.);\n\n\n\n\n\nreturn esm;\n}\n#endif\n","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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}\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}","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 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\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);\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);\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);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  48056. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  48057. module.exports = BABYLON;
  48058. };