babylon.max.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588
  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. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = 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. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2(1, 1)
  845. */
  846. Vector2.One = function () {
  847. return new Vector2(1, 1);
  848. };
  849. /**
  850. * Returns a new Vector2 set from the passed index element of the passed array.
  851. */
  852. Vector2.FromArray = function (array, offset) {
  853. if (offset === void 0) { offset = 0; }
  854. return new Vector2(array[offset], array[offset + 1]);
  855. };
  856. /**
  857. * Sets "result" from the passed index element of the passed array.
  858. */
  859. Vector2.FromArrayToRef = function (array, offset, result) {
  860. result.x = array[offset];
  861. result.y = array[offset + 1];
  862. };
  863. /**
  864. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  865. */
  866. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  867. var squared = amount * amount;
  868. var cubed = amount * squared;
  869. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  870. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  871. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  872. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  873. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  874. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  875. return new Vector2(x, y);
  876. };
  877. /**
  878. * 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".
  879. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  880. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  881. */
  882. Vector2.Clamp = function (value, min, max) {
  883. var x = value.x;
  884. x = (x > max.x) ? max.x : x;
  885. x = (x < min.x) ? min.x : x;
  886. var y = value.y;
  887. y = (y > max.y) ? max.y : y;
  888. y = (y < min.y) ? min.y : y;
  889. return new Vector2(x, y);
  890. };
  891. /**
  892. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  893. */
  894. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  895. var squared = amount * amount;
  896. var cubed = amount * squared;
  897. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  898. var part2 = (-2.0 * cubed) + (3.0 * squared);
  899. var part3 = (cubed - (2.0 * squared)) + amount;
  900. var part4 = cubed - squared;
  901. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  902. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  907. */
  908. Vector2.Lerp = function (start, end, amount) {
  909. var x = start.x + ((end.x - start.x) * amount);
  910. var y = start.y + ((end.y - start.y) * amount);
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns the dot product (float) of the vector "left" and the vector "right".
  915. */
  916. Vector2.Dot = function (left, right) {
  917. return left.x * right.x + left.y * right.y;
  918. };
  919. /**
  920. * Returns a new Vector2 equal to the normalized passed vector.
  921. */
  922. Vector2.Normalize = function (vector) {
  923. var newVector = vector.clone();
  924. newVector.normalize();
  925. return newVector;
  926. };
  927. /**
  928. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  929. */
  930. Vector2.Minimize = function (left, right) {
  931. var x = (left.x < right.x) ? left.x : right.x;
  932. var y = (left.y < right.y) ? left.y : right.y;
  933. return new Vector2(x, y);
  934. };
  935. /**
  936. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  937. */
  938. Vector2.Maximize = function (left, right) {
  939. var x = (left.x > right.x) ? left.x : right.x;
  940. var y = (left.y > right.y) ? left.y : right.y;
  941. return new Vector2(x, y);
  942. };
  943. /**
  944. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  945. */
  946. Vector2.Transform = function (vector, transformation) {
  947. var r = Vector2.Zero();
  948. Vector2.TransformToRef(vector, transformation, r);
  949. return r;
  950. };
  951. /**
  952. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  953. */
  954. Vector2.TransformToRef = function (vector, transformation, result) {
  955. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  956. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  957. result.x = x;
  958. result.y = y;
  959. };
  960. /**
  961. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  962. */
  963. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  964. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  965. var sign = a < 0 ? -1 : 1;
  966. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  967. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  968. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  969. };
  970. /**
  971. * Returns the distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.Distance = function (value1, value2) {
  974. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  975. };
  976. /**
  977. * Returns the squared distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. return (x * x) + (y * y);
  983. };
  984. /**
  985. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  986. */
  987. Vector2.Center = function (value1, value2) {
  988. var center = value1.add(value2);
  989. center.scaleInPlace(0.5);
  990. return center;
  991. };
  992. /**
  993. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  994. */
  995. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  996. var l2 = Vector2.DistanceSquared(segA, segB);
  997. if (l2 === 0.0) {
  998. return Vector2.Distance(p, segA);
  999. }
  1000. var v = segB.subtract(segA);
  1001. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1002. var proj = segA.add(v.multiplyByFloats(t, t));
  1003. return Vector2.Distance(p, proj);
  1004. };
  1005. return Vector2;
  1006. }());
  1007. BABYLON.Vector2 = Vector2;
  1008. var Vector3 = (function () {
  1009. /**
  1010. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1011. * A Vector3 is the main object used in 3D geometry.
  1012. * It can represent etiher the coordinates of a point the space, either a direction.
  1013. */
  1014. function Vector3(x, y, z) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. }
  1019. /**
  1020. * Returns a string with the Vector3 coordinates.
  1021. */
  1022. Vector3.prototype.toString = function () {
  1023. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1024. };
  1025. /**
  1026. * Returns the string "Vector3"
  1027. */
  1028. Vector3.prototype.getClassName = function () {
  1029. return "Vector3";
  1030. };
  1031. /**
  1032. * Returns the Vector hash code.
  1033. */
  1034. Vector3.prototype.getHashCode = function () {
  1035. var hash = this.x || 0;
  1036. hash = (hash * 397) ^ (this.y || 0);
  1037. hash = (hash * 397) ^ (this.z || 0);
  1038. return hash;
  1039. };
  1040. // Operators
  1041. /**
  1042. * Returns a new array with three elements : the coordinates the Vector3.
  1043. */
  1044. Vector3.prototype.asArray = function () {
  1045. var result = [];
  1046. this.toArray(result, 0);
  1047. return result;
  1048. };
  1049. /**
  1050. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1051. * Returns the Vector3.
  1052. */
  1053. Vector3.prototype.toArray = function (array, index) {
  1054. if (index === void 0) { index = 0; }
  1055. array[index] = this.x;
  1056. array[index + 1] = this.y;
  1057. array[index + 2] = this.z;
  1058. return this;
  1059. };
  1060. /**
  1061. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1062. */
  1063. Vector3.prototype.toQuaternion = function () {
  1064. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1065. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1066. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1067. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1068. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1069. var cosy = Math.cos(this.y * 0.5);
  1070. var siny = Math.sin(this.y * 0.5);
  1071. result.x = coszMinusx * siny;
  1072. result.y = -sinzMinusx * siny;
  1073. result.z = sinxPlusz * cosy;
  1074. result.w = cosxPlusz * cosy;
  1075. return result;
  1076. };
  1077. /**
  1078. * Adds the passed vector to the current Vector3.
  1079. * Returns the updated Vector3.
  1080. */
  1081. Vector3.prototype.addInPlace = function (otherVector) {
  1082. this.x += otherVector.x;
  1083. this.y += otherVector.y;
  1084. this.z += otherVector.z;
  1085. return this;
  1086. };
  1087. /**
  1088. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1089. */
  1090. Vector3.prototype.add = function (otherVector) {
  1091. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1092. };
  1093. /**
  1094. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1095. * Returns the current Vector3.
  1096. */
  1097. Vector3.prototype.addToRef = function (otherVector, result) {
  1098. result.x = this.x + otherVector.x;
  1099. result.y = this.y + otherVector.y;
  1100. result.z = this.z + otherVector.z;
  1101. return this;
  1102. };
  1103. /**
  1104. * Subtract the passed vector from the current Vector3.
  1105. * Returns the updated Vector3.
  1106. */
  1107. Vector3.prototype.subtractInPlace = function (otherVector) {
  1108. this.x -= otherVector.x;
  1109. this.y -= otherVector.y;
  1110. this.z -= otherVector.z;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1115. */
  1116. Vector3.prototype.subtract = function (otherVector) {
  1117. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1118. };
  1119. /**
  1120. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1121. * Returns the current Vector3.
  1122. */
  1123. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1124. result.x = this.x - otherVector.x;
  1125. result.y = this.y - otherVector.y;
  1126. result.z = this.z - otherVector.z;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1131. */
  1132. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1133. return new Vector3(this.x - x, this.y - y, this.z - z);
  1134. };
  1135. /**
  1136. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1137. * Returns the current Vector3.
  1138. */
  1139. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1140. result.x = this.x - x;
  1141. result.y = this.y - y;
  1142. result.z = this.z - z;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1147. */
  1148. Vector3.prototype.negate = function () {
  1149. return new Vector3(-this.x, -this.y, -this.z);
  1150. };
  1151. /**
  1152. * Multiplies the Vector3 coordinates by the float "scale".
  1153. * Returns the updated Vector3.
  1154. */
  1155. Vector3.prototype.scaleInPlace = function (scale) {
  1156. this.x *= scale;
  1157. this.y *= scale;
  1158. this.z *= scale;
  1159. return this;
  1160. };
  1161. /**
  1162. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1163. */
  1164. Vector3.prototype.scale = function (scale) {
  1165. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1166. };
  1167. /**
  1168. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1169. * Returns the current Vector3.
  1170. */
  1171. Vector3.prototype.scaleToRef = function (scale, result) {
  1172. result.x = this.x * scale;
  1173. result.y = this.y * scale;
  1174. result.z = this.z * scale;
  1175. return this;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1179. */
  1180. Vector3.prototype.equals = function (otherVector) {
  1181. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1185. */
  1186. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1187. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1188. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1189. };
  1190. /**
  1191. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1192. */
  1193. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1194. return this.x === x && this.y === y && this.z === z;
  1195. };
  1196. /**
  1197. * Muliplies the current Vector3 coordinates by the passed ones.
  1198. * Returns the updated Vector3.
  1199. */
  1200. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1201. this.x *= otherVector.x;
  1202. this.y *= otherVector.y;
  1203. this.z *= otherVector.z;
  1204. return this;
  1205. };
  1206. /**
  1207. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1208. */
  1209. Vector3.prototype.multiply = function (otherVector) {
  1210. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1211. };
  1212. /**
  1213. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1214. * Returns the current Vector3.
  1215. */
  1216. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1217. result.x = this.x * otherVector.x;
  1218. result.y = this.y * otherVector.y;
  1219. result.z = this.z * otherVector.z;
  1220. return this;
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1224. */
  1225. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1226. return new Vector3(this.x * x, this.y * y, this.z * z);
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1230. */
  1231. Vector3.prototype.divide = function (otherVector) {
  1232. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1233. };
  1234. /**
  1235. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1236. * Returns the current Vector3.
  1237. */
  1238. Vector3.prototype.divideToRef = function (otherVector, result) {
  1239. result.x = this.x / otherVector.x;
  1240. result.y = this.y / otherVector.y;
  1241. result.z = this.z / otherVector.z;
  1242. return this;
  1243. };
  1244. /**
  1245. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1246. * Returns the updated Vector3.
  1247. */
  1248. Vector3.prototype.MinimizeInPlace = function (other) {
  1249. if (other.x < this.x)
  1250. this.x = other.x;
  1251. if (other.y < this.y)
  1252. this.y = other.y;
  1253. if (other.z < this.z)
  1254. this.z = other.z;
  1255. return this;
  1256. };
  1257. /**
  1258. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1259. * Returns the updated Vector3.
  1260. */
  1261. Vector3.prototype.MaximizeInPlace = function (other) {
  1262. if (other.x > this.x)
  1263. this.x = other.x;
  1264. if (other.y > this.y)
  1265. this.y = other.y;
  1266. if (other.z > this.z)
  1267. this.z = other.z;
  1268. return this;
  1269. };
  1270. // Properties
  1271. /**
  1272. * Returns the length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.length = function () {
  1275. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. /**
  1278. * Returns the squared length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.lengthSquared = function () {
  1281. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. // Methods
  1284. /**
  1285. * Normalize the current Vector3.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.normalize = function () {
  1289. var len = this.length();
  1290. if (len === 0 || len === 1.0)
  1291. return this;
  1292. var num = 1.0 / len;
  1293. this.x *= num;
  1294. this.y *= num;
  1295. this.z *= num;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new Vector3 copied from the current Vector3.
  1300. */
  1301. Vector3.prototype.clone = function () {
  1302. return new Vector3(this.x, this.y, this.z);
  1303. };
  1304. /**
  1305. * Copies the passed vector coordinates to the current Vector3 ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.copyFrom = function (source) {
  1309. this.x = source.x;
  1310. this.y = source.y;
  1311. this.z = source.z;
  1312. return this;
  1313. };
  1314. /**
  1315. * Copies the passed floats to the current Vector3 coordinates.
  1316. * Returns the updated Vector3.
  1317. */
  1318. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. return this;
  1323. };
  1324. /**
  1325. * Copies the passed floats to the current Vector3 coordinates.
  1326. * Returns the updated Vector3.
  1327. */
  1328. Vector3.prototype.set = function (x, y, z) {
  1329. return this.copyFromFloats(x, y, z);
  1330. };
  1331. // Statics
  1332. /**
  1333. *
  1334. */
  1335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1336. var d0 = Vector3.Dot(vector0, axis) - size;
  1337. var d1 = Vector3.Dot(vector1, axis) - size;
  1338. var s = d0 / (d0 - d1);
  1339. return s;
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set from the index "offset" of the passed array.
  1343. */
  1344. Vector3.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1352. * This function is deprecated. Use FromArray instead.
  1353. */
  1354. Vector3.FromFloatArray = function (array, offset) {
  1355. return Vector3.FromArray(array, offset);
  1356. };
  1357. /**
  1358. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1359. */
  1360. Vector3.FromArrayToRef = function (array, offset, result) {
  1361. result.x = array[offset];
  1362. result.y = array[offset + 1];
  1363. result.z = array[offset + 2];
  1364. };
  1365. /**
  1366. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1367. * This function is deprecated. Use FromArrayToRef instead.
  1368. */
  1369. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1370. return Vector3.FromArrayToRef(array, offset, result);
  1371. };
  1372. /**
  1373. * Sets the passed vector "result" with the passed floats.
  1374. */
  1375. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1376. result.x = x;
  1377. result.y = y;
  1378. result.z = z;
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1382. */
  1383. Vector3.Zero = function () {
  1384. return new Vector3(0.0, 0.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1388. */
  1389. Vector3.One = function () {
  1390. return new Vector3(1.0, 1.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1394. */
  1395. Vector3.Up = function () {
  1396. return new Vector3(0.0, 1.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1400. */
  1401. Vector3.Forward = function () {
  1402. return new Vector3(0.0, 0.0, 1.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1406. */
  1407. Vector3.Right = function () {
  1408. return new Vector3(1.0, 0.0, 0.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Left = function () {
  1414. return new Vector3(-1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1418. * This method computes tranformed coordinates only, not transformed direction vectors.
  1419. */
  1420. Vector3.TransformCoordinates = function (vector, transformation) {
  1421. var result = Vector3.Zero();
  1422. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1423. return result;
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1427. * This method computes tranformed coordinates only, not transformed direction vectors.
  1428. */
  1429. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1430. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1431. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1432. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1433. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1434. result.x = x / w;
  1435. result.y = y / w;
  1436. result.z = z / w;
  1437. };
  1438. /**
  1439. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1440. * This method computes tranformed coordinates only, not transformed direction vectors.
  1441. */
  1442. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1443. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1444. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1445. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1446. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1447. result.x = rx / rw;
  1448. result.y = ry / rw;
  1449. result.z = rz / rw;
  1450. };
  1451. /**
  1452. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1453. * This methods computes transformed normalized direction vectors only.
  1454. */
  1455. Vector3.TransformNormal = function (vector, transformation) {
  1456. var result = Vector3.Zero();
  1457. Vector3.TransformNormalToRef(vector, transformation, result);
  1458. return result;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1467. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1468. result.x = x;
  1469. result.y = y;
  1470. result.z = z;
  1471. };
  1472. /**
  1473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1474. * This methods computes transformed normalized direction vectors only.
  1475. */
  1476. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1477. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1478. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1479. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1480. };
  1481. /**
  1482. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1483. */
  1484. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1485. var squared = amount * amount;
  1486. var cubed = amount * squared;
  1487. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1488. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1489. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1490. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1491. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1492. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1493. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1494. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1495. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * 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".
  1500. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1501. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1502. */
  1503. Vector3.Clamp = function (value, min, max) {
  1504. var x = value.x;
  1505. x = (x > max.x) ? max.x : x;
  1506. x = (x < min.x) ? min.x : x;
  1507. var y = value.y;
  1508. y = (y > max.y) ? max.y : y;
  1509. y = (y < min.y) ? min.y : y;
  1510. var z = value.z;
  1511. z = (z > max.z) ? max.z : z;
  1512. z = (z < min.z) ? min.z : z;
  1513. return new Vector3(x, y, z);
  1514. };
  1515. /**
  1516. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1517. */
  1518. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1519. var squared = amount * amount;
  1520. var cubed = amount * squared;
  1521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1523. var part3 = (cubed - (2.0 * squared)) + amount;
  1524. var part4 = cubed - squared;
  1525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1527. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1528. return new Vector3(x, y, z);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1532. */
  1533. Vector3.Lerp = function (start, end, amount) {
  1534. var result = new Vector3(0, 0, 0);
  1535. Vector3.LerpToRef(start, end, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1540. */
  1541. Vector3.LerpToRef = function (start, end, amount, result) {
  1542. result.x = start.x + ((end.x - start.x) * amount);
  1543. result.y = start.y + ((end.y - start.y) * amount);
  1544. result.z = start.z + ((end.z - start.z) * amount);
  1545. };
  1546. /**
  1547. * Returns the dot product (float) between the vectors "left" and "right".
  1548. */
  1549. Vector3.Dot = function (left, right) {
  1550. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1551. };
  1552. /**
  1553. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1554. * The cross product is then orthogonal to both "left" and "right".
  1555. */
  1556. Vector3.Cross = function (left, right) {
  1557. var result = Vector3.Zero();
  1558. Vector3.CrossToRef(left, right, result);
  1559. return result;
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the cross product of "left" and "right".
  1563. * The cross product is then orthogonal to both "left" and "right".
  1564. */
  1565. Vector3.CrossToRef = function (left, right, result) {
  1566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1569. result.copyFrom(MathTmp.Vector3[0]);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 as the normalization of the passed vector.
  1573. */
  1574. Vector3.Normalize = function (vector) {
  1575. var result = Vector3.Zero();
  1576. Vector3.NormalizeToRef(vector, result);
  1577. return result;
  1578. };
  1579. /**
  1580. * Sets the passed vector "result" with the normalization of the passed first vector.
  1581. */
  1582. Vector3.NormalizeToRef = function (vector, result) {
  1583. result.copyFrom(vector);
  1584. result.normalize();
  1585. };
  1586. Vector3.Project = function (vector, world, transform, viewport) {
  1587. var cw = viewport.width;
  1588. var ch = viewport.height;
  1589. var cx = viewport.x;
  1590. var cy = viewport.y;
  1591. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1592. 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);
  1593. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1594. world.multiplyToRef(transform, matrix);
  1595. matrix.multiplyToRef(viewportMatrix, matrix);
  1596. return Vector3.TransformCoordinates(vector, matrix);
  1597. };
  1598. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.invert();
  1602. source.x = source.x / viewportWidth * 2 - 1;
  1603. source.y = -(source.y / viewportHeight * 2 - 1);
  1604. var vector = Vector3.TransformCoordinates(source, matrix);
  1605. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1606. if (MathTools.WithinEpsilon(num, 1.0)) {
  1607. vector = vector.scale(1.0 / num);
  1608. }
  1609. return vector;
  1610. };
  1611. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1612. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1613. world.multiplyToRef(view, matrix);
  1614. matrix.multiplyToRef(projection, matrix);
  1615. matrix.invert();
  1616. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1617. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1618. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1619. if (MathTools.WithinEpsilon(num, 1.0)) {
  1620. vector = vector.scale(1.0 / num);
  1621. }
  1622. return vector;
  1623. };
  1624. Vector3.Minimize = function (left, right) {
  1625. var min = left.clone();
  1626. min.MinimizeInPlace(right);
  1627. return min;
  1628. };
  1629. Vector3.Maximize = function (left, right) {
  1630. var max = left.clone();
  1631. max.MaximizeInPlace(right);
  1632. return max;
  1633. };
  1634. /**
  1635. * Returns the distance (float) between the vectors "value1" and "value2".
  1636. */
  1637. Vector3.Distance = function (value1, value2) {
  1638. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1639. };
  1640. /**
  1641. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.DistanceSquared = function (value1, value2) {
  1644. var x = value1.x - value2.x;
  1645. var y = value1.y - value2.y;
  1646. var z = value1.z - value2.z;
  1647. return (x * x) + (y * y) + (z * z);
  1648. };
  1649. /**
  1650. * Returns a new Vector3 located at the center between "value1" and "value2".
  1651. */
  1652. Vector3.Center = function (value1, value2) {
  1653. var center = value1.add(value2);
  1654. center.scaleInPlace(0.5);
  1655. return center;
  1656. };
  1657. /**
  1658. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1659. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1660. * to something in order to rotate it from its local system to the given target system.
  1661. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1662. * Returns a new Vector3.
  1663. */
  1664. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1665. var rotation = Vector3.Zero();
  1666. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1667. return rotation;
  1668. };
  1669. /**
  1670. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1671. */
  1672. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1673. var quat = MathTmp.Quaternion[0];
  1674. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1675. quat.toEulerAnglesToRef(ref);
  1676. };
  1677. return Vector3;
  1678. }());
  1679. BABYLON.Vector3 = Vector3;
  1680. //Vector4 class created for EulerAngle class conversion to Quaternion
  1681. var Vector4 = (function () {
  1682. /**
  1683. * Creates a Vector4 object from the passed floats.
  1684. */
  1685. function Vector4(x, y, z, w) {
  1686. this.x = x;
  1687. this.y = y;
  1688. this.z = z;
  1689. this.w = w;
  1690. }
  1691. /**
  1692. * Returns the string with the Vector4 coordinates.
  1693. */
  1694. Vector4.prototype.toString = function () {
  1695. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1696. };
  1697. /**
  1698. * Returns the string "Vector4".
  1699. */
  1700. Vector4.prototype.getClassName = function () {
  1701. return "Vector4";
  1702. };
  1703. /**
  1704. * Returns the Vector4 hash code.
  1705. */
  1706. Vector4.prototype.getHashCode = function () {
  1707. var hash = this.x || 0;
  1708. hash = (hash * 397) ^ (this.y || 0);
  1709. hash = (hash * 397) ^ (this.z || 0);
  1710. hash = (hash * 397) ^ (this.w || 0);
  1711. return hash;
  1712. };
  1713. // Operators
  1714. /**
  1715. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1716. */
  1717. Vector4.prototype.asArray = function () {
  1718. var result = [];
  1719. this.toArray(result, 0);
  1720. return result;
  1721. };
  1722. /**
  1723. * Populates the passed array from the passed index with the Vector4 coordinates.
  1724. * Returns the Vector4.
  1725. */
  1726. Vector4.prototype.toArray = function (array, index) {
  1727. if (index === undefined) {
  1728. index = 0;
  1729. }
  1730. array[index] = this.x;
  1731. array[index + 1] = this.y;
  1732. array[index + 2] = this.z;
  1733. array[index + 3] = this.w;
  1734. return this;
  1735. };
  1736. /**
  1737. * Adds the passed vector to the current Vector4.
  1738. * Returns the updated Vector4.
  1739. */
  1740. Vector4.prototype.addInPlace = function (otherVector) {
  1741. this.x += otherVector.x;
  1742. this.y += otherVector.y;
  1743. this.z += otherVector.z;
  1744. this.w += otherVector.w;
  1745. return this;
  1746. };
  1747. /**
  1748. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1749. */
  1750. Vector4.prototype.add = function (otherVector) {
  1751. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1752. };
  1753. /**
  1754. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1755. * Returns the current Vector4.
  1756. */
  1757. Vector4.prototype.addToRef = function (otherVector, result) {
  1758. result.x = this.x + otherVector.x;
  1759. result.y = this.y + otherVector.y;
  1760. result.z = this.z + otherVector.z;
  1761. result.w = this.w + otherVector.w;
  1762. return this;
  1763. };
  1764. /**
  1765. * Subtract in place the passed vector from the current Vector4.
  1766. * Returns the updated Vector4.
  1767. */
  1768. Vector4.prototype.subtractInPlace = function (otherVector) {
  1769. this.x -= otherVector.x;
  1770. this.y -= otherVector.y;
  1771. this.z -= otherVector.z;
  1772. this.w -= otherVector.w;
  1773. return this;
  1774. };
  1775. /**
  1776. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1777. */
  1778. Vector4.prototype.subtract = function (otherVector) {
  1779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1780. };
  1781. /**
  1782. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1783. * Returns the current Vector4.
  1784. */
  1785. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1786. result.x = this.x - otherVector.x;
  1787. result.y = this.y - otherVector.y;
  1788. result.z = this.z - otherVector.z;
  1789. result.w = this.w - otherVector.w;
  1790. return this;
  1791. };
  1792. /**
  1793. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1794. */
  1795. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1796. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1797. };
  1798. /**
  1799. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. * Returns the current Vector4.
  1801. */
  1802. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1803. result.x = this.x - x;
  1804. result.y = this.y - y;
  1805. result.z = this.z - z;
  1806. result.w = this.w - w;
  1807. return this;
  1808. };
  1809. /**
  1810. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1811. */
  1812. Vector4.prototype.negate = function () {
  1813. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1814. };
  1815. /**
  1816. * Multiplies the current Vector4 coordinates by scale (float).
  1817. * Returns the updated Vector4.
  1818. */
  1819. Vector4.prototype.scaleInPlace = function (scale) {
  1820. this.x *= scale;
  1821. this.y *= scale;
  1822. this.z *= scale;
  1823. this.w *= scale;
  1824. return this;
  1825. };
  1826. /**
  1827. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1828. */
  1829. Vector4.prototype.scale = function (scale) {
  1830. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1831. };
  1832. /**
  1833. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1834. * Returns the current Vector4.
  1835. */
  1836. Vector4.prototype.scaleToRef = function (scale, result) {
  1837. result.x = this.x * scale;
  1838. result.y = this.y * scale;
  1839. result.z = this.z * scale;
  1840. result.w = this.w * scale;
  1841. return this;
  1842. };
  1843. /**
  1844. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1845. */
  1846. Vector4.prototype.equals = function (otherVector) {
  1847. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1851. */
  1852. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1853. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1854. return otherVector
  1855. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1856. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1857. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1858. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1859. };
  1860. /**
  1861. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1864. return this.x === x && this.y === y && this.z === z && this.w === w;
  1865. };
  1866. /**
  1867. * Multiplies in place the current Vector4 by the passed one.
  1868. * Returns the updated Vector4.
  1869. */
  1870. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1871. this.x *= otherVector.x;
  1872. this.y *= otherVector.y;
  1873. this.z *= otherVector.z;
  1874. this.w *= otherVector.w;
  1875. return this;
  1876. };
  1877. /**
  1878. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1879. */
  1880. Vector4.prototype.multiply = function (otherVector) {
  1881. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1882. };
  1883. /**
  1884. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1885. * Returns the current Vector4.
  1886. */
  1887. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1888. result.x = this.x * otherVector.x;
  1889. result.y = this.y * otherVector.y;
  1890. result.z = this.z * otherVector.z;
  1891. result.w = this.w * otherVector.w;
  1892. return this;
  1893. };
  1894. /**
  1895. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1896. */
  1897. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1898. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1902. */
  1903. Vector4.prototype.divide = function (otherVector) {
  1904. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1905. };
  1906. /**
  1907. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1908. * Returns the current Vector4.
  1909. */
  1910. Vector4.prototype.divideToRef = function (otherVector, result) {
  1911. result.x = this.x / otherVector.x;
  1912. result.y = this.y / otherVector.y;
  1913. result.z = this.z / otherVector.z;
  1914. result.w = this.w / otherVector.w;
  1915. return this;
  1916. };
  1917. /**
  1918. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1919. */
  1920. Vector4.prototype.MinimizeInPlace = function (other) {
  1921. if (other.x < this.x)
  1922. this.x = other.x;
  1923. if (other.y < this.y)
  1924. this.y = other.y;
  1925. if (other.z < this.z)
  1926. this.z = other.z;
  1927. if (other.w < this.w)
  1928. this.w = other.w;
  1929. return this;
  1930. };
  1931. /**
  1932. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1933. */
  1934. Vector4.prototype.MaximizeInPlace = function (other) {
  1935. if (other.x > this.x)
  1936. this.x = other.x;
  1937. if (other.y > this.y)
  1938. this.y = other.y;
  1939. if (other.z > this.z)
  1940. this.z = other.z;
  1941. if (other.w > this.w)
  1942. this.w = other.w;
  1943. return this;
  1944. };
  1945. // Properties
  1946. /**
  1947. * Returns the Vector4 length (float).
  1948. */
  1949. Vector4.prototype.length = function () {
  1950. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1951. };
  1952. /**
  1953. * Returns the Vector4 squared length (float).
  1954. */
  1955. Vector4.prototype.lengthSquared = function () {
  1956. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. // Methods
  1959. /**
  1960. * Normalizes in place the Vector4.
  1961. * Returns the updated Vector4.
  1962. */
  1963. Vector4.prototype.normalize = function () {
  1964. var len = this.length();
  1965. if (len === 0)
  1966. return this;
  1967. var num = 1.0 / len;
  1968. this.x *= num;
  1969. this.y *= num;
  1970. this.z *= num;
  1971. this.w *= num;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1976. */
  1977. Vector4.prototype.toVector3 = function () {
  1978. return new Vector3(this.x, this.y, this.z);
  1979. };
  1980. /**
  1981. * Returns a new Vector4 copied from the current one.
  1982. */
  1983. Vector4.prototype.clone = function () {
  1984. return new Vector4(this.x, this.y, this.z, this.w);
  1985. };
  1986. /**
  1987. * Updates the current Vector4 with the passed one coordinates.
  1988. * Returns the updated Vector4.
  1989. */
  1990. Vector4.prototype.copyFrom = function (source) {
  1991. this.x = source.x;
  1992. this.y = source.y;
  1993. this.z = source.z;
  1994. this.w = source.w;
  1995. return this;
  1996. };
  1997. /**
  1998. * Updates the current Vector4 coordinates with the passed floats.
  1999. * Returns the updated Vector4.
  2000. */
  2001. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. this.w = w;
  2006. return this;
  2007. };
  2008. /**
  2009. * Updates the current Vector4 coordinates with the passed floats.
  2010. * Returns the updated Vector4.
  2011. */
  2012. Vector4.prototype.set = function (x, y, z, w) {
  2013. return this.copyFromFloats(x, y, z, w);
  2014. };
  2015. // Statics
  2016. /**
  2017. * Returns a new Vector4 set from the starting index of the passed array.
  2018. */
  2019. Vector4.FromArray = function (array, offset) {
  2020. if (!offset) {
  2021. offset = 0;
  2022. }
  2023. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2024. };
  2025. /**
  2026. * Updates the passed vector "result" from the starting index of the passed array.
  2027. */
  2028. Vector4.FromArrayToRef = function (array, offset, result) {
  2029. result.x = array[offset];
  2030. result.y = array[offset + 1];
  2031. result.z = array[offset + 2];
  2032. result.w = array[offset + 3];
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2036. */
  2037. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2038. Vector4.FromArrayToRef(array, offset, result);
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" coordinates from the passed floats.
  2042. */
  2043. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2044. result.x = x;
  2045. result.y = y;
  2046. result.z = z;
  2047. result.w = w;
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2051. */
  2052. Vector4.Zero = function () {
  2053. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2057. */
  2058. Vector4.One = function () {
  2059. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2060. };
  2061. /**
  2062. * Returns a new normalized Vector4 from the passed one.
  2063. */
  2064. Vector4.Normalize = function (vector) {
  2065. var result = Vector4.Zero();
  2066. Vector4.NormalizeToRef(vector, result);
  2067. return result;
  2068. };
  2069. /**
  2070. * Updates the passed vector "result" from the normalization of the passed one.
  2071. */
  2072. Vector4.NormalizeToRef = function (vector, result) {
  2073. result.copyFrom(vector);
  2074. result.normalize();
  2075. };
  2076. Vector4.Minimize = function (left, right) {
  2077. var min = left.clone();
  2078. min.MinimizeInPlace(right);
  2079. return min;
  2080. };
  2081. Vector4.Maximize = function (left, right) {
  2082. var max = left.clone();
  2083. max.MaximizeInPlace(right);
  2084. return max;
  2085. };
  2086. /**
  2087. * Returns the distance (float) between the vectors "value1" and "value2".
  2088. */
  2089. Vector4.Distance = function (value1, value2) {
  2090. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2091. };
  2092. /**
  2093. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.DistanceSquared = function (value1, value2) {
  2096. var x = value1.x - value2.x;
  2097. var y = value1.y - value2.y;
  2098. var z = value1.z - value2.z;
  2099. var w = value1.w - value2.w;
  2100. return (x * x) + (y * y) + (z * z) + (w * w);
  2101. };
  2102. /**
  2103. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2104. */
  2105. Vector4.Center = function (value1, value2) {
  2106. var center = value1.add(value2);
  2107. center.scaleInPlace(0.5);
  2108. return center;
  2109. };
  2110. /**
  2111. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2112. * This methods computes transformed normalized direction vectors only.
  2113. */
  2114. Vector4.TransformNormal = function (vector, transformation) {
  2115. var result = Vector4.Zero();
  2116. Vector4.TransformNormalToRef(vector, transformation, result);
  2117. return result;
  2118. };
  2119. /**
  2120. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2121. * This methods computes transformed normalized direction vectors only.
  2122. */
  2123. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2124. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2125. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2126. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2127. result.x = x;
  2128. result.y = y;
  2129. result.z = z;
  2130. result.w = vector.w;
  2131. };
  2132. /**
  2133. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2134. * This methods computes transformed normalized direction vectors only.
  2135. */
  2136. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2137. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2138. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2139. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2140. result.w = w;
  2141. };
  2142. return Vector4;
  2143. }());
  2144. BABYLON.Vector4 = Vector4;
  2145. var Size = (function () {
  2146. /**
  2147. * Creates a Size object from the passed width and height (floats).
  2148. */
  2149. function Size(width, height) {
  2150. this.width = width;
  2151. this.height = height;
  2152. }
  2153. // Returns a string with the Size width and height.
  2154. Size.prototype.toString = function () {
  2155. return "{W: " + this.width + ", H: " + this.height + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Size"
  2159. */
  2160. Size.prototype.getClassName = function () {
  2161. return "Size";
  2162. };
  2163. /**
  2164. * Returns the Size hash code.
  2165. */
  2166. Size.prototype.getHashCode = function () {
  2167. var hash = this.width || 0;
  2168. hash = (hash * 397) ^ (this.height || 0);
  2169. return hash;
  2170. };
  2171. /**
  2172. * Updates the current size from the passed one.
  2173. * Returns the updated Size.
  2174. */
  2175. Size.prototype.copyFrom = function (src) {
  2176. this.width = src.width;
  2177. this.height = src.height;
  2178. };
  2179. /**
  2180. * Updates in place the current Size from the passed floats.
  2181. * Returns the updated Size.
  2182. */
  2183. Size.prototype.copyFromFloats = function (width, height) {
  2184. this.width = width;
  2185. this.height = height;
  2186. return this;
  2187. };
  2188. /**
  2189. * Updates in place the current Size from the passed floats.
  2190. * Returns the updated Size.
  2191. */
  2192. Size.prototype.set = function (width, height) {
  2193. return this.copyFromFloats(width, height);
  2194. };
  2195. /**
  2196. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2197. */
  2198. Size.prototype.multiplyByFloats = function (w, h) {
  2199. return new Size(this.width * w, this.height * h);
  2200. };
  2201. /**
  2202. * Returns a new Size copied from the passed one.
  2203. */
  2204. Size.prototype.clone = function () {
  2205. return new Size(this.width, this.height);
  2206. };
  2207. /**
  2208. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2209. */
  2210. Size.prototype.equals = function (other) {
  2211. if (!other) {
  2212. return false;
  2213. }
  2214. return (this.width === other.width) && (this.height === other.height);
  2215. };
  2216. Object.defineProperty(Size.prototype, "surface", {
  2217. /**
  2218. * Returns the surface of the Size : width * height (float).
  2219. */
  2220. get: function () {
  2221. return this.width * this.height;
  2222. },
  2223. enumerable: true,
  2224. configurable: true
  2225. });
  2226. /**
  2227. * Returns a new Size set to (0.0, 0.0)
  2228. */
  2229. Size.Zero = function () {
  2230. return new Size(0.0, 0.0);
  2231. };
  2232. /**
  2233. * Returns a new Size set as the addition result of the current Size and the passed one.
  2234. */
  2235. Size.prototype.add = function (otherSize) {
  2236. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2237. return r;
  2238. };
  2239. /**
  2240. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2241. */
  2242. Size.prototype.subtract = function (otherSize) {
  2243. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2244. return r;
  2245. };
  2246. /**
  2247. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2248. */
  2249. Size.Lerp = function (start, end, amount) {
  2250. var w = start.width + ((end.width - start.width) * amount);
  2251. var h = start.height + ((end.height - start.height) * amount);
  2252. return new Size(w, h);
  2253. };
  2254. return Size;
  2255. }());
  2256. BABYLON.Size = Size;
  2257. var Quaternion = (function () {
  2258. /**
  2259. * Creates a new Quaternion from the passed floats.
  2260. */
  2261. function Quaternion(x, y, z, w) {
  2262. if (x === void 0) { x = 0.0; }
  2263. if (y === void 0) { y = 0.0; }
  2264. if (z === void 0) { z = 0.0; }
  2265. if (w === void 0) { w = 1.0; }
  2266. this.x = x;
  2267. this.y = y;
  2268. this.z = z;
  2269. this.w = w;
  2270. }
  2271. /**
  2272. * Returns a string with the Quaternion coordinates.
  2273. */
  2274. Quaternion.prototype.toString = function () {
  2275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2276. };
  2277. /**
  2278. * Returns the string "Quaternion".
  2279. */
  2280. Quaternion.prototype.getClassName = function () {
  2281. return "Quaternion";
  2282. };
  2283. /**
  2284. * Returns the Quaternion hash code.
  2285. */
  2286. Quaternion.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. hash = (hash * 397) ^ (this.z || 0);
  2290. hash = (hash * 397) ^ (this.w || 0);
  2291. return hash;
  2292. };
  2293. /**
  2294. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2295. */
  2296. Quaternion.prototype.asArray = function () {
  2297. return [this.x, this.y, this.z, this.w];
  2298. };
  2299. /**
  2300. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2301. */
  2302. Quaternion.prototype.equals = function (otherQuaternion) {
  2303. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2304. };
  2305. /**
  2306. * Returns a new Quaternion copied from the current one.
  2307. */
  2308. Quaternion.prototype.clone = function () {
  2309. return new Quaternion(this.x, this.y, this.z, this.w);
  2310. };
  2311. /**
  2312. * Updates the current Quaternion from the passed one coordinates.
  2313. * Returns the updated Quaterion.
  2314. */
  2315. Quaternion.prototype.copyFrom = function (other) {
  2316. this.x = other.x;
  2317. this.y = other.y;
  2318. this.z = other.z;
  2319. this.w = other.w;
  2320. return this;
  2321. };
  2322. /**
  2323. * Updates the current Quaternion from the passed float coordinates.
  2324. * Returns the updated Quaterion.
  2325. */
  2326. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2327. this.x = x;
  2328. this.y = y;
  2329. this.z = z;
  2330. this.w = w;
  2331. return this;
  2332. };
  2333. /**
  2334. * Updates the current Quaternion from the passed float coordinates.
  2335. * Returns the updated Quaterion.
  2336. */
  2337. Quaternion.prototype.set = function (x, y, z, w) {
  2338. return this.copyFromFloats(x, y, z, w);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2342. */
  2343. Quaternion.prototype.add = function (other) {
  2344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2348. */
  2349. Quaternion.prototype.subtract = 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 set by multiplying the current Quaterion coordinates by the float "scale".
  2354. */
  2355. Quaternion.prototype.scale = function (value) {
  2356. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2360. */
  2361. Quaternion.prototype.multiply = function (q1) {
  2362. var result = new Quaternion(0, 0, 0, 1.0);
  2363. this.multiplyToRef(q1, result);
  2364. return result;
  2365. };
  2366. /**
  2367. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2368. * Returns the current Quaternion.
  2369. */
  2370. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2371. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2372. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2373. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2374. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2375. result.copyFromFloats(x, y, z, w);
  2376. return this;
  2377. };
  2378. /**
  2379. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.multiplyInPlace = function (q1) {
  2383. this.multiplyToRef(q1, this);
  2384. return this;
  2385. };
  2386. /**
  2387. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2388. * Returns the current Quaternion.
  2389. */
  2390. Quaternion.prototype.conjugateToRef = function (ref) {
  2391. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2392. return this;
  2393. };
  2394. /**
  2395. * Conjugates in place the current Quaternion.
  2396. * Returns the updated Quaternion.
  2397. */
  2398. Quaternion.prototype.conjugateInPlace = function () {
  2399. this.x *= -1;
  2400. this.y *= -1;
  2401. this.z *= -1;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2406. */
  2407. Quaternion.prototype.conjugate = function () {
  2408. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2409. return result;
  2410. };
  2411. /**
  2412. * Returns the Quaternion length (float).
  2413. */
  2414. Quaternion.prototype.length = function () {
  2415. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2416. };
  2417. /**
  2418. * Normalize in place the current Quaternion.
  2419. * Returns the updated Quaternion.
  2420. */
  2421. Quaternion.prototype.normalize = function () {
  2422. var length = 1.0 / this.length();
  2423. this.x *= length;
  2424. this.y *= length;
  2425. this.z *= length;
  2426. this.w *= length;
  2427. return this;
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2431. */
  2432. Quaternion.prototype.toEulerAngles = function (order) {
  2433. if (order === void 0) { order = "YZX"; }
  2434. var result = Vector3.Zero();
  2435. this.toEulerAnglesToRef(result, order);
  2436. return result;
  2437. };
  2438. /**
  2439. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2440. * Returns the current Quaternion.
  2441. */
  2442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2443. if (order === void 0) { order = "YZX"; }
  2444. var qz = this.z;
  2445. var qx = this.x;
  2446. var qy = this.y;
  2447. var qw = this.w;
  2448. var sqw = qw * qw;
  2449. var sqz = qz * qz;
  2450. var sqx = qx * qx;
  2451. var sqy = qy * qy;
  2452. var zAxisY = qy * qz - qx * qw;
  2453. var limit = .4999999;
  2454. if (zAxisY < -limit) {
  2455. result.y = 2 * Math.atan2(qy, qw);
  2456. result.x = Math.PI / 2;
  2457. result.z = 0;
  2458. }
  2459. else if (zAxisY > limit) {
  2460. result.y = 2 * Math.atan2(qy, qw);
  2461. result.x = -Math.PI / 2;
  2462. result.z = 0;
  2463. }
  2464. else {
  2465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2468. }
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the passed rotation matrix with the current Quaternion values.
  2473. * Returns the current Quaternion.
  2474. */
  2475. Quaternion.prototype.toRotationMatrix = function (result) {
  2476. var xx = this.x * this.x;
  2477. var yy = this.y * this.y;
  2478. var zz = this.z * this.z;
  2479. var xy = this.x * this.y;
  2480. var zw = this.z * this.w;
  2481. var zx = this.z * this.x;
  2482. var yw = this.y * this.w;
  2483. var yz = this.y * this.z;
  2484. var xw = this.x * this.w;
  2485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2486. result.m[1] = 2.0 * (xy + zw);
  2487. result.m[2] = 2.0 * (zx - yw);
  2488. result.m[3] = 0;
  2489. result.m[4] = 2.0 * (xy - zw);
  2490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2491. result.m[6] = 2.0 * (yz + xw);
  2492. result.m[7] = 0;
  2493. result.m[8] = 2.0 * (zx + yw);
  2494. result.m[9] = 2.0 * (yz - xw);
  2495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2496. result.m[11] = 0;
  2497. result.m[12] = 0;
  2498. result.m[13] = 0;
  2499. result.m[14] = 0;
  2500. result.m[15] = 1.0;
  2501. result._markAsUpdated();
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion from the passed rotation matrix values.
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2509. Quaternion.FromRotationMatrixToRef(matrix, this);
  2510. return this;
  2511. };
  2512. // Statics
  2513. /**
  2514. * Returns a new Quaternion set from the passed rotation matrix values.
  2515. */
  2516. Quaternion.FromRotationMatrix = function (matrix) {
  2517. var result = new Quaternion();
  2518. Quaternion.FromRotationMatrixToRef(matrix, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2523. */
  2524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2525. var data = matrix.m;
  2526. var m11 = data[0], m12 = data[4], m13 = data[8];
  2527. var m21 = data[1], m22 = data[5], m23 = data[9];
  2528. var m31 = data[2], m32 = data[6], m33 = data[10];
  2529. var trace = m11 + m22 + m33;
  2530. var s;
  2531. if (trace > 0) {
  2532. s = 0.5 / Math.sqrt(trace + 1.0);
  2533. result.w = 0.25 / s;
  2534. result.x = (m32 - m23) * s;
  2535. result.y = (m13 - m31) * s;
  2536. result.z = (m21 - m12) * s;
  2537. }
  2538. else if (m11 > m22 && m11 > m33) {
  2539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2540. result.w = (m32 - m23) / s;
  2541. result.x = 0.25 * s;
  2542. result.y = (m12 + m21) / s;
  2543. result.z = (m13 + m31) / s;
  2544. }
  2545. else if (m22 > m33) {
  2546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2547. result.w = (m13 - m31) / s;
  2548. result.x = (m12 + m21) / s;
  2549. result.y = 0.25 * s;
  2550. result.z = (m23 + m32) / s;
  2551. }
  2552. else {
  2553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2554. result.w = (m21 - m12) / s;
  2555. result.x = (m13 + m31) / s;
  2556. result.y = (m23 + m32) / s;
  2557. result.z = 0.25 * s;
  2558. }
  2559. };
  2560. /**
  2561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2562. */
  2563. Quaternion.Zero = function () {
  2564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion as the inverted current Quaternion.
  2568. */
  2569. Quaternion.Inverse = function (q) {
  2570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2571. };
  2572. /**
  2573. * Returns the identity Quaternion.
  2574. */
  2575. Quaternion.Identity = function () {
  2576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2577. };
  2578. Quaternion.IsIdentity = function (quaternion) {
  2579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2580. };
  2581. /**
  2582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2583. */
  2584. Quaternion.RotationAxis = function (axis, angle) {
  2585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2586. };
  2587. /**
  2588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2591. var sin = Math.sin(angle / 2);
  2592. axis.normalize();
  2593. result.w = Math.cos(angle / 2);
  2594. result.x = axis.x * sin;
  2595. result.y = axis.y * sin;
  2596. result.z = axis.z * sin;
  2597. return result;
  2598. };
  2599. /**
  2600. * Retuns a new Quaternion set from the starting index of the passed array.
  2601. */
  2602. Quaternion.FromArray = function (array, offset) {
  2603. if (!offset) {
  2604. offset = 0;
  2605. }
  2606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2607. };
  2608. /**
  2609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2610. */
  2611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2612. var q = new Quaternion();
  2613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2614. return q;
  2615. };
  2616. /**
  2617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2618. */
  2619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2621. var halfRoll = roll * 0.5;
  2622. var halfPitch = pitch * 0.5;
  2623. var halfYaw = yaw * 0.5;
  2624. var sinRoll = Math.sin(halfRoll);
  2625. var cosRoll = Math.cos(halfRoll);
  2626. var sinPitch = Math.sin(halfPitch);
  2627. var cosPitch = Math.cos(halfPitch);
  2628. var sinYaw = Math.sin(halfYaw);
  2629. var cosYaw = Math.cos(halfYaw);
  2630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2634. };
  2635. /**
  2636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2637. */
  2638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2639. var result = new Quaternion();
  2640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2641. return result;
  2642. };
  2643. /**
  2644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2645. */
  2646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2647. // Produces a quaternion from Euler angles in the z-x-z orientation
  2648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2650. var halfBeta = beta * 0.5;
  2651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2655. };
  2656. /**
  2657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2658. * cf to Vector3.RotationFromAxis() documentation.
  2659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2660. */
  2661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2664. return quat;
  2665. };
  2666. /**
  2667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2668. * cf to Vector3.RotationFromAxis() documentation.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. */
  2671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2672. var rotMat = MathTmp.Matrix[0];
  2673. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2674. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2675. };
  2676. Quaternion.Slerp = function (left, right, amount) {
  2677. var result = Quaternion.Identity();
  2678. Quaternion.SlerpToRef(left, right, amount, result);
  2679. return result;
  2680. };
  2681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2682. var num2;
  2683. var num3;
  2684. var num = amount;
  2685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2686. var flag = false;
  2687. if (num4 < 0) {
  2688. flag = true;
  2689. num4 = -num4;
  2690. }
  2691. if (num4 > 0.999999) {
  2692. num3 = 1 - num;
  2693. num2 = flag ? -num : num;
  2694. }
  2695. else {
  2696. var num5 = Math.acos(num4);
  2697. var num6 = (1.0 / Math.sin(num5));
  2698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2700. }
  2701. result.x = (num3 * left.x) + (num2 * right.x);
  2702. result.y = (num3 * left.y) + (num2 * right.y);
  2703. result.z = (num3 * left.z) + (num2 * right.z);
  2704. result.w = (num3 * left.w) + (num2 * right.w);
  2705. };
  2706. /**
  2707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2708. */
  2709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2710. var squared = amount * amount;
  2711. var cubed = amount * squared;
  2712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2714. var part3 = (cubed - (2.0 * squared)) + amount;
  2715. var part4 = cubed - squared;
  2716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2720. return new Quaternion(x, y, z, w);
  2721. };
  2722. return Quaternion;
  2723. }());
  2724. BABYLON.Quaternion = Quaternion;
  2725. var Matrix = (function () {
  2726. function Matrix() {
  2727. this.m = new Float32Array(16);
  2728. this._markAsUpdated();
  2729. }
  2730. Matrix.prototype._markAsUpdated = function () {
  2731. this.updateFlag = Matrix._updateFlagSeed++;
  2732. };
  2733. // Properties
  2734. /**
  2735. * Boolean : True is the matrix is the identity matrix
  2736. */
  2737. Matrix.prototype.isIdentity = function () {
  2738. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2739. return false;
  2740. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2741. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2742. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2743. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2744. return false;
  2745. return true;
  2746. };
  2747. /**
  2748. * Returns the matrix determinant (float).
  2749. */
  2750. Matrix.prototype.determinant = function () {
  2751. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2752. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2753. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2754. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2755. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2756. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2757. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2758. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2759. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2760. };
  2761. // Methods
  2762. /**
  2763. * Returns the matrix underlying array.
  2764. */
  2765. Matrix.prototype.toArray = function () {
  2766. return this.m;
  2767. };
  2768. /**
  2769. * Returns the matrix underlying array.
  2770. */
  2771. Matrix.prototype.asArray = function () {
  2772. return this.toArray();
  2773. };
  2774. /**
  2775. * Inverts in place the Matrix.
  2776. * Returns the Matrix inverted.
  2777. */
  2778. Matrix.prototype.invert = function () {
  2779. this.invertToRef(this);
  2780. return this;
  2781. };
  2782. /**
  2783. * Sets all the matrix elements to zero.
  2784. * Returns the Matrix.
  2785. */
  2786. Matrix.prototype.reset = function () {
  2787. for (var index = 0; index < 16; index++) {
  2788. this.m[index] = 0.0;
  2789. }
  2790. this._markAsUpdated();
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2795. */
  2796. Matrix.prototype.add = function (other) {
  2797. var result = new Matrix();
  2798. this.addToRef(other, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2803. * Returns the Matrix.
  2804. */
  2805. Matrix.prototype.addToRef = function (other, result) {
  2806. for (var index = 0; index < 16; index++) {
  2807. result.m[index] = this.m[index] + other.m[index];
  2808. }
  2809. result._markAsUpdated();
  2810. return this;
  2811. };
  2812. /**
  2813. * Adds in place the passed matrix to the current Matrix.
  2814. * Returns the updated Matrix.
  2815. */
  2816. Matrix.prototype.addToSelf = function (other) {
  2817. for (var index = 0; index < 16; index++) {
  2818. this.m[index] += other.m[index];
  2819. }
  2820. this._markAsUpdated();
  2821. return this;
  2822. };
  2823. /**
  2824. * Sets the passed matrix with the current inverted Matrix.
  2825. * Returns the unmodified current Matrix.
  2826. */
  2827. Matrix.prototype.invertToRef = function (other) {
  2828. var l1 = this.m[0];
  2829. var l2 = this.m[1];
  2830. var l3 = this.m[2];
  2831. var l4 = this.m[3];
  2832. var l5 = this.m[4];
  2833. var l6 = this.m[5];
  2834. var l7 = this.m[6];
  2835. var l8 = this.m[7];
  2836. var l9 = this.m[8];
  2837. var l10 = this.m[9];
  2838. var l11 = this.m[10];
  2839. var l12 = this.m[11];
  2840. var l13 = this.m[12];
  2841. var l14 = this.m[13];
  2842. var l15 = this.m[14];
  2843. var l16 = this.m[15];
  2844. var l17 = (l11 * l16) - (l12 * l15);
  2845. var l18 = (l10 * l16) - (l12 * l14);
  2846. var l19 = (l10 * l15) - (l11 * l14);
  2847. var l20 = (l9 * l16) - (l12 * l13);
  2848. var l21 = (l9 * l15) - (l11 * l13);
  2849. var l22 = (l9 * l14) - (l10 * l13);
  2850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2855. var l28 = (l7 * l16) - (l8 * l15);
  2856. var l29 = (l6 * l16) - (l8 * l14);
  2857. var l30 = (l6 * l15) - (l7 * l14);
  2858. var l31 = (l5 * l16) - (l8 * l13);
  2859. var l32 = (l5 * l15) - (l7 * l13);
  2860. var l33 = (l5 * l14) - (l6 * l13);
  2861. var l34 = (l7 * l12) - (l8 * l11);
  2862. var l35 = (l6 * l12) - (l8 * l10);
  2863. var l36 = (l6 * l11) - (l7 * l10);
  2864. var l37 = (l5 * l12) - (l8 * l9);
  2865. var l38 = (l5 * l11) - (l7 * l9);
  2866. var l39 = (l5 * l10) - (l6 * l9);
  2867. other.m[0] = l23 * l27;
  2868. other.m[4] = l24 * l27;
  2869. other.m[8] = l25 * l27;
  2870. other.m[12] = l26 * l27;
  2871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2883. other._markAsUpdated();
  2884. return this;
  2885. };
  2886. /**
  2887. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2888. * Returns the updated Matrix.
  2889. */
  2890. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2891. this.m[12] = x;
  2892. this.m[13] = y;
  2893. this.m[14] = z;
  2894. this._markAsUpdated();
  2895. return this;
  2896. };
  2897. /**
  2898. * Inserts the translation vector in the current Matrix.
  2899. * Returns the updated Matrix.
  2900. */
  2901. Matrix.prototype.setTranslation = function (vector3) {
  2902. this.m[12] = vector3.x;
  2903. this.m[13] = vector3.y;
  2904. this.m[14] = vector3.z;
  2905. this._markAsUpdated();
  2906. return this;
  2907. };
  2908. /**
  2909. * Returns a new Vector3 as the extracted translation from the Matrix.
  2910. */
  2911. Matrix.prototype.getTranslation = function () {
  2912. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2913. };
  2914. /**
  2915. * Fill a Vector3 with the extracted translation from the Matrix.
  2916. */
  2917. Matrix.prototype.getTranslationToRef = function (result) {
  2918. result.x = this.m[12];
  2919. result.y = this.m[13];
  2920. result.z = this.m[14];
  2921. return this;
  2922. };
  2923. /**
  2924. * Remove rotation and scaling part from the Matrix.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.removeRotationAndScaling = function () {
  2928. this.setRowFromFloats(0, 1, 0, 0, 0);
  2929. this.setRowFromFloats(1, 0, 1, 0, 0);
  2930. this.setRowFromFloats(2, 0, 0, 1, 0);
  2931. return this;
  2932. };
  2933. /**
  2934. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2935. */
  2936. Matrix.prototype.multiply = function (other) {
  2937. var result = new Matrix();
  2938. this.multiplyToRef(other, result);
  2939. return result;
  2940. };
  2941. /**
  2942. * Updates the current Matrix from the passed one values.
  2943. * Returns the updated Matrix.
  2944. */
  2945. Matrix.prototype.copyFrom = function (other) {
  2946. for (var index = 0; index < 16; index++) {
  2947. this.m[index] = other.m[index];
  2948. }
  2949. this._markAsUpdated();
  2950. return this;
  2951. };
  2952. /**
  2953. * Populates the passed array from the starting index with the Matrix values.
  2954. * Returns the Matrix.
  2955. */
  2956. Matrix.prototype.copyToArray = function (array, offset) {
  2957. if (offset === void 0) { offset = 0; }
  2958. for (var index = 0; index < 16; index++) {
  2959. array[offset + index] = this.m[index];
  2960. }
  2961. return this;
  2962. };
  2963. /**
  2964. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2965. */
  2966. Matrix.prototype.multiplyToRef = function (other, result) {
  2967. this.multiplyToArray(other, result.m, 0);
  2968. result._markAsUpdated();
  2969. return this;
  2970. };
  2971. /**
  2972. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2973. */
  2974. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2975. var tm0 = this.m[0];
  2976. var tm1 = this.m[1];
  2977. var tm2 = this.m[2];
  2978. var tm3 = this.m[3];
  2979. var tm4 = this.m[4];
  2980. var tm5 = this.m[5];
  2981. var tm6 = this.m[6];
  2982. var tm7 = this.m[7];
  2983. var tm8 = this.m[8];
  2984. var tm9 = this.m[9];
  2985. var tm10 = this.m[10];
  2986. var tm11 = this.m[11];
  2987. var tm12 = this.m[12];
  2988. var tm13 = this.m[13];
  2989. var tm14 = this.m[14];
  2990. var tm15 = this.m[15];
  2991. var om0 = other.m[0];
  2992. var om1 = other.m[1];
  2993. var om2 = other.m[2];
  2994. var om3 = other.m[3];
  2995. var om4 = other.m[4];
  2996. var om5 = other.m[5];
  2997. var om6 = other.m[6];
  2998. var om7 = other.m[7];
  2999. var om8 = other.m[8];
  3000. var om9 = other.m[9];
  3001. var om10 = other.m[10];
  3002. var om11 = other.m[11];
  3003. var om12 = other.m[12];
  3004. var om13 = other.m[13];
  3005. var om14 = other.m[14];
  3006. var om15 = other.m[15];
  3007. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3008. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3009. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3010. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3011. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3012. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3013. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3014. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3015. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3016. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3017. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3018. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3019. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3020. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3021. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3022. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3023. return this;
  3024. };
  3025. /**
  3026. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3027. */
  3028. Matrix.prototype.equals = function (value) {
  3029. return value &&
  3030. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3031. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3032. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3033. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3034. };
  3035. /**
  3036. * Returns a new Matrix from the current Matrix.
  3037. */
  3038. Matrix.prototype.clone = function () {
  3039. 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]);
  3040. };
  3041. /**
  3042. * Returns the string "Matrix"
  3043. */
  3044. Matrix.prototype.getClassName = function () {
  3045. return "Matrix";
  3046. };
  3047. /**
  3048. * Returns the Matrix hash code.
  3049. */
  3050. Matrix.prototype.getHashCode = function () {
  3051. var hash = this.m[0] || 0;
  3052. for (var i = 1; i < 16; i++) {
  3053. hash = (hash * 397) ^ (this.m[i] || 0);
  3054. }
  3055. return hash;
  3056. };
  3057. /**
  3058. * Decomposes the current Matrix into :
  3059. * - a scale vector3 passed as a reference to update,
  3060. * - a rotation quaternion passed as a reference to update,
  3061. * - a translation vector3 passed as a reference to update.
  3062. * Returns the boolean `true`.
  3063. */
  3064. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3065. translation.x = this.m[12];
  3066. translation.y = this.m[13];
  3067. translation.z = this.m[14];
  3068. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3069. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3070. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3071. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3072. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3073. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3074. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3075. rotation.x = 0;
  3076. rotation.y = 0;
  3077. rotation.z = 0;
  3078. rotation.w = 1;
  3079. return false;
  3080. }
  3081. 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]);
  3082. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3083. return true;
  3084. };
  3085. /**
  3086. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3087. */
  3088. Matrix.prototype.getRotationMatrix = function () {
  3089. var result = Matrix.Identity();
  3090. this.getRotationMatrixToRef(result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3095. * Returns the current Matrix.
  3096. */
  3097. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3098. var m = this.m;
  3099. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3100. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3101. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3102. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3103. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3104. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3105. 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);
  3106. return this;
  3107. };
  3108. // Statics
  3109. /**
  3110. * Returns a new Matrix set from the starting index of the passed array.
  3111. */
  3112. Matrix.FromArray = function (array, offset) {
  3113. var result = new Matrix();
  3114. if (!offset) {
  3115. offset = 0;
  3116. }
  3117. Matrix.FromArrayToRef(array, offset, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed "result" matrix from the starting index of the passed array.
  3122. */
  3123. Matrix.FromArrayToRef = function (array, offset, result) {
  3124. for (var index = 0; index < 16; index++) {
  3125. result.m[index] = array[index + offset];
  3126. }
  3127. result._markAsUpdated();
  3128. };
  3129. /**
  3130. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3131. */
  3132. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3133. for (var index = 0; index < 16; index++) {
  3134. result.m[index] = array[index + offset] * scale;
  3135. }
  3136. result._markAsUpdated();
  3137. };
  3138. /**
  3139. * Sets the passed matrix "result" with the 16 passed floats.
  3140. */
  3141. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3142. result.m[0] = initialM11;
  3143. result.m[1] = initialM12;
  3144. result.m[2] = initialM13;
  3145. result.m[3] = initialM14;
  3146. result.m[4] = initialM21;
  3147. result.m[5] = initialM22;
  3148. result.m[6] = initialM23;
  3149. result.m[7] = initialM24;
  3150. result.m[8] = initialM31;
  3151. result.m[9] = initialM32;
  3152. result.m[10] = initialM33;
  3153. result.m[11] = initialM34;
  3154. result.m[12] = initialM41;
  3155. result.m[13] = initialM42;
  3156. result.m[14] = initialM43;
  3157. result.m[15] = initialM44;
  3158. result._markAsUpdated();
  3159. };
  3160. /**
  3161. * Returns the index-th row of the current matrix as a new Vector4.
  3162. */
  3163. Matrix.prototype.getRow = function (index) {
  3164. if (index < 0 || index > 3) {
  3165. return null;
  3166. }
  3167. var i = index * 4;
  3168. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3169. };
  3170. /**
  3171. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3172. * Returns the updated Matrix.
  3173. */
  3174. Matrix.prototype.setRow = function (index, row) {
  3175. if (index < 0 || index > 3) {
  3176. return this;
  3177. }
  3178. var i = index * 4;
  3179. this.m[i + 0] = row.x;
  3180. this.m[i + 1] = row.y;
  3181. this.m[i + 2] = row.z;
  3182. this.m[i + 3] = row.w;
  3183. this._markAsUpdated();
  3184. return this;
  3185. };
  3186. /**
  3187. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3188. * Returns the updated Matrix.
  3189. */
  3190. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3191. if (index < 0 || index > 3) {
  3192. return this;
  3193. }
  3194. var i = index * 4;
  3195. this.m[i + 0] = x;
  3196. this.m[i + 1] = y;
  3197. this.m[i + 2] = z;
  3198. this.m[i + 3] = w;
  3199. this._markAsUpdated();
  3200. return this;
  3201. };
  3202. /**
  3203. * Returns a new Matrix set from the 16 passed floats.
  3204. */
  3205. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3206. var result = new Matrix();
  3207. result.m[0] = initialM11;
  3208. result.m[1] = initialM12;
  3209. result.m[2] = initialM13;
  3210. result.m[3] = initialM14;
  3211. result.m[4] = initialM21;
  3212. result.m[5] = initialM22;
  3213. result.m[6] = initialM23;
  3214. result.m[7] = initialM24;
  3215. result.m[8] = initialM31;
  3216. result.m[9] = initialM32;
  3217. result.m[10] = initialM33;
  3218. result.m[11] = initialM34;
  3219. result.m[12] = initialM41;
  3220. result.m[13] = initialM42;
  3221. result.m[14] = initialM43;
  3222. result.m[15] = initialM44;
  3223. return result;
  3224. };
  3225. /**
  3226. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3227. */
  3228. Matrix.Compose = function (scale, rotation, translation) {
  3229. var result = Matrix.Identity();
  3230. Matrix.ComposeToRef(scale, rotation, translation, result);
  3231. return result;
  3232. };
  3233. /**
  3234. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3235. */
  3236. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3237. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3238. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3239. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3240. result.setTranslation(translation);
  3241. };
  3242. /**
  3243. * Returns a new indentity Matrix.
  3244. */
  3245. Matrix.Identity = function () {
  3246. 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);
  3247. };
  3248. /**
  3249. * Sets the passed "result" as an identity matrix.
  3250. */
  3251. Matrix.IdentityToRef = function (result) {
  3252. 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);
  3253. };
  3254. /**
  3255. * Returns a new zero Matrix.
  3256. */
  3257. Matrix.Zero = function () {
  3258. 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);
  3259. };
  3260. /**
  3261. * Returns a new rotation matrix for "angle" radians around the X axis.
  3262. */
  3263. Matrix.RotationX = function (angle) {
  3264. var result = new Matrix();
  3265. Matrix.RotationXToRef(angle, result);
  3266. return result;
  3267. };
  3268. /**
  3269. * Returns a new Matrix as the passed inverted one.
  3270. */
  3271. Matrix.Invert = function (source) {
  3272. var result = new Matrix();
  3273. source.invertToRef(result);
  3274. return result;
  3275. };
  3276. /**
  3277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3278. */
  3279. Matrix.RotationXToRef = function (angle, result) {
  3280. var s = Math.sin(angle);
  3281. var c = Math.cos(angle);
  3282. result.m[0] = 1.0;
  3283. result.m[15] = 1.0;
  3284. result.m[5] = c;
  3285. result.m[10] = c;
  3286. result.m[9] = -s;
  3287. result.m[6] = s;
  3288. result.m[1] = 0.0;
  3289. result.m[2] = 0.0;
  3290. result.m[3] = 0.0;
  3291. result.m[4] = 0.0;
  3292. result.m[7] = 0.0;
  3293. result.m[8] = 0.0;
  3294. result.m[11] = 0.0;
  3295. result.m[12] = 0.0;
  3296. result.m[13] = 0.0;
  3297. result.m[14] = 0.0;
  3298. result._markAsUpdated();
  3299. };
  3300. /**
  3301. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3302. */
  3303. Matrix.RotationY = function (angle) {
  3304. var result = new Matrix();
  3305. Matrix.RotationYToRef(angle, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3310. */
  3311. Matrix.RotationYToRef = function (angle, result) {
  3312. var s = Math.sin(angle);
  3313. var c = Math.cos(angle);
  3314. result.m[5] = 1.0;
  3315. result.m[15] = 1.0;
  3316. result.m[0] = c;
  3317. result.m[2] = -s;
  3318. result.m[8] = s;
  3319. result.m[10] = c;
  3320. result.m[1] = 0.0;
  3321. result.m[3] = 0.0;
  3322. result.m[4] = 0.0;
  3323. result.m[6] = 0.0;
  3324. result.m[7] = 0.0;
  3325. result.m[9] = 0.0;
  3326. result.m[11] = 0.0;
  3327. result.m[12] = 0.0;
  3328. result.m[13] = 0.0;
  3329. result.m[14] = 0.0;
  3330. result._markAsUpdated();
  3331. };
  3332. /**
  3333. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3334. */
  3335. Matrix.RotationZ = function (angle) {
  3336. var result = new Matrix();
  3337. Matrix.RotationZToRef(angle, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3342. */
  3343. Matrix.RotationZToRef = function (angle, result) {
  3344. var s = Math.sin(angle);
  3345. var c = Math.cos(angle);
  3346. result.m[10] = 1.0;
  3347. result.m[15] = 1.0;
  3348. result.m[0] = c;
  3349. result.m[1] = s;
  3350. result.m[4] = -s;
  3351. result.m[5] = c;
  3352. result.m[2] = 0.0;
  3353. result.m[3] = 0.0;
  3354. result.m[6] = 0.0;
  3355. result.m[7] = 0.0;
  3356. result.m[8] = 0.0;
  3357. result.m[9] = 0.0;
  3358. result.m[11] = 0.0;
  3359. result.m[12] = 0.0;
  3360. result.m[13] = 0.0;
  3361. result.m[14] = 0.0;
  3362. result._markAsUpdated();
  3363. };
  3364. /**
  3365. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3366. */
  3367. Matrix.RotationAxis = function (axis, angle) {
  3368. var result = Matrix.Zero();
  3369. Matrix.RotationAxisToRef(axis, angle, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3374. */
  3375. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3376. var s = Math.sin(-angle);
  3377. var c = Math.cos(-angle);
  3378. var c1 = 1 - c;
  3379. axis.normalize();
  3380. result.m[0] = (axis.x * axis.x) * c1 + c;
  3381. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3382. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3383. result.m[3] = 0.0;
  3384. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3385. result.m[5] = (axis.y * axis.y) * c1 + c;
  3386. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3387. result.m[7] = 0.0;
  3388. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3389. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3390. result.m[10] = (axis.z * axis.z) * c1 + c;
  3391. result.m[11] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3397. */
  3398. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3399. var result = new Matrix();
  3400. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3405. */
  3406. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3407. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3408. this._tempQuaternion.toRotationMatrix(result);
  3409. };
  3410. /**
  3411. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3412. */
  3413. Matrix.Scaling = function (x, y, z) {
  3414. var result = Matrix.Zero();
  3415. Matrix.ScalingToRef(x, y, z, result);
  3416. return result;
  3417. };
  3418. /**
  3419. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3420. */
  3421. Matrix.ScalingToRef = function (x, y, z, result) {
  3422. result.m[0] = x;
  3423. result.m[1] = 0.0;
  3424. result.m[2] = 0.0;
  3425. result.m[3] = 0.0;
  3426. result.m[4] = 0.0;
  3427. result.m[5] = y;
  3428. result.m[6] = 0.0;
  3429. result.m[7] = 0.0;
  3430. result.m[8] = 0.0;
  3431. result.m[9] = 0.0;
  3432. result.m[10] = z;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result.m[15] = 1.0;
  3438. result._markAsUpdated();
  3439. };
  3440. /**
  3441. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3442. */
  3443. Matrix.Translation = function (x, y, z) {
  3444. var result = Matrix.Identity();
  3445. Matrix.TranslationToRef(x, y, z, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3450. */
  3451. Matrix.TranslationToRef = function (x, y, z, result) {
  3452. 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);
  3453. };
  3454. /**
  3455. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3456. */
  3457. Matrix.Lerp = function (startValue, endValue, gradient) {
  3458. var result = Matrix.Zero();
  3459. for (var index = 0; index < 16; index++) {
  3460. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3461. }
  3462. result._markAsUpdated();
  3463. return result;
  3464. };
  3465. /**
  3466. * Returns a new Matrix whose values are computed by :
  3467. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3468. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3469. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3470. */
  3471. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3472. var startScale = new Vector3(0, 0, 0);
  3473. var startRotation = new Quaternion();
  3474. var startTranslation = new Vector3(0, 0, 0);
  3475. startValue.decompose(startScale, startRotation, startTranslation);
  3476. var endScale = new Vector3(0, 0, 0);
  3477. var endRotation = new Quaternion();
  3478. var endTranslation = new Vector3(0, 0, 0);
  3479. endValue.decompose(endScale, endRotation, endTranslation);
  3480. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3481. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3482. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3483. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3484. };
  3485. /**
  3486. * 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".
  3487. * This methods works for a Left-Handed system.
  3488. */
  3489. Matrix.LookAtLH = function (eye, target, up) {
  3490. var result = Matrix.Zero();
  3491. Matrix.LookAtLHToRef(eye, target, up, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * 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".
  3496. * This methods works for a Left-Handed system.
  3497. */
  3498. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3499. // Z axis
  3500. target.subtractToRef(eye, this._zAxis);
  3501. this._zAxis.normalize();
  3502. // X axis
  3503. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3504. if (this._xAxis.lengthSquared() === 0) {
  3505. this._xAxis.x = 1.0;
  3506. }
  3507. else {
  3508. this._xAxis.normalize();
  3509. }
  3510. // Y axis
  3511. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3512. this._yAxis.normalize();
  3513. // Eye angles
  3514. var ex = -Vector3.Dot(this._xAxis, eye);
  3515. var ey = -Vector3.Dot(this._yAxis, eye);
  3516. var ez = -Vector3.Dot(this._zAxis, eye);
  3517. 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);
  3518. };
  3519. /**
  3520. * 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".
  3521. * This methods works for a Right-Handed system.
  3522. */
  3523. Matrix.LookAtRH = function (eye, target, up) {
  3524. var result = Matrix.Zero();
  3525. Matrix.LookAtRHToRef(eye, target, up, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * 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".
  3530. * This methods works for a Left-Handed system.
  3531. */
  3532. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3533. // Z axis
  3534. eye.subtractToRef(target, this._zAxis);
  3535. this._zAxis.normalize();
  3536. // X axis
  3537. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3538. if (this._xAxis.lengthSquared() === 0) {
  3539. this._xAxis.x = 1.0;
  3540. }
  3541. else {
  3542. this._xAxis.normalize();
  3543. }
  3544. // Y axis
  3545. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3546. this._yAxis.normalize();
  3547. // Eye angles
  3548. var ex = -Vector3.Dot(this._xAxis, eye);
  3549. var ey = -Vector3.Dot(this._yAxis, eye);
  3550. var ez = -Vector3.Dot(this._zAxis, eye);
  3551. 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);
  3552. };
  3553. /**
  3554. * 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.
  3555. */
  3556. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3557. var matrix = Matrix.Zero();
  3558. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3559. return matrix;
  3560. };
  3561. /**
  3562. * 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.
  3563. */
  3564. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3565. var n = znear;
  3566. var f = zfar;
  3567. var a = 2.0 / width;
  3568. var b = 2.0 / height;
  3569. var c = 2.0 / (f - n);
  3570. var d = -(f + n) / (f - n);
  3571. 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);
  3572. };
  3573. /**
  3574. * 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.
  3575. */
  3576. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * 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.
  3583. */
  3584. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3585. var n = znear;
  3586. var f = zfar;
  3587. var a = 2.0 / (right - left);
  3588. var b = 2.0 / (top - bottom);
  3589. var c = 2.0 / (f - n);
  3590. var d = -(f + n) / (f - n);
  3591. var i0 = (left + right) / (left - right);
  3592. var i1 = (top + bottom) / (bottom - top);
  3593. 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);
  3594. };
  3595. /**
  3596. * 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.
  3597. */
  3598. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * 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.
  3605. */
  3606. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3607. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3608. result.m[10] *= -1.0;
  3609. };
  3610. /**
  3611. * 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.
  3612. */
  3613. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3614. var matrix = Matrix.Zero();
  3615. var n = znear;
  3616. var f = zfar;
  3617. var a = 2.0 * n / width;
  3618. var b = 2.0 * n / height;
  3619. var c = (f + n) / (f - n);
  3620. var d = -2.0 * f * n / (f - n);
  3621. 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);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * 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.
  3626. */
  3627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3628. var matrix = Matrix.Zero();
  3629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3630. return matrix;
  3631. };
  3632. /**
  3633. * 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.
  3634. */
  3635. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3636. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3637. var n = znear;
  3638. var f = zfar;
  3639. var t = 1.0 / (Math.tan(fov * 0.5));
  3640. var a = isVerticalFovFixed ? (t / aspect) : t;
  3641. var b = isVerticalFovFixed ? t : (t * aspect);
  3642. var c = (f + n) / (f - n);
  3643. var d = -2.0 * f * n / (f - n);
  3644. 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);
  3645. };
  3646. /**
  3647. * 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.
  3648. */
  3649. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3650. var matrix = Matrix.Zero();
  3651. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3652. return matrix;
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3658. //alternatively this could be expressed as:
  3659. // m = PerspectiveFovLHToRef
  3660. // m[10] *= -1.0;
  3661. // m[11] *= -1.0;
  3662. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3663. var n = znear;
  3664. var f = zfar;
  3665. var t = 1.0 / (Math.tan(fov * 0.5));
  3666. var a = isVerticalFovFixed ? (t / aspect) : t;
  3667. var b = isVerticalFovFixed ? t : (t * aspect);
  3668. var c = -(f + n) / (f - n);
  3669. var d = -2 * f * n / (f - n);
  3670. 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);
  3671. };
  3672. /**
  3673. * 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.
  3674. */
  3675. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3676. if (rightHanded === void 0) { rightHanded = false; }
  3677. var rightHandedFactor = rightHanded ? -1 : 1;
  3678. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3679. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3680. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3681. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3682. var xScale = 2.0 / (leftTan + rightTan);
  3683. var yScale = 2.0 / (upTan + downTan);
  3684. result.m[0] = xScale;
  3685. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3686. result.m[5] = yScale;
  3687. result.m[6] = result.m[7] = 0.0;
  3688. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3689. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3690. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3691. result.m[10] = -zfar / (znear - zfar);
  3692. result.m[11] = 1.0 * rightHandedFactor;
  3693. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3694. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3695. // result.m[14] = (znear * zfar) / (znear - zfar);
  3696. result._markAsUpdated();
  3697. };
  3698. /**
  3699. * Returns the final transformation matrix : world * view * projection * viewport
  3700. */
  3701. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3702. var cw = viewport.width;
  3703. var ch = viewport.height;
  3704. var cx = viewport.x;
  3705. var cy = viewport.y;
  3706. 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);
  3707. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3708. };
  3709. /**
  3710. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3711. */
  3712. Matrix.GetAsMatrix2x2 = function (matrix) {
  3713. return new Float32Array([
  3714. matrix.m[0], matrix.m[1],
  3715. matrix.m[4], matrix.m[5]
  3716. ]);
  3717. };
  3718. /**
  3719. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3720. */
  3721. Matrix.GetAsMatrix3x3 = function (matrix) {
  3722. return new Float32Array([
  3723. matrix.m[0], matrix.m[1], matrix.m[2],
  3724. matrix.m[4], matrix.m[5], matrix.m[6],
  3725. matrix.m[8], matrix.m[9], matrix.m[10]
  3726. ]);
  3727. };
  3728. /**
  3729. * Compute the transpose of the passed Matrix.
  3730. * Returns a new Matrix.
  3731. */
  3732. Matrix.Transpose = function (matrix) {
  3733. var result = new Matrix();
  3734. result.m[0] = matrix.m[0];
  3735. result.m[1] = matrix.m[4];
  3736. result.m[2] = matrix.m[8];
  3737. result.m[3] = matrix.m[12];
  3738. result.m[4] = matrix.m[1];
  3739. result.m[5] = matrix.m[5];
  3740. result.m[6] = matrix.m[9];
  3741. result.m[7] = matrix.m[13];
  3742. result.m[8] = matrix.m[2];
  3743. result.m[9] = matrix.m[6];
  3744. result.m[10] = matrix.m[10];
  3745. result.m[11] = matrix.m[14];
  3746. result.m[12] = matrix.m[3];
  3747. result.m[13] = matrix.m[7];
  3748. result.m[14] = matrix.m[11];
  3749. result.m[15] = matrix.m[15];
  3750. return result;
  3751. };
  3752. /**
  3753. * Returns a new Matrix as the reflection matrix across the passed plane.
  3754. */
  3755. Matrix.Reflection = function (plane) {
  3756. var matrix = new Matrix();
  3757. Matrix.ReflectionToRef(plane, matrix);
  3758. return matrix;
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3762. */
  3763. Matrix.ReflectionToRef = function (plane, result) {
  3764. plane.normalize();
  3765. var x = plane.normal.x;
  3766. var y = plane.normal.y;
  3767. var z = plane.normal.z;
  3768. var temp = -2 * x;
  3769. var temp2 = -2 * y;
  3770. var temp3 = -2 * z;
  3771. result.m[0] = (temp * x) + 1;
  3772. result.m[1] = temp2 * x;
  3773. result.m[2] = temp3 * x;
  3774. result.m[3] = 0.0;
  3775. result.m[4] = temp * y;
  3776. result.m[5] = (temp2 * y) + 1;
  3777. result.m[6] = temp3 * y;
  3778. result.m[7] = 0.0;
  3779. result.m[8] = temp * z;
  3780. result.m[9] = temp2 * z;
  3781. result.m[10] = (temp3 * z) + 1;
  3782. result.m[11] = 0.0;
  3783. result.m[12] = temp * plane.d;
  3784. result.m[13] = temp2 * plane.d;
  3785. result.m[14] = temp3 * plane.d;
  3786. result.m[15] = 1.0;
  3787. result._markAsUpdated();
  3788. };
  3789. /**
  3790. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3791. */
  3792. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3793. result.m[0] = xaxis.x;
  3794. result.m[1] = xaxis.y;
  3795. result.m[2] = xaxis.z;
  3796. result.m[3] = 0.0;
  3797. result.m[4] = yaxis.x;
  3798. result.m[5] = yaxis.y;
  3799. result.m[6] = yaxis.z;
  3800. result.m[7] = 0.0;
  3801. result.m[8] = zaxis.x;
  3802. result.m[9] = zaxis.y;
  3803. result.m[10] = zaxis.z;
  3804. result.m[11] = 0.0;
  3805. result.m[12] = 0.0;
  3806. result.m[13] = 0.0;
  3807. result.m[14] = 0.0;
  3808. result.m[15] = 1.0;
  3809. result._markAsUpdated();
  3810. };
  3811. /**
  3812. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3813. */
  3814. Matrix.FromQuaternionToRef = function (quat, result) {
  3815. var xx = quat.x * quat.x;
  3816. var yy = quat.y * quat.y;
  3817. var zz = quat.z * quat.z;
  3818. var xy = quat.x * quat.y;
  3819. var zw = quat.z * quat.w;
  3820. var zx = quat.z * quat.x;
  3821. var yw = quat.y * quat.w;
  3822. var yz = quat.y * quat.z;
  3823. var xw = quat.x * quat.w;
  3824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3825. result.m[1] = 2.0 * (xy + zw);
  3826. result.m[2] = 2.0 * (zx - yw);
  3827. result.m[3] = 0.0;
  3828. result.m[4] = 2.0 * (xy - zw);
  3829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3830. result.m[6] = 2.0 * (yz + xw);
  3831. result.m[7] = 0.0;
  3832. result.m[8] = 2.0 * (zx + yw);
  3833. result.m[9] = 2.0 * (yz - xw);
  3834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3835. result.m[11] = 0.0;
  3836. result.m[12] = 0.0;
  3837. result.m[13] = 0.0;
  3838. result.m[14] = 0.0;
  3839. result.m[15] = 1.0;
  3840. result._markAsUpdated();
  3841. };
  3842. return Matrix;
  3843. }());
  3844. Matrix._tempQuaternion = new Quaternion();
  3845. Matrix._xAxis = Vector3.Zero();
  3846. Matrix._yAxis = Vector3.Zero();
  3847. Matrix._zAxis = Vector3.Zero();
  3848. Matrix._updateFlagSeed = 0;
  3849. BABYLON.Matrix = Matrix;
  3850. var Plane = (function () {
  3851. /**
  3852. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3853. */
  3854. function Plane(a, b, c, d) {
  3855. this.normal = new Vector3(a, b, c);
  3856. this.d = d;
  3857. }
  3858. /**
  3859. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3860. */
  3861. Plane.prototype.asArray = function () {
  3862. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3863. };
  3864. // Methods
  3865. /**
  3866. * Returns a new plane copied from the current Plane.
  3867. */
  3868. Plane.prototype.clone = function () {
  3869. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3870. };
  3871. /**
  3872. * Returns the string "Plane".
  3873. */
  3874. Plane.prototype.getClassName = function () {
  3875. return "Plane";
  3876. };
  3877. /**
  3878. * Returns the Plane hash code.
  3879. */
  3880. Plane.prototype.getHashCode = function () {
  3881. var hash = this.normal.getHashCode();
  3882. hash = (hash * 397) ^ (this.d || 0);
  3883. return hash;
  3884. };
  3885. /**
  3886. * Normalize the current Plane in place.
  3887. * Returns the updated Plane.
  3888. */
  3889. Plane.prototype.normalize = function () {
  3890. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3891. var magnitude = 0.0;
  3892. if (norm !== 0) {
  3893. magnitude = 1.0 / norm;
  3894. }
  3895. this.normal.x *= magnitude;
  3896. this.normal.y *= magnitude;
  3897. this.normal.z *= magnitude;
  3898. this.d *= magnitude;
  3899. return this;
  3900. };
  3901. /**
  3902. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3903. */
  3904. Plane.prototype.transform = function (transformation) {
  3905. var transposedMatrix = Matrix.Transpose(transformation);
  3906. var x = this.normal.x;
  3907. var y = this.normal.y;
  3908. var z = this.normal.z;
  3909. var d = this.d;
  3910. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3911. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3912. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3913. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3914. return new Plane(normalX, normalY, normalZ, finalD);
  3915. };
  3916. /**
  3917. * Returns the dot product (float) of the point coordinates and the plane normal.
  3918. */
  3919. Plane.prototype.dotCoordinate = function (point) {
  3920. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3921. };
  3922. /**
  3923. * Updates the current Plane from the plane defined by the three passed points.
  3924. * Returns the updated Plane.
  3925. */
  3926. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3927. var x1 = point2.x - point1.x;
  3928. var y1 = point2.y - point1.y;
  3929. var z1 = point2.z - point1.z;
  3930. var x2 = point3.x - point1.x;
  3931. var y2 = point3.y - point1.y;
  3932. var z2 = point3.z - point1.z;
  3933. var yz = (y1 * z2) - (z1 * y2);
  3934. var xz = (z1 * x2) - (x1 * z2);
  3935. var xy = (x1 * y2) - (y1 * x2);
  3936. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3937. var invPyth;
  3938. if (pyth !== 0) {
  3939. invPyth = 1.0 / pyth;
  3940. }
  3941. else {
  3942. invPyth = 0.0;
  3943. }
  3944. this.normal.x = yz * invPyth;
  3945. this.normal.y = xz * invPyth;
  3946. this.normal.z = xy * invPyth;
  3947. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3948. return this;
  3949. };
  3950. /**
  3951. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3952. */
  3953. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3954. var dot = Vector3.Dot(this.normal, direction);
  3955. return (dot <= epsilon);
  3956. };
  3957. /**
  3958. * Returns the signed distance (float) from the passed point to the Plane.
  3959. */
  3960. Plane.prototype.signedDistanceTo = function (point) {
  3961. return Vector3.Dot(point, this.normal) + this.d;
  3962. };
  3963. // Statics
  3964. /**
  3965. * Returns a new Plane from the passed array.
  3966. */
  3967. Plane.FromArray = function (array) {
  3968. return new Plane(array[0], array[1], array[2], array[3]);
  3969. };
  3970. /**
  3971. * Returns a new Plane defined by the three passed points.
  3972. */
  3973. Plane.FromPoints = function (point1, point2, point3) {
  3974. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3975. result.copyFromPoints(point1, point2, point3);
  3976. return result;
  3977. };
  3978. /**
  3979. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3980. * Note : the vector "normal" is updated because normalized.
  3981. */
  3982. Plane.FromPositionAndNormal = function (origin, normal) {
  3983. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3984. normal.normalize();
  3985. result.normal = normal;
  3986. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3987. return result;
  3988. };
  3989. /**
  3990. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3991. */
  3992. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3993. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3994. return Vector3.Dot(point, normal) + d;
  3995. };
  3996. return Plane;
  3997. }());
  3998. BABYLON.Plane = Plane;
  3999. var Viewport = (function () {
  4000. /**
  4001. * Creates a Viewport object located at (x, y) and sized (width, height).
  4002. */
  4003. function Viewport(x, y, width, height) {
  4004. this.x = x;
  4005. this.y = y;
  4006. this.width = width;
  4007. this.height = height;
  4008. }
  4009. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  4010. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4011. };
  4012. /**
  4013. * Returns a new Viewport copied from the current one.
  4014. */
  4015. Viewport.prototype.clone = function () {
  4016. return new Viewport(this.x, this.y, this.width, this.height);
  4017. };
  4018. return Viewport;
  4019. }());
  4020. BABYLON.Viewport = Viewport;
  4021. var Frustum = (function () {
  4022. function Frustum() {
  4023. }
  4024. /**
  4025. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4026. */
  4027. Frustum.GetPlanes = function (transform) {
  4028. var frustumPlanes = [];
  4029. for (var index = 0; index < 6; index++) {
  4030. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4031. }
  4032. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4033. return frustumPlanes;
  4034. };
  4035. /**
  4036. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4037. */
  4038. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4039. // Near
  4040. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4041. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4042. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4043. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4044. frustumPlanes[0].normalize();
  4045. // Far
  4046. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4047. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4048. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4049. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4050. frustumPlanes[1].normalize();
  4051. // Left
  4052. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4053. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4054. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4055. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4056. frustumPlanes[2].normalize();
  4057. // Right
  4058. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4059. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4060. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4061. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4062. frustumPlanes[3].normalize();
  4063. // Top
  4064. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4065. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4066. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4067. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4068. frustumPlanes[4].normalize();
  4069. // Bottom
  4070. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4071. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4072. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4073. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4074. frustumPlanes[5].normalize();
  4075. };
  4076. return Frustum;
  4077. }());
  4078. BABYLON.Frustum = Frustum;
  4079. var Space;
  4080. (function (Space) {
  4081. Space[Space["LOCAL"] = 0] = "LOCAL";
  4082. Space[Space["WORLD"] = 1] = "WORLD";
  4083. Space[Space["BONE"] = 2] = "BONE";
  4084. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4085. var Axis = (function () {
  4086. function Axis() {
  4087. }
  4088. return Axis;
  4089. }());
  4090. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4091. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4092. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4093. BABYLON.Axis = Axis;
  4094. ;
  4095. var BezierCurve = (function () {
  4096. function BezierCurve() {
  4097. }
  4098. /**
  4099. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4100. */
  4101. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4102. // Extract X (which is equal to time here)
  4103. var f0 = 1 - 3 * x2 + 3 * x1;
  4104. var f1 = 3 * x2 - 6 * x1;
  4105. var f2 = 3 * x1;
  4106. var refinedT = t;
  4107. for (var i = 0; i < 5; i++) {
  4108. var refinedT2 = refinedT * refinedT;
  4109. var refinedT3 = refinedT2 * refinedT;
  4110. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4111. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4112. refinedT -= (x - t) * slope;
  4113. refinedT = Math.min(1, Math.max(0, refinedT));
  4114. }
  4115. // Resolve cubic bezier for the given x
  4116. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4117. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4118. Math.pow(refinedT, 3);
  4119. };
  4120. return BezierCurve;
  4121. }());
  4122. BABYLON.BezierCurve = BezierCurve;
  4123. var Orientation;
  4124. (function (Orientation) {
  4125. Orientation[Orientation["CW"] = 0] = "CW";
  4126. Orientation[Orientation["CCW"] = 1] = "CCW";
  4127. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4128. var Angle = (function () {
  4129. /**
  4130. * Creates an Angle object of "radians" radians (float).
  4131. */
  4132. function Angle(radians) {
  4133. var _this = this;
  4134. /**
  4135. * Returns the Angle value in degrees (float).
  4136. */
  4137. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4138. /**
  4139. * Returns the Angle value in radians (float).
  4140. */
  4141. this.radians = function () { return _this._radians; };
  4142. this._radians = radians;
  4143. if (this._radians < 0.0)
  4144. this._radians += (2.0 * Math.PI);
  4145. }
  4146. /**
  4147. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4148. */
  4149. Angle.BetweenTwoPoints = function (a, b) {
  4150. var delta = b.subtract(a);
  4151. var theta = Math.atan2(delta.y, delta.x);
  4152. return new Angle(theta);
  4153. };
  4154. /**
  4155. * Returns a new Angle object from the passed float in radians.
  4156. */
  4157. Angle.FromRadians = function (radians) {
  4158. return new Angle(radians);
  4159. };
  4160. /**
  4161. * Returns a new Angle object from the passed float in degrees.
  4162. */
  4163. Angle.FromDegrees = function (degrees) {
  4164. return new Angle(degrees * Math.PI / 180.0);
  4165. };
  4166. return Angle;
  4167. }());
  4168. BABYLON.Angle = Angle;
  4169. var Arc2 = (function () {
  4170. /**
  4171. * Creates an Arc object from the three passed points : start, middle and end.
  4172. */
  4173. function Arc2(startPoint, midPoint, endPoint) {
  4174. this.startPoint = startPoint;
  4175. this.midPoint = midPoint;
  4176. this.endPoint = endPoint;
  4177. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4178. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4179. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4180. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4181. 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);
  4182. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4183. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4184. var a1 = this.startAngle.degrees();
  4185. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4186. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4187. // angles correction
  4188. if (a2 - a1 > +180.0)
  4189. a2 -= 360.0;
  4190. if (a2 - a1 < -180.0)
  4191. a2 += 360.0;
  4192. if (a3 - a2 > +180.0)
  4193. a3 -= 360.0;
  4194. if (a3 - a2 < -180.0)
  4195. a3 += 360.0;
  4196. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4197. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4198. }
  4199. return Arc2;
  4200. }());
  4201. BABYLON.Arc2 = Arc2;
  4202. var Path2 = (function () {
  4203. /**
  4204. * Creates a Path2 object from the starting 2D coordinates x and y.
  4205. */
  4206. function Path2(x, y) {
  4207. this._points = new Array();
  4208. this._length = 0.0;
  4209. this.closed = false;
  4210. this._points.push(new Vector2(x, y));
  4211. }
  4212. /**
  4213. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4214. * Returns the updated Path2.
  4215. */
  4216. Path2.prototype.addLineTo = function (x, y) {
  4217. if (closed) {
  4218. //Tools.Error("cannot add lines to closed paths");
  4219. return this;
  4220. }
  4221. var newPoint = new Vector2(x, y);
  4222. var previousPoint = this._points[this._points.length - 1];
  4223. this._points.push(newPoint);
  4224. this._length += newPoint.subtract(previousPoint).length();
  4225. return this;
  4226. };
  4227. /**
  4228. * 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.
  4229. * Returns the updated Path2.
  4230. */
  4231. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4232. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4233. if (closed) {
  4234. //Tools.Error("cannot add arcs to closed paths");
  4235. return this;
  4236. }
  4237. var startPoint = this._points[this._points.length - 1];
  4238. var midPoint = new Vector2(midX, midY);
  4239. var endPoint = new Vector2(endX, endY);
  4240. var arc = new Arc2(startPoint, midPoint, endPoint);
  4241. var increment = arc.angle.radians() / numberOfSegments;
  4242. if (arc.orientation === Orientation.CW)
  4243. increment *= -1;
  4244. var currentAngle = arc.startAngle.radians() + increment;
  4245. for (var i = 0; i < numberOfSegments; i++) {
  4246. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4247. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4248. this.addLineTo(x, y);
  4249. currentAngle += increment;
  4250. }
  4251. return this;
  4252. };
  4253. /**
  4254. * Closes the Path2.
  4255. * Returns the Path2.
  4256. */
  4257. Path2.prototype.close = function () {
  4258. this.closed = true;
  4259. return this;
  4260. };
  4261. /**
  4262. * Returns the Path2 total length (float).
  4263. */
  4264. Path2.prototype.length = function () {
  4265. var result = this._length;
  4266. if (!this.closed) {
  4267. var lastPoint = this._points[this._points.length - 1];
  4268. var firstPoint = this._points[0];
  4269. result += (firstPoint.subtract(lastPoint).length());
  4270. }
  4271. return result;
  4272. };
  4273. /**
  4274. * Returns the Path2 internal array of points.
  4275. */
  4276. Path2.prototype.getPoints = function () {
  4277. return this._points;
  4278. };
  4279. /**
  4280. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4281. */
  4282. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4283. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4284. //Tools.Error("normalized length position should be between 0 and 1.");
  4285. return Vector2.Zero();
  4286. }
  4287. var lengthPosition = normalizedLengthPosition * this.length();
  4288. var previousOffset = 0;
  4289. for (var i = 0; i < this._points.length; i++) {
  4290. var j = (i + 1) % this._points.length;
  4291. var a = this._points[i];
  4292. var b = this._points[j];
  4293. var bToA = b.subtract(a);
  4294. var nextOffset = (bToA.length() + previousOffset);
  4295. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4296. var dir = bToA.normalize();
  4297. var localOffset = lengthPosition - previousOffset;
  4298. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4299. }
  4300. previousOffset = nextOffset;
  4301. }
  4302. //Tools.Error("internal error");
  4303. return Vector2.Zero();
  4304. };
  4305. /**
  4306. * Returns a new Path2 starting at the coordinates (x, y).
  4307. */
  4308. Path2.StartingAt = function (x, y) {
  4309. return new Path2(x, y);
  4310. };
  4311. return Path2;
  4312. }());
  4313. BABYLON.Path2 = Path2;
  4314. var Path3D = (function () {
  4315. /**
  4316. * new Path3D(path, normal, raw)
  4317. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4318. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4319. * path : an array of Vector3, the curve axis of the Path3D
  4320. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4321. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4322. */
  4323. function Path3D(path, firstNormal, raw) {
  4324. this.path = path;
  4325. this._curve = new Array();
  4326. this._distances = new Array();
  4327. this._tangents = new Array();
  4328. this._normals = new Array();
  4329. this._binormals = new Array();
  4330. for (var p = 0; p < path.length; p++) {
  4331. this._curve[p] = path[p].clone(); // hard copy
  4332. }
  4333. this._raw = raw || false;
  4334. this._compute(firstNormal);
  4335. }
  4336. /**
  4337. * Returns the Path3D array of successive Vector3 designing its curve.
  4338. */
  4339. Path3D.prototype.getCurve = function () {
  4340. return this._curve;
  4341. };
  4342. /**
  4343. * Returns an array populated with tangent vectors on each Path3D curve point.
  4344. */
  4345. Path3D.prototype.getTangents = function () {
  4346. return this._tangents;
  4347. };
  4348. /**
  4349. * Returns an array populated with normal vectors on each Path3D curve point.
  4350. */
  4351. Path3D.prototype.getNormals = function () {
  4352. return this._normals;
  4353. };
  4354. /**
  4355. * Returns an array populated with binormal vectors on each Path3D curve point.
  4356. */
  4357. Path3D.prototype.getBinormals = function () {
  4358. return this._binormals;
  4359. };
  4360. /**
  4361. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4362. */
  4363. Path3D.prototype.getDistances = function () {
  4364. return this._distances;
  4365. };
  4366. /**
  4367. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4368. * Returns the same object updated.
  4369. */
  4370. Path3D.prototype.update = function (path, firstNormal) {
  4371. for (var p = 0; p < path.length; p++) {
  4372. this._curve[p].x = path[p].x;
  4373. this._curve[p].y = path[p].y;
  4374. this._curve[p].z = path[p].z;
  4375. }
  4376. this._compute(firstNormal);
  4377. return this;
  4378. };
  4379. // private function compute() : computes tangents, normals and binormals
  4380. Path3D.prototype._compute = function (firstNormal) {
  4381. var l = this._curve.length;
  4382. // first and last tangents
  4383. this._tangents[0] = this._getFirstNonNullVector(0);
  4384. if (!this._raw) {
  4385. this._tangents[0].normalize();
  4386. }
  4387. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4388. if (!this._raw) {
  4389. this._tangents[l - 1].normalize();
  4390. }
  4391. // normals and binormals at first point : arbitrary vector with _normalVector()
  4392. var tg0 = this._tangents[0];
  4393. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4394. this._normals[0] = pp0;
  4395. if (!this._raw) {
  4396. this._normals[0].normalize();
  4397. }
  4398. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4399. if (!this._raw) {
  4400. this._binormals[0].normalize();
  4401. }
  4402. this._distances[0] = 0.0;
  4403. // normals and binormals : next points
  4404. var prev; // previous vector (segment)
  4405. var cur; // current vector (segment)
  4406. var curTang; // current tangent
  4407. // previous normal
  4408. var prevBinor; // previous binormal
  4409. for (var i = 1; i < l; i++) {
  4410. // tangents
  4411. prev = this._getLastNonNullVector(i);
  4412. if (i < l - 1) {
  4413. cur = this._getFirstNonNullVector(i);
  4414. this._tangents[i] = prev.add(cur);
  4415. this._tangents[i].normalize();
  4416. }
  4417. this._distances[i] = this._distances[i - 1] + prev.length();
  4418. // normals and binormals
  4419. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4420. curTang = this._tangents[i];
  4421. prevBinor = this._binormals[i - 1];
  4422. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4423. if (!this._raw) {
  4424. this._normals[i].normalize();
  4425. }
  4426. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4427. if (!this._raw) {
  4428. this._binormals[i].normalize();
  4429. }
  4430. }
  4431. };
  4432. // private function getFirstNonNullVector(index)
  4433. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4434. Path3D.prototype._getFirstNonNullVector = function (index) {
  4435. var i = 1;
  4436. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4437. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4438. i++;
  4439. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4440. }
  4441. return nNVector;
  4442. };
  4443. // private function getLastNonNullVector(index)
  4444. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4445. Path3D.prototype._getLastNonNullVector = function (index) {
  4446. var i = 1;
  4447. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4448. while (nLVector.length() === 0 && index > i + 1) {
  4449. i++;
  4450. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4451. }
  4452. return nLVector;
  4453. };
  4454. // private function normalVector(v0, vt, va) :
  4455. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4456. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4457. Path3D.prototype._normalVector = function (v0, vt, va) {
  4458. var normal0;
  4459. var tgl = vt.length();
  4460. if (tgl === 0.0) {
  4461. tgl = 1.0;
  4462. }
  4463. if (va === undefined || va === null) {
  4464. var point;
  4465. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4466. point = new Vector3(0.0, -1.0, 0.0);
  4467. }
  4468. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4469. point = new Vector3(1.0, 0.0, 0.0);
  4470. }
  4471. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4472. point = new Vector3(0.0, 0.0, 1.0);
  4473. }
  4474. normal0 = Vector3.Cross(vt, point);
  4475. }
  4476. else {
  4477. normal0 = Vector3.Cross(vt, va);
  4478. Vector3.CrossToRef(normal0, vt, normal0);
  4479. }
  4480. normal0.normalize();
  4481. return normal0;
  4482. };
  4483. return Path3D;
  4484. }());
  4485. BABYLON.Path3D = Path3D;
  4486. var Curve3 = (function () {
  4487. /**
  4488. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4489. * A Curve3 is designed from a series of successive Vector3.
  4490. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4491. */
  4492. function Curve3(points) {
  4493. this._length = 0.0;
  4494. this._points = points;
  4495. this._length = this._computeLength(points);
  4496. }
  4497. /**
  4498. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4499. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4500. * @param v1 (Vector3) the control point
  4501. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4502. * @param nbPoints (integer) the wanted number of points in the curve
  4503. */
  4504. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4505. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4506. var bez = new Array();
  4507. var equation = function (t, val0, val1, val2) {
  4508. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4509. return res;
  4510. };
  4511. for (var i = 0; i <= nbPoints; i++) {
  4512. 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)));
  4513. }
  4514. return new Curve3(bez);
  4515. };
  4516. /**
  4517. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4518. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4519. * @param v1 (Vector3) the first control point
  4520. * @param v2 (Vector3) the second control point
  4521. * @param v3 (Vector3) the end point of the Cubic Bezier
  4522. * @param nbPoints (integer) the wanted number of points in the curve
  4523. */
  4524. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4525. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4526. var bez = new Array();
  4527. var equation = function (t, val0, val1, val2, val3) {
  4528. 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;
  4529. return res;
  4530. };
  4531. for (var i = 0; i <= nbPoints; i++) {
  4532. 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)));
  4533. }
  4534. return new Curve3(bez);
  4535. };
  4536. /**
  4537. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4538. * @param p1 (Vector3) the origin point of the Hermite Spline
  4539. * @param t1 (Vector3) the tangent vector at the origin point
  4540. * @param p2 (Vector3) the end point of the Hermite Spline
  4541. * @param t2 (Vector3) the tangent vector at the end point
  4542. * @param nbPoints (integer) the wanted number of points in the curve
  4543. */
  4544. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4545. var hermite = new Array();
  4546. var step = 1.0 / nbPoints;
  4547. for (var i = 0; i <= nbPoints; i++) {
  4548. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4549. }
  4550. return new Curve3(hermite);
  4551. };
  4552. /**
  4553. * Returns a Curve3 object along a CatmullRom Spline curve :
  4554. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4555. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4556. */
  4557. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4558. var totalPoints = new Array();
  4559. totalPoints.push(points[0].clone());
  4560. Array.prototype.push.apply(totalPoints, points);
  4561. totalPoints.push(points[points.length - 1].clone());
  4562. var catmullRom = new Array();
  4563. var step = 1.0 / nbPoints;
  4564. for (var i = 0; i < totalPoints.length - 3; i++) {
  4565. var amount = 0.0;
  4566. for (var c = 0; c < nbPoints; c++) {
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. amount += step;
  4569. }
  4570. }
  4571. i--;
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. return new Curve3(catmullRom);
  4574. };
  4575. /**
  4576. * Returns the Curve3 stored array of successive Vector3
  4577. */
  4578. Curve3.prototype.getPoints = function () {
  4579. return this._points;
  4580. };
  4581. /**
  4582. * Returns the computed length (float) of the curve.
  4583. */
  4584. Curve3.prototype.length = function () {
  4585. return this._length;
  4586. };
  4587. /**
  4588. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4589. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4590. * curveA and curveB keep unchanged.
  4591. */
  4592. Curve3.prototype.continue = function (curve) {
  4593. var lastPoint = this._points[this._points.length - 1];
  4594. var continuedPoints = this._points.slice();
  4595. var curvePoints = curve.getPoints();
  4596. for (var i = 1; i < curvePoints.length; i++) {
  4597. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4598. }
  4599. var continuedCurve = new Curve3(continuedPoints);
  4600. return continuedCurve;
  4601. };
  4602. Curve3.prototype._computeLength = function (path) {
  4603. var l = 0;
  4604. for (var i = 1; i < path.length; i++) {
  4605. l += (path[i].subtract(path[i - 1])).length();
  4606. }
  4607. return l;
  4608. };
  4609. return Curve3;
  4610. }());
  4611. BABYLON.Curve3 = Curve3;
  4612. // SphericalHarmonics
  4613. var SphericalHarmonics = (function () {
  4614. function SphericalHarmonics() {
  4615. this.L00 = Vector3.Zero();
  4616. this.L1_1 = Vector3.Zero();
  4617. this.L10 = Vector3.Zero();
  4618. this.L11 = Vector3.Zero();
  4619. this.L2_2 = Vector3.Zero();
  4620. this.L2_1 = Vector3.Zero();
  4621. this.L20 = Vector3.Zero();
  4622. this.L21 = Vector3.Zero();
  4623. this.L22 = Vector3.Zero();
  4624. }
  4625. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4626. var colorVector = new Vector3(color.r, color.g, color.b);
  4627. var c = colorVector.scale(deltaSolidAngle);
  4628. this.L00 = this.L00.add(c.scale(0.282095));
  4629. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4630. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4631. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4632. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4633. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4634. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4635. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4636. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4637. };
  4638. SphericalHarmonics.prototype.scale = function (scale) {
  4639. this.L00 = this.L00.scale(scale);
  4640. this.L1_1 = this.L1_1.scale(scale);
  4641. this.L10 = this.L10.scale(scale);
  4642. this.L11 = this.L11.scale(scale);
  4643. this.L2_2 = this.L2_2.scale(scale);
  4644. this.L2_1 = this.L2_1.scale(scale);
  4645. this.L20 = this.L20.scale(scale);
  4646. this.L21 = this.L21.scale(scale);
  4647. this.L22 = this.L22.scale(scale);
  4648. };
  4649. return SphericalHarmonics;
  4650. }());
  4651. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4652. // SphericalPolynomial
  4653. var SphericalPolynomial = (function () {
  4654. function SphericalPolynomial() {
  4655. this.x = Vector3.Zero();
  4656. this.y = Vector3.Zero();
  4657. this.z = Vector3.Zero();
  4658. this.xx = Vector3.Zero();
  4659. this.yy = Vector3.Zero();
  4660. this.zz = Vector3.Zero();
  4661. this.xy = Vector3.Zero();
  4662. this.yz = Vector3.Zero();
  4663. this.zx = Vector3.Zero();
  4664. }
  4665. SphericalPolynomial.prototype.addAmbient = function (color) {
  4666. var colorVector = new Vector3(color.r, color.g, color.b);
  4667. this.xx = this.xx.add(colorVector);
  4668. this.yy = this.yy.add(colorVector);
  4669. this.zz = this.zz.add(colorVector);
  4670. };
  4671. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4672. var result = new SphericalPolynomial();
  4673. result.x = harmonics.L11.scale(1.02333);
  4674. result.y = harmonics.L1_1.scale(1.02333);
  4675. result.z = harmonics.L10.scale(1.02333);
  4676. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4677. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4678. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4679. result.yz = harmonics.L2_1.scale(0.858086);
  4680. result.zx = harmonics.L21.scale(0.858086);
  4681. result.xy = harmonics.L2_2.scale(0.858086);
  4682. return result;
  4683. };
  4684. return SphericalPolynomial;
  4685. }());
  4686. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4687. // Vertex formats
  4688. var PositionNormalVertex = (function () {
  4689. function PositionNormalVertex(position, normal) {
  4690. if (position === void 0) { position = Vector3.Zero(); }
  4691. if (normal === void 0) { normal = Vector3.Up(); }
  4692. this.position = position;
  4693. this.normal = normal;
  4694. }
  4695. PositionNormalVertex.prototype.clone = function () {
  4696. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4697. };
  4698. return PositionNormalVertex;
  4699. }());
  4700. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4701. var PositionNormalTextureVertex = (function () {
  4702. function PositionNormalTextureVertex(position, normal, uv) {
  4703. if (position === void 0) { position = Vector3.Zero(); }
  4704. if (normal === void 0) { normal = Vector3.Up(); }
  4705. if (uv === void 0) { uv = Vector2.Zero(); }
  4706. this.position = position;
  4707. this.normal = normal;
  4708. this.uv = uv;
  4709. }
  4710. PositionNormalTextureVertex.prototype.clone = function () {
  4711. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4712. };
  4713. return PositionNormalTextureVertex;
  4714. }());
  4715. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4716. // Temporary pre-allocated objects for engine internal use
  4717. // usage in any internal function :
  4718. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4719. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4720. var Tmp = (function () {
  4721. function Tmp() {
  4722. }
  4723. return Tmp;
  4724. }());
  4725. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4726. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4727. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4728. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4729. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4730. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4731. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4732. Matrix.Zero(), Matrix.Zero(),
  4733. Matrix.Zero(), Matrix.Zero(),
  4734. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4735. BABYLON.Tmp = Tmp;
  4736. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4737. var MathTmp = (function () {
  4738. function MathTmp() {
  4739. }
  4740. return MathTmp;
  4741. }());
  4742. MathTmp.Vector3 = [Vector3.Zero()];
  4743. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4744. MathTmp.Quaternion = [Quaternion.Zero()];
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.math.js.map
  4747. //# sourceMappingURL=babylon.mixins.js.map
  4748. var BABYLON;
  4749. (function (BABYLON) {
  4750. function generateSerializableMember(type, sourceName) {
  4751. return function (target, propertyKey) {
  4752. if (!target.__serializableMembers) {
  4753. target.__serializableMembers = {};
  4754. }
  4755. if (!target.__serializableMembers[propertyKey]) {
  4756. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4757. }
  4758. };
  4759. }
  4760. function generateExpandMember(setCallback, targetKey) {
  4761. return function (target, propertyKey) {
  4762. var key = targetKey || ("_" + propertyKey);
  4763. Object.defineProperty(target, propertyKey, {
  4764. get: function () {
  4765. return this[key];
  4766. },
  4767. set: function (value) {
  4768. if (this[key] === value) {
  4769. return;
  4770. }
  4771. this[key] = value;
  4772. target[setCallback].apply(this);
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. };
  4778. }
  4779. function expandToProperty(callback, targetKey) {
  4780. return generateExpandMember(callback, targetKey);
  4781. }
  4782. BABYLON.expandToProperty = expandToProperty;
  4783. function serialize(sourceName) {
  4784. return generateSerializableMember(0, sourceName); // value member
  4785. }
  4786. BABYLON.serialize = serialize;
  4787. function serializeAsTexture(sourceName) {
  4788. return generateSerializableMember(1, sourceName); // texture member
  4789. }
  4790. BABYLON.serializeAsTexture = serializeAsTexture;
  4791. function serializeAsColor3(sourceName) {
  4792. return generateSerializableMember(2, sourceName); // color3 member
  4793. }
  4794. BABYLON.serializeAsColor3 = serializeAsColor3;
  4795. function serializeAsFresnelParameters(sourceName) {
  4796. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4797. }
  4798. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4799. function serializeAsVector2(sourceName) {
  4800. return generateSerializableMember(4, sourceName); // vector2 member
  4801. }
  4802. BABYLON.serializeAsVector2 = serializeAsVector2;
  4803. function serializeAsVector3(sourceName) {
  4804. return generateSerializableMember(5, sourceName); // vector3 member
  4805. }
  4806. BABYLON.serializeAsVector3 = serializeAsVector3;
  4807. function serializeAsMeshReference(sourceName) {
  4808. return generateSerializableMember(6, sourceName); // mesh reference member
  4809. }
  4810. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4811. function serializeAsColorCurves(sourceName) {
  4812. return generateSerializableMember(7, sourceName); // color curves
  4813. }
  4814. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4815. function serializeAsColor4(sourceName) {
  4816. return generateSerializableMember(8, sourceName); // color 4
  4817. }
  4818. BABYLON.serializeAsColor4 = serializeAsColor4;
  4819. function serializeAsImageProcessingConfiguration(sourceName) {
  4820. return generateSerializableMember(9, sourceName); // image processing
  4821. }
  4822. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4823. var SerializationHelper = (function () {
  4824. function SerializationHelper() {
  4825. }
  4826. SerializationHelper.Serialize = function (entity, serializationObject) {
  4827. if (!serializationObject) {
  4828. serializationObject = {};
  4829. }
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4833. }
  4834. // Properties
  4835. for (var property in entity.__serializableMembers) {
  4836. var propertyDescriptor = entity.__serializableMembers[property];
  4837. var targetPropertyName = propertyDescriptor.sourceName || property;
  4838. var propertyType = propertyDescriptor.type;
  4839. var sourceProperty = entity[property];
  4840. if (sourceProperty !== undefined && sourceProperty !== null) {
  4841. switch (propertyType) {
  4842. case 0:
  4843. serializationObject[targetPropertyName] = sourceProperty;
  4844. break;
  4845. case 1:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 2:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 3:
  4852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4853. break;
  4854. case 4:
  4855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4856. break;
  4857. case 5:
  4858. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4859. break;
  4860. case 6:
  4861. serializationObject[targetPropertyName] = sourceProperty.id;
  4862. break;
  4863. case 7:
  4864. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4865. break;
  4866. case 8:
  4867. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4868. break;
  4869. case 9:
  4870. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return serializationObject;
  4876. };
  4877. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4878. var destination = creationFunction();
  4879. // Tags
  4880. if (BABYLON.Tags) {
  4881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4882. }
  4883. // Properties
  4884. for (var property in destination.__serializableMembers) {
  4885. var propertyDescriptor = destination.__serializableMembers[property];
  4886. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4887. var propertyType = propertyDescriptor.type;
  4888. if (sourceProperty !== undefined && sourceProperty !== null) {
  4889. switch (propertyType) {
  4890. case 0:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1:
  4894. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4895. break;
  4896. case 2:
  4897. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4898. break;
  4899. case 3:
  4900. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4901. break;
  4902. case 4:
  4903. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4904. break;
  4905. case 5:
  4906. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4907. break;
  4908. case 6:
  4909. destination[property] = scene.getLastMeshByID(sourceProperty);
  4910. break;
  4911. case 7:
  4912. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4913. break;
  4914. case 8:
  4915. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4916. break;
  4917. case 9:
  4918. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4919. break;
  4920. }
  4921. }
  4922. }
  4923. return destination;
  4924. };
  4925. SerializationHelper.Clone = function (creationFunction, source) {
  4926. var destination = creationFunction();
  4927. // Tags
  4928. if (BABYLON.Tags) {
  4929. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4930. }
  4931. // Properties
  4932. for (var property in destination.__serializableMembers) {
  4933. var propertyDescriptor = destination.__serializableMembers[property];
  4934. var sourceProperty = source[property];
  4935. var propertyType = propertyDescriptor.type;
  4936. if (sourceProperty !== undefined && sourceProperty !== null) {
  4937. switch (propertyType) {
  4938. case 0: // Value
  4939. case 6:
  4940. destination[property] = sourceProperty;
  4941. break;
  4942. case 1: // Texture
  4943. case 2: // Color3
  4944. case 3: // FresnelParameters
  4945. case 4: // Vector2
  4946. case 5: // Vector3
  4947. case 7:
  4948. destination[property] = sourceProperty.clone();
  4949. break;
  4950. }
  4951. }
  4952. }
  4953. return destination;
  4954. };
  4955. return SerializationHelper;
  4956. }());
  4957. BABYLON.SerializationHelper = SerializationHelper;
  4958. })(BABYLON || (BABYLON = {}));
  4959. //# sourceMappingURL=babylon.decorators.js.map
  4960. var BABYLON;
  4961. (function (BABYLON) {
  4962. /**
  4963. * A class serves as a medium between the observable and its observers
  4964. */
  4965. var EventState = (function () {
  4966. /**
  4967. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4968. */
  4969. function EventState(mask, skipNextObservers) {
  4970. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4971. this.initalize(mask, skipNextObservers);
  4972. }
  4973. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4974. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4975. this.mask = mask;
  4976. this.skipNextObservers = skipNextObservers;
  4977. return this;
  4978. };
  4979. return EventState;
  4980. }());
  4981. BABYLON.EventState = EventState;
  4982. /**
  4983. * Represent an Observer registered to a given Observable object.
  4984. */
  4985. var Observer = (function () {
  4986. function Observer(callback, mask) {
  4987. this.callback = callback;
  4988. this.mask = mask;
  4989. }
  4990. return Observer;
  4991. }());
  4992. BABYLON.Observer = Observer;
  4993. /**
  4994. * The Observable class is a simple implementation of the Observable pattern.
  4995. * 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.
  4996. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4997. * 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).
  4998. * 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.
  4999. */
  5000. var Observable = (function () {
  5001. function Observable() {
  5002. this._observers = new Array();
  5003. this._eventState = new EventState(0);
  5004. }
  5005. /**
  5006. * Create a new Observer with the specified callback
  5007. * @param callback the callback that will be executed for that Observer
  5008. * @param mask the mask used to filter observers
  5009. * @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.
  5010. */
  5011. Observable.prototype.add = function (callback, mask, insertFirst) {
  5012. if (mask === void 0) { mask = -1; }
  5013. if (insertFirst === void 0) { insertFirst = false; }
  5014. if (!callback) {
  5015. return null;
  5016. }
  5017. var observer = new Observer(callback, mask);
  5018. if (insertFirst) {
  5019. this._observers.unshift(observer);
  5020. }
  5021. else {
  5022. this._observers.push(observer);
  5023. }
  5024. return observer;
  5025. };
  5026. /**
  5027. * Remove an Observer from the Observable object
  5028. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5029. */
  5030. Observable.prototype.remove = function (observer) {
  5031. var index = this._observers.indexOf(observer);
  5032. if (index !== -1) {
  5033. this._observers.splice(index, 1);
  5034. return true;
  5035. }
  5036. return false;
  5037. };
  5038. /**
  5039. * Remove a callback from the Observable object
  5040. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5041. */
  5042. Observable.prototype.removeCallback = function (callback) {
  5043. for (var index = 0; index < this._observers.length; index++) {
  5044. if (this._observers[index].callback === callback) {
  5045. this._observers.splice(index, 1);
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. };
  5051. /**
  5052. * Notify all Observers by calling their respective callback with the given data
  5053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5054. * @param eventData
  5055. * @param mask
  5056. */
  5057. Observable.prototype.notifyObservers = function (eventData, mask) {
  5058. if (mask === void 0) { mask = -1; }
  5059. var state = this._eventState;
  5060. state.mask = mask;
  5061. state.skipNextObservers = false;
  5062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5063. var obs = _a[_i];
  5064. if (obs.mask & mask) {
  5065. obs.callback(eventData, state);
  5066. }
  5067. if (state.skipNextObservers) {
  5068. return false;
  5069. }
  5070. }
  5071. return true;
  5072. };
  5073. /**
  5074. * return true is the Observable has at least one Observer registered
  5075. */
  5076. Observable.prototype.hasObservers = function () {
  5077. return this._observers.length > 0;
  5078. };
  5079. /**
  5080. * Clear the list of observers
  5081. */
  5082. Observable.prototype.clear = function () {
  5083. this._observers = new Array();
  5084. };
  5085. /**
  5086. * Clone the current observable
  5087. */
  5088. Observable.prototype.clone = function () {
  5089. var result = new Observable();
  5090. result._observers = this._observers.slice(0);
  5091. return result;
  5092. };
  5093. /**
  5094. * Does this observable handles observer registered with a given mask
  5095. * @param {number} trigger - the mask to be tested
  5096. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5097. **/
  5098. Observable.prototype.hasSpecificMask = function (mask) {
  5099. if (mask === void 0) { mask = -1; }
  5100. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5101. var obs = _a[_i];
  5102. if (obs.mask & mask && obs.mask === mask) {
  5103. return true;
  5104. }
  5105. }
  5106. return false;
  5107. };
  5108. return Observable;
  5109. }());
  5110. BABYLON.Observable = Observable;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.observable.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. var SmartArray = (function () {
  5116. function SmartArray(capacity) {
  5117. this.length = 0;
  5118. this._duplicateId = 0;
  5119. this.data = new Array(capacity);
  5120. this._id = SmartArray._GlobalId++;
  5121. }
  5122. SmartArray.prototype.push = function (value) {
  5123. this.data[this.length++] = value;
  5124. if (this.length > this.data.length) {
  5125. this.data.length *= 2;
  5126. }
  5127. if (!value.__smartArrayFlags) {
  5128. value.__smartArrayFlags = {};
  5129. }
  5130. value.__smartArrayFlags[this._id] = this._duplicateId;
  5131. };
  5132. SmartArray.prototype.forEach = function (func) {
  5133. for (var index = 0; index < this.length; index++) {
  5134. func(this.data[index]);
  5135. }
  5136. };
  5137. SmartArray.prototype.pushNoDuplicate = function (value) {
  5138. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5139. return false;
  5140. }
  5141. this.push(value);
  5142. return true;
  5143. };
  5144. SmartArray.prototype.sort = function (compareFn) {
  5145. this.data.sort(compareFn);
  5146. };
  5147. SmartArray.prototype.reset = function () {
  5148. this.length = 0;
  5149. this._duplicateId++;
  5150. };
  5151. SmartArray.prototype.dispose = function () {
  5152. this.reset();
  5153. this.data.length = 0;
  5154. };
  5155. SmartArray.prototype.concat = function (array) {
  5156. if (array.length === 0) {
  5157. return;
  5158. }
  5159. if (this.length + array.length > this.data.length) {
  5160. this.data.length = (this.length + array.length) * 2;
  5161. }
  5162. for (var index = 0; index < array.length; index++) {
  5163. this.data[this.length++] = (array.data || array)[index];
  5164. }
  5165. };
  5166. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5167. if (array.length === 0) {
  5168. return;
  5169. }
  5170. if (this.length + array.length > this.data.length) {
  5171. this.data.length = (this.length + array.length) * 2;
  5172. }
  5173. for (var index = 0; index < array.length; index++) {
  5174. var item = (array.data || array)[index];
  5175. this.pushNoDuplicate(item);
  5176. }
  5177. };
  5178. SmartArray.prototype.indexOf = function (value) {
  5179. var position = this.data.indexOf(value);
  5180. if (position >= this.length) {
  5181. return -1;
  5182. }
  5183. return position;
  5184. };
  5185. SmartArray.prototype.contains = function (value) {
  5186. return this.data.indexOf(value) !== -1;
  5187. };
  5188. return SmartArray;
  5189. }());
  5190. // Statics
  5191. SmartArray._GlobalId = 0;
  5192. BABYLON.SmartArray = SmartArray;
  5193. })(BABYLON || (BABYLON = {}));
  5194. //# sourceMappingURL=babylon.smartArray.js.map
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. // Screenshots
  5198. var screenshotCanvas;
  5199. var cloneValue = function (source, destinationObject) {
  5200. if (!source)
  5201. return null;
  5202. if (source instanceof BABYLON.Mesh) {
  5203. return null;
  5204. }
  5205. if (source instanceof BABYLON.SubMesh) {
  5206. return source.clone(destinationObject);
  5207. }
  5208. else if (source.clone) {
  5209. return source.clone();
  5210. }
  5211. return null;
  5212. };
  5213. var Tools = (function () {
  5214. function Tools() {
  5215. }
  5216. ;
  5217. /**
  5218. * Interpolates between a and b via alpha
  5219. * @param a The lower value (returned when alpha = 0)
  5220. * @param b The upper value (returned when alpha = 1)
  5221. * @param alpha The interpolation-factor
  5222. * @return The mixed value
  5223. */
  5224. Tools.Mix = function (a, b, alpha) {
  5225. return a * (1 - alpha) + b * alpha;
  5226. };
  5227. Tools.Instantiate = function (className) {
  5228. var arr = className.split(".");
  5229. var fn = (window || this);
  5230. for (var i = 0, len = arr.length; i < len; i++) {
  5231. fn = fn[arr[i]];
  5232. }
  5233. if (typeof fn !== "function") {
  5234. return null;
  5235. }
  5236. return fn;
  5237. };
  5238. Tools.SetImmediate = function (action) {
  5239. if (window.setImmediate) {
  5240. window.setImmediate(action);
  5241. }
  5242. else {
  5243. setTimeout(action, 1);
  5244. }
  5245. };
  5246. Tools.IsExponentOfTwo = function (value) {
  5247. var count = 1;
  5248. do {
  5249. count *= 2;
  5250. } while (count < value);
  5251. return count === value;
  5252. };
  5253. /**
  5254. * Find the next highest power of two.
  5255. * @param x Number to start search from.
  5256. * @return Next highest power of two.
  5257. */
  5258. Tools.CeilingPOT = function (x) {
  5259. x--;
  5260. x |= x >> 1;
  5261. x |= x >> 2;
  5262. x |= x >> 4;
  5263. x |= x >> 8;
  5264. x |= x >> 16;
  5265. x++;
  5266. return x;
  5267. };
  5268. /**
  5269. * Find the next lowest power of two.
  5270. * @param x Number to start search from.
  5271. * @return Next lowest power of two.
  5272. */
  5273. Tools.FloorPOT = function (x) {
  5274. x = x | (x >> 1);
  5275. x = x | (x >> 2);
  5276. x = x | (x >> 4);
  5277. x = x | (x >> 8);
  5278. x = x | (x >> 16);
  5279. return x - (x >> 1);
  5280. };
  5281. /**
  5282. * Find the nearest power of two.
  5283. * @param x Number to start search from.
  5284. * @return Next nearest power of two.
  5285. */
  5286. Tools.NearestPOT = function (x) {
  5287. var c = Tools.CeilingPOT(x);
  5288. var f = Tools.FloorPOT(x);
  5289. return (c - x) > (x - f) ? f : c;
  5290. };
  5291. Tools.GetExponentOfTwo = function (value, max, mode) {
  5292. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5293. var pot;
  5294. switch (mode) {
  5295. case BABYLON.Engine.SCALEMODE_FLOOR:
  5296. pot = Tools.FloorPOT(value);
  5297. break;
  5298. case BABYLON.Engine.SCALEMODE_NEAREST:
  5299. pot = Tools.NearestPOT(value);
  5300. break;
  5301. case BABYLON.Engine.SCALEMODE_CEILING:
  5302. pot = Tools.CeilingPOT(value);
  5303. break;
  5304. }
  5305. return Math.min(pot, max);
  5306. };
  5307. Tools.GetFilename = function (path) {
  5308. var index = path.lastIndexOf("/");
  5309. if (index < 0)
  5310. return path;
  5311. return path.substring(index + 1);
  5312. };
  5313. Tools.GetDOMTextContent = function (element) {
  5314. var result = "";
  5315. var child = element.firstChild;
  5316. while (child) {
  5317. if (child.nodeType === 3) {
  5318. result += child.textContent;
  5319. }
  5320. child = child.nextSibling;
  5321. }
  5322. return result;
  5323. };
  5324. Tools.ToDegrees = function (angle) {
  5325. return angle * 180 / Math.PI;
  5326. };
  5327. Tools.ToRadians = function (angle) {
  5328. return angle * Math.PI / 180;
  5329. };
  5330. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5331. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5332. var output = "";
  5333. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5334. var i = 0;
  5335. var bytes = new Uint8Array(buffer);
  5336. while (i < bytes.length) {
  5337. chr1 = bytes[i++];
  5338. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5339. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5340. enc1 = chr1 >> 2;
  5341. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5342. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5343. enc4 = chr3 & 63;
  5344. if (isNaN(chr2)) {
  5345. enc3 = enc4 = 64;
  5346. }
  5347. else if (isNaN(chr3)) {
  5348. enc4 = 64;
  5349. }
  5350. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5351. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5352. }
  5353. return "data:image/png;base64," + output;
  5354. };
  5355. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5356. if (bias === void 0) { bias = null; }
  5357. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5359. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5360. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5361. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5362. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5363. }
  5364. if (bias) {
  5365. minimum.x -= minimum.x * bias.x + bias.y;
  5366. minimum.y -= minimum.y * bias.x + bias.y;
  5367. minimum.z -= minimum.z * bias.x + bias.y;
  5368. maximum.x += maximum.x * bias.x + bias.y;
  5369. maximum.y += maximum.y * bias.x + bias.y;
  5370. maximum.z += maximum.z * bias.x + bias.y;
  5371. }
  5372. return {
  5373. minimum: minimum,
  5374. maximum: maximum
  5375. };
  5376. };
  5377. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5378. if (bias === void 0) { bias = null; }
  5379. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5380. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5381. if (!stride) {
  5382. stride = 3;
  5383. }
  5384. for (var index = start; index < start + count; index++) {
  5385. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5388. }
  5389. if (bias) {
  5390. minimum.x -= minimum.x * bias.x + bias.y;
  5391. minimum.y -= minimum.y * bias.x + bias.y;
  5392. minimum.z -= minimum.z * bias.x + bias.y;
  5393. maximum.x += maximum.x * bias.x + bias.y;
  5394. maximum.y += maximum.y * bias.x + bias.y;
  5395. maximum.z += maximum.z * bias.x + bias.y;
  5396. }
  5397. return {
  5398. minimum: minimum,
  5399. maximum: maximum
  5400. };
  5401. };
  5402. Tools.Vector2ArrayFeeder = function (array) {
  5403. return function (index) {
  5404. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5405. var length = isFloatArray ? array.length / 2 : array.length;
  5406. if (index >= length) {
  5407. return null;
  5408. }
  5409. if (isFloatArray) {
  5410. var fa = array;
  5411. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5412. }
  5413. var a = array;
  5414. return a[index];
  5415. };
  5416. };
  5417. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5418. if (bias === void 0) { bias = null; }
  5419. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5420. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5421. var i = 0;
  5422. var cur = feeder(i++);
  5423. while (cur) {
  5424. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5425. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5426. cur = feeder(i++);
  5427. }
  5428. if (bias) {
  5429. minimum.x -= minimum.x * bias.x + bias.y;
  5430. minimum.y -= minimum.y * bias.x + bias.y;
  5431. maximum.x += maximum.x * bias.x + bias.y;
  5432. maximum.y += maximum.y * bias.x + bias.y;
  5433. }
  5434. return {
  5435. minimum: minimum,
  5436. maximum: maximum
  5437. };
  5438. };
  5439. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5440. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5441. return undefined;
  5442. return Array.isArray(obj) ? obj : [obj];
  5443. };
  5444. // Misc.
  5445. Tools.GetPointerPrefix = function () {
  5446. var eventPrefix = "pointer";
  5447. // Check if pointer events are supported
  5448. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5449. eventPrefix = "mouse";
  5450. }
  5451. return eventPrefix;
  5452. };
  5453. /**
  5454. * @param func - the function to be called
  5455. * @param requester - the object that will request the next frame. Falls back to window.
  5456. */
  5457. Tools.QueueNewFrame = function (func, requester) {
  5458. if (requester === void 0) { requester = window; }
  5459. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5460. /*if(requester.isPresenting) {
  5461. return;
  5462. } else*/ if (requester.requestAnimationFrame)
  5463. requester.requestAnimationFrame(func);
  5464. else if (requester.msRequestAnimationFrame)
  5465. requester.msRequestAnimationFrame(func);
  5466. else if (requester.webkitRequestAnimationFrame)
  5467. requester.webkitRequestAnimationFrame(func);
  5468. else if (requester.mozRequestAnimationFrame)
  5469. requester.mozRequestAnimationFrame(func);
  5470. else if (requester.oRequestAnimationFrame)
  5471. requester.oRequestAnimationFrame(func);
  5472. else {
  5473. window.setTimeout(func, 16);
  5474. }
  5475. };
  5476. Tools.RequestFullscreen = function (element) {
  5477. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5478. if (!requestFunction)
  5479. return;
  5480. requestFunction.call(element);
  5481. };
  5482. Tools.ExitFullscreen = function () {
  5483. if (document.exitFullscreen) {
  5484. document.exitFullscreen();
  5485. }
  5486. else if (document.mozCancelFullScreen) {
  5487. document.mozCancelFullScreen();
  5488. }
  5489. else if (document.webkitCancelFullScreen) {
  5490. document.webkitCancelFullScreen();
  5491. }
  5492. else if (document.msCancelFullScreen) {
  5493. document.msCancelFullScreen();
  5494. }
  5495. };
  5496. Tools.SetCorsBehavior = function (url, img) {
  5497. if (Tools.CorsBehavior) {
  5498. switch (typeof (Tools.CorsBehavior)) {
  5499. case "function":
  5500. var result = Tools.CorsBehavior(url);
  5501. if (result) {
  5502. img.crossOrigin = result;
  5503. }
  5504. break;
  5505. case "string":
  5506. default:
  5507. img.crossOrigin = Tools.CorsBehavior;
  5508. break;
  5509. }
  5510. }
  5511. };
  5512. // External files
  5513. Tools.CleanUrl = function (url) {
  5514. url = url.replace(/#/mg, "%23");
  5515. return url;
  5516. };
  5517. Tools.LoadImage = function (url, onload, onerror, database) {
  5518. if (url instanceof ArrayBuffer) {
  5519. url = Tools.EncodeArrayBufferTobase64(url);
  5520. }
  5521. url = Tools.CleanUrl(url);
  5522. var img = new Image();
  5523. if (url.substr(0, 5) !== "data:") {
  5524. Tools.SetCorsBehavior(url, img);
  5525. }
  5526. img.onload = function () {
  5527. onload(img);
  5528. };
  5529. img.onerror = function (err) {
  5530. Tools.Error("Error while trying to load image: " + url);
  5531. if (Tools.UseFallbackTexture) {
  5532. img.src = Tools.fallbackTexture;
  5533. onload(img);
  5534. }
  5535. else {
  5536. onerror();
  5537. }
  5538. };
  5539. var noIndexedDB = function () {
  5540. img.src = url;
  5541. };
  5542. var loadFromIndexedDB = function () {
  5543. database.loadImageFromDB(url, img);
  5544. };
  5545. //ANY database to do!
  5546. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5547. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5548. }
  5549. else {
  5550. if (url.indexOf("file:") !== 0) {
  5551. noIndexedDB();
  5552. }
  5553. else {
  5554. var textureName = url.substring(5).toLowerCase();
  5555. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5556. try {
  5557. var blobURL;
  5558. try {
  5559. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5560. }
  5561. catch (ex) {
  5562. // Chrome doesn't support oneTimeOnly parameter
  5563. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5564. }
  5565. img.src = blobURL;
  5566. }
  5567. catch (e) {
  5568. img.src = null;
  5569. }
  5570. }
  5571. else {
  5572. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5573. img.src = Tools.fallbackTexture;
  5574. }
  5575. }
  5576. }
  5577. return img;
  5578. };
  5579. //ANY
  5580. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5581. url = Tools.CleanUrl(url);
  5582. var noIndexedDB = function () {
  5583. var request = new XMLHttpRequest();
  5584. var loadUrl = Tools.BaseUrl + url;
  5585. request.open('GET', loadUrl, true);
  5586. if (useArrayBuffer) {
  5587. request.responseType = "arraybuffer";
  5588. }
  5589. request.onprogress = progressCallBack;
  5590. request.onreadystatechange = function () {
  5591. // In case of undefined state in some browsers.
  5592. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5593. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5594. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5595. callback(!useArrayBuffer ? request.responseText : request.response);
  5596. }
  5597. else {
  5598. if (onError) {
  5599. onError(request);
  5600. }
  5601. else {
  5602. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5603. }
  5604. }
  5605. }
  5606. };
  5607. request.send(null);
  5608. };
  5609. var loadFromIndexedDB = function () {
  5610. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5611. };
  5612. if (url.indexOf("file:") !== -1) {
  5613. var fileName = url.substring(5).toLowerCase();
  5614. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5615. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5616. }
  5617. else {
  5618. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5619. }
  5620. }
  5621. else {
  5622. // Caching all files
  5623. if (database && database.enableSceneOffline) {
  5624. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5625. }
  5626. else {
  5627. noIndexedDB();
  5628. }
  5629. }
  5630. };
  5631. /**
  5632. * Load a script (identified by an url). When the url returns, the
  5633. * content of this file is added into a new script element, attached to the DOM (body element)
  5634. */
  5635. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5636. var head = document.getElementsByTagName('head')[0];
  5637. var script = document.createElement('script');
  5638. script.type = 'text/javascript';
  5639. script.src = scriptUrl;
  5640. var self = this;
  5641. script.onload = function () {
  5642. if (onSuccess) {
  5643. onSuccess();
  5644. }
  5645. };
  5646. script.onerror = function () {
  5647. if (onError) {
  5648. onError();
  5649. }
  5650. };
  5651. head.appendChild(script);
  5652. };
  5653. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5654. var reader = new FileReader();
  5655. reader.onload = function (e) {
  5656. //target doesn't have result from ts 1.3
  5657. callback(e.target['result']);
  5658. };
  5659. reader.onprogress = progressCallback;
  5660. reader.readAsDataURL(fileToLoad);
  5661. };
  5662. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5663. var reader = new FileReader();
  5664. reader.onerror = function (e) {
  5665. Tools.Log("Error while reading file: " + fileToLoad.name);
  5666. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5667. };
  5668. reader.onload = function (e) {
  5669. //target doesn't have result from ts 1.3
  5670. callback(e.target['result']);
  5671. };
  5672. reader.onprogress = progressCallBack;
  5673. if (!useArrayBuffer) {
  5674. // Asynchronous read
  5675. reader.readAsText(fileToLoad);
  5676. }
  5677. else {
  5678. reader.readAsArrayBuffer(fileToLoad);
  5679. }
  5680. };
  5681. //returns a downloadable url to a file content.
  5682. Tools.FileAsURL = function (content) {
  5683. var fileBlob = new Blob([content]);
  5684. var url = window.URL || window.webkitURL;
  5685. var link = url.createObjectURL(fileBlob);
  5686. return link;
  5687. };
  5688. // Misc.
  5689. Tools.Format = function (value, decimals) {
  5690. if (decimals === void 0) { decimals = 2; }
  5691. return value.toFixed(decimals);
  5692. };
  5693. Tools.CheckExtends = function (v, min, max) {
  5694. if (v.x < min.x)
  5695. min.x = v.x;
  5696. if (v.y < min.y)
  5697. min.y = v.y;
  5698. if (v.z < min.z)
  5699. min.z = v.z;
  5700. if (v.x > max.x)
  5701. max.x = v.x;
  5702. if (v.y > max.y)
  5703. max.y = v.y;
  5704. if (v.z > max.z)
  5705. max.z = v.z;
  5706. };
  5707. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5708. for (var prop in source) {
  5709. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5710. continue;
  5711. }
  5712. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5713. continue;
  5714. }
  5715. var sourceValue = source[prop];
  5716. var typeOfSourceValue = typeof sourceValue;
  5717. if (typeOfSourceValue === "function") {
  5718. continue;
  5719. }
  5720. if (typeOfSourceValue === "object") {
  5721. if (sourceValue instanceof Array) {
  5722. destination[prop] = [];
  5723. if (sourceValue.length > 0) {
  5724. if (typeof sourceValue[0] == "object") {
  5725. for (var index = 0; index < sourceValue.length; index++) {
  5726. var clonedValue = cloneValue(sourceValue[index], destination);
  5727. if (destination[prop].indexOf(clonedValue) === -1) {
  5728. destination[prop].push(clonedValue);
  5729. }
  5730. }
  5731. }
  5732. else {
  5733. destination[prop] = sourceValue.slice(0);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = cloneValue(sourceValue, destination);
  5739. }
  5740. }
  5741. else {
  5742. destination[prop] = sourceValue;
  5743. }
  5744. }
  5745. };
  5746. Tools.IsEmpty = function (obj) {
  5747. for (var i in obj) {
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. Tools.RegisterTopRootEvents = function (events) {
  5753. for (var index = 0; index < events.length; index++) {
  5754. var event = events[index];
  5755. window.addEventListener(event.name, event.handler, false);
  5756. try {
  5757. if (window.parent) {
  5758. window.parent.addEventListener(event.name, event.handler, false);
  5759. }
  5760. }
  5761. catch (e) {
  5762. // Silently fails...
  5763. }
  5764. }
  5765. };
  5766. Tools.UnregisterTopRootEvents = function (events) {
  5767. for (var index = 0; index < events.length; index++) {
  5768. var event = events[index];
  5769. window.removeEventListener(event.name, event.handler);
  5770. try {
  5771. if (window.parent) {
  5772. window.parent.removeEventListener(event.name, event.handler);
  5773. }
  5774. }
  5775. catch (e) {
  5776. // Silently fails...
  5777. }
  5778. }
  5779. };
  5780. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5781. if (mimeType === void 0) { mimeType = "image/png"; }
  5782. // Read the contents of the framebuffer
  5783. var numberOfChannelsByLine = width * 4;
  5784. var halfHeight = height / 2;
  5785. //Reading datas from WebGL
  5786. var data = engine.readPixels(0, 0, width, height);
  5787. //To flip image on Y axis.
  5788. for (var i = 0; i < halfHeight; i++) {
  5789. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5790. var currentCell = j + i * numberOfChannelsByLine;
  5791. var targetLine = height - i - 1;
  5792. var targetCell = j + targetLine * numberOfChannelsByLine;
  5793. var temp = data[currentCell];
  5794. data[currentCell] = data[targetCell];
  5795. data[targetCell] = temp;
  5796. }
  5797. }
  5798. // Create a 2D canvas to store the result
  5799. if (!screenshotCanvas) {
  5800. screenshotCanvas = document.createElement('canvas');
  5801. }
  5802. screenshotCanvas.width = width;
  5803. screenshotCanvas.height = height;
  5804. var context = screenshotCanvas.getContext('2d');
  5805. // Copy the pixels to a 2D canvas
  5806. var imageData = context.createImageData(width, height);
  5807. var castData = (imageData.data);
  5808. castData.set(data);
  5809. context.putImageData(imageData, 0, 0);
  5810. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5811. };
  5812. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5813. if (mimeType === void 0) { mimeType = "image/png"; }
  5814. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5815. if (successCallback) {
  5816. successCallback(base64Image);
  5817. }
  5818. else {
  5819. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5820. if (("download" in document.createElement("a"))) {
  5821. var a = window.document.createElement("a");
  5822. a.href = base64Image;
  5823. var date = new Date();
  5824. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5825. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5826. window.document.body.appendChild(a);
  5827. a.addEventListener("click", function () {
  5828. a.parentElement.removeChild(a);
  5829. });
  5830. a.click();
  5831. //Or opening a new tab with the image if it is not possible to automatically start download.
  5832. }
  5833. else {
  5834. var newWindow = window.open("");
  5835. var img = newWindow.document.createElement("img");
  5836. img.src = base64Image;
  5837. newWindow.document.body.appendChild(img);
  5838. }
  5839. }
  5840. };
  5841. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5842. if (mimeType === void 0) { mimeType = "image/png"; }
  5843. var width;
  5844. var height;
  5845. // If a precision value is specified
  5846. if (size.precision) {
  5847. width = Math.round(engine.getRenderWidth() * size.precision);
  5848. height = Math.round(width / engine.getAspectRatio(camera));
  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. }
  5858. else if (size.height && !size.width) {
  5859. height = size.height;
  5860. width = Math.round(height * engine.getAspectRatio(camera));
  5861. }
  5862. else if (!isNaN(size)) {
  5863. height = size;
  5864. width = size;
  5865. }
  5866. else {
  5867. Tools.Error("Invalid 'size' parameter !");
  5868. return;
  5869. }
  5870. if (!screenshotCanvas) {
  5871. screenshotCanvas = document.createElement('canvas');
  5872. }
  5873. screenshotCanvas.width = width;
  5874. screenshotCanvas.height = height;
  5875. var renderContext = screenshotCanvas.getContext("2d");
  5876. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5877. var newWidth = width;
  5878. var newHeight = newWidth / ratio;
  5879. if (newHeight > height) {
  5880. newHeight = height;
  5881. newWidth = newHeight * ratio;
  5882. }
  5883. var offsetX = Math.max(0, width - newWidth) / 2;
  5884. var offsetY = Math.max(0, height - newHeight) / 2;
  5885. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5886. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5887. };
  5888. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5889. if (mimeType === void 0) { mimeType = "image/png"; }
  5890. if (samples === void 0) { samples = 1; }
  5891. var width;
  5892. var height;
  5893. //If a precision value is specified
  5894. if (size.precision) {
  5895. width = Math.round(engine.getRenderWidth() * size.precision);
  5896. height = Math.round(width / engine.getAspectRatio(camera));
  5897. size = { width: width, height: height };
  5898. }
  5899. else if (size.width && size.height) {
  5900. width = size.width;
  5901. height = size.height;
  5902. }
  5903. else if (size.width && !size.height) {
  5904. width = size.width;
  5905. height = Math.round(width / engine.getAspectRatio(camera));
  5906. size = { width: width, height: height };
  5907. }
  5908. else if (size.height && !size.width) {
  5909. height = size.height;
  5910. width = Math.round(height * engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (!isNaN(size)) {
  5914. height = size;
  5915. width = size;
  5916. }
  5917. else {
  5918. Tools.Error("Invalid 'size' parameter !");
  5919. return;
  5920. }
  5921. var scene = camera.getScene();
  5922. var previousCamera = null;
  5923. if (scene.activeCamera !== camera) {
  5924. previousCamera = scene.activeCamera;
  5925. scene.activeCamera = camera;
  5926. }
  5927. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5928. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5929. texture.renderList = scene.meshes;
  5930. texture.samples = samples;
  5931. texture.onAfterRenderObservable.add(function () {
  5932. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5933. });
  5934. scene.incrementRenderId();
  5935. scene.resetCachedMaterial();
  5936. texture.render(true);
  5937. texture.dispose();
  5938. if (previousCamera) {
  5939. scene.activeCamera = previousCamera;
  5940. }
  5941. camera.getProjectionMatrix(true); // Force cache refresh;
  5942. };
  5943. // XHR response validator for local file scenario
  5944. Tools.ValidateXHRData = function (xhr, dataType) {
  5945. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5946. if (dataType === void 0) { dataType = 7; }
  5947. try {
  5948. if (dataType & 1) {
  5949. if (xhr.responseText && xhr.responseText.length > 0) {
  5950. return true;
  5951. }
  5952. else if (dataType === 1) {
  5953. return false;
  5954. }
  5955. }
  5956. if (dataType & 2) {
  5957. // Check header width and height since there is no "TGA" magic number
  5958. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5959. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5960. return true;
  5961. }
  5962. else if (dataType === 2) {
  5963. return false;
  5964. }
  5965. }
  5966. if (dataType & 4) {
  5967. // Check for the "DDS" magic number
  5968. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5969. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5970. return true;
  5971. }
  5972. else {
  5973. return false;
  5974. }
  5975. }
  5976. }
  5977. catch (e) {
  5978. // Global protection
  5979. }
  5980. return false;
  5981. };
  5982. /**
  5983. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5984. * Be aware Math.random() could cause collisions, but:
  5985. * "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"
  5986. */
  5987. Tools.RandomId = function () {
  5988. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5989. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5990. return v.toString(16);
  5991. });
  5992. };
  5993. Object.defineProperty(Tools, "NoneLogLevel", {
  5994. get: function () {
  5995. return Tools._NoneLogLevel;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Object.defineProperty(Tools, "MessageLogLevel", {
  6001. get: function () {
  6002. return Tools._MessageLogLevel;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. Object.defineProperty(Tools, "WarningLogLevel", {
  6008. get: function () {
  6009. return Tools._WarningLogLevel;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. Object.defineProperty(Tools, "ErrorLogLevel", {
  6015. get: function () {
  6016. return Tools._ErrorLogLevel;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "AllLogLevel", {
  6022. get: function () {
  6023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Tools._AddLogEntry = function (entry) {
  6029. Tools._LogCache = entry + Tools._LogCache;
  6030. if (Tools.OnNewCacheEntry) {
  6031. Tools.OnNewCacheEntry(entry);
  6032. }
  6033. };
  6034. Tools._FormatMessage = function (message) {
  6035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6036. var date = new Date();
  6037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6038. };
  6039. Tools._LogDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._LogEnabled = function (message) {
  6043. var formattedMessage = Tools._FormatMessage(message);
  6044. console.log("BJS - " + formattedMessage);
  6045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6046. Tools._AddLogEntry(entry);
  6047. };
  6048. Tools._WarnDisabled = function (message) {
  6049. // nothing to do
  6050. };
  6051. Tools._WarnEnabled = function (message) {
  6052. var formattedMessage = Tools._FormatMessage(message);
  6053. console.warn("BJS - " + formattedMessage);
  6054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6055. Tools._AddLogEntry(entry);
  6056. };
  6057. Tools._ErrorDisabled = function (message) {
  6058. // nothing to do
  6059. };
  6060. Tools._ErrorEnabled = function (message) {
  6061. Tools.errorsCount++;
  6062. var formattedMessage = Tools._FormatMessage(message);
  6063. console.error("BJS - " + formattedMessage);
  6064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6065. Tools._AddLogEntry(entry);
  6066. };
  6067. Object.defineProperty(Tools, "LogCache", {
  6068. get: function () {
  6069. return Tools._LogCache;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Tools.ClearLogCache = function () {
  6075. Tools._LogCache = "";
  6076. Tools.errorsCount = 0;
  6077. };
  6078. Object.defineProperty(Tools, "LogLevels", {
  6079. set: function (level) {
  6080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6081. Tools.Log = Tools._LogEnabled;
  6082. }
  6083. else {
  6084. Tools.Log = Tools._LogDisabled;
  6085. }
  6086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6087. Tools.Warn = Tools._WarnEnabled;
  6088. }
  6089. else {
  6090. Tools.Warn = Tools._WarnDisabled;
  6091. }
  6092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6093. Tools.Error = Tools._ErrorEnabled;
  6094. }
  6095. else {
  6096. Tools.Error = Tools._ErrorDisabled;
  6097. }
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6103. get: function () {
  6104. return Tools._PerformanceNoneLogLevel;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6110. get: function () {
  6111. return Tools._PerformanceUserMarkLogLevel;
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6117. get: function () {
  6118. return Tools._PerformanceConsoleLogLevel;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6124. set: function (level) {
  6125. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6126. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6127. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6128. return;
  6129. }
  6130. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6132. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6133. return;
  6134. }
  6135. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6136. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6142. };
  6143. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6144. };
  6145. Tools._StartUserMark = function (counterName, condition) {
  6146. if (condition === void 0) { condition = true; }
  6147. if (!condition || !Tools._performance.mark) {
  6148. return;
  6149. }
  6150. Tools._performance.mark(counterName + "-Begin");
  6151. };
  6152. Tools._EndUserMark = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition || !Tools._performance.mark) {
  6155. return;
  6156. }
  6157. Tools._performance.mark(counterName + "-End");
  6158. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6159. };
  6160. Tools._StartPerformanceConsole = function (counterName, condition) {
  6161. if (condition === void 0) { condition = true; }
  6162. if (!condition) {
  6163. return;
  6164. }
  6165. Tools._StartUserMark(counterName, condition);
  6166. if (console.time) {
  6167. console.time(counterName);
  6168. }
  6169. };
  6170. Tools._EndPerformanceConsole = function (counterName, condition) {
  6171. if (condition === void 0) { condition = true; }
  6172. if (!condition) {
  6173. return;
  6174. }
  6175. Tools._EndUserMark(counterName, condition);
  6176. if (console.time) {
  6177. console.timeEnd(counterName);
  6178. }
  6179. };
  6180. Object.defineProperty(Tools, "Now", {
  6181. get: function () {
  6182. if (window.performance && window.performance.now) {
  6183. return window.performance.now();
  6184. }
  6185. return new Date().getTime();
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. /**
  6191. * This method will return the name of the class used to create the instance of the given object.
  6192. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6193. * @param object the object to get the class name from
  6194. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6195. */
  6196. Tools.getClassName = function (object, isType) {
  6197. if (isType === void 0) { isType = false; }
  6198. var name = null;
  6199. if (!isType && object.getClassName) {
  6200. name = object.getClassName();
  6201. }
  6202. else {
  6203. if (object instanceof Object) {
  6204. var classObj = isType ? object : Object.getPrototypeOf(object);
  6205. name = classObj.constructor["__bjsclassName__"];
  6206. }
  6207. if (!name) {
  6208. name = typeof object;
  6209. }
  6210. }
  6211. return name;
  6212. };
  6213. Tools.first = function (array, predicate) {
  6214. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6215. var el = array_1[_i];
  6216. if (predicate(el)) {
  6217. return el;
  6218. }
  6219. }
  6220. };
  6221. /**
  6222. * This method will return the name of the full name of the class, including its owning module (if any).
  6223. * 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).
  6224. * @param object the object to get the class name from
  6225. * @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.
  6226. */
  6227. Tools.getFullClassName = function (object, isType) {
  6228. if (isType === void 0) { isType = false; }
  6229. var className = null;
  6230. var moduleName = null;
  6231. if (!isType && object.getClassName) {
  6232. className = object.getClassName();
  6233. }
  6234. else {
  6235. if (object instanceof Object) {
  6236. var classObj = isType ? object : Object.getPrototypeOf(object);
  6237. className = classObj.constructor["__bjsclassName__"];
  6238. moduleName = classObj.constructor["__bjsmoduleName__"];
  6239. }
  6240. if (!className) {
  6241. className = typeof object;
  6242. }
  6243. }
  6244. if (!className) {
  6245. return null;
  6246. }
  6247. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6248. };
  6249. /**
  6250. * 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.
  6251. * @param array
  6252. */
  6253. Tools.arrayOrStringFeeder = function (array) {
  6254. return function (index) {
  6255. if (index >= array.length) {
  6256. return null;
  6257. }
  6258. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6259. if (val && val.getHashCode) {
  6260. val = val.getHashCode();
  6261. }
  6262. if (typeof val === "string") {
  6263. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6264. }
  6265. return val;
  6266. };
  6267. };
  6268. /**
  6269. * Compute the hashCode of a stream of number
  6270. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6271. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6272. * @return the hash code computed
  6273. */
  6274. Tools.hashCodeFromStream = function (feeder) {
  6275. // Based from here: http://stackoverflow.com/a/7616484/802124
  6276. var hash = 0;
  6277. var index = 0;
  6278. var chr = feeder(index++);
  6279. while (chr != null) {
  6280. hash = ((hash << 5) - hash) + chr;
  6281. hash |= 0; // Convert to 32bit integer
  6282. chr = feeder(index++);
  6283. }
  6284. return hash;
  6285. };
  6286. return Tools;
  6287. }());
  6288. Tools.BaseUrl = "";
  6289. Tools.CorsBehavior = "anonymous";
  6290. Tools.UseFallbackTexture = true;
  6291. // Used in case of a texture loading problem
  6292. 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";
  6293. // Logs
  6294. Tools._NoneLogLevel = 0;
  6295. Tools._MessageLogLevel = 1;
  6296. Tools._WarningLogLevel = 2;
  6297. Tools._ErrorLogLevel = 4;
  6298. Tools._LogCache = "";
  6299. Tools.errorsCount = 0;
  6300. Tools.Log = Tools._LogEnabled;
  6301. Tools.Warn = Tools._WarnEnabled;
  6302. Tools.Error = Tools._ErrorEnabled;
  6303. // Performances
  6304. Tools._PerformanceNoneLogLevel = 0;
  6305. Tools._PerformanceUserMarkLogLevel = 1;
  6306. Tools._PerformanceConsoleLogLevel = 2;
  6307. Tools._performance = window.performance;
  6308. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6309. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6310. BABYLON.Tools = Tools;
  6311. /**
  6312. * This class is used to track a performance counter which is number based.
  6313. * The user has access to many properties which give statistics of different nature
  6314. *
  6315. * The implementer can track two kinds of Performance Counter: time and count
  6316. * 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.
  6317. * 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.
  6318. */
  6319. var PerfCounter = (function () {
  6320. function PerfCounter() {
  6321. this._startMonitoringTime = 0;
  6322. this._min = 0;
  6323. this._max = 0;
  6324. this._average = 0;
  6325. this._lastSecAverage = 0;
  6326. this._current = 0;
  6327. this._totalValueCount = 0;
  6328. this._totalAccumulated = 0;
  6329. this._lastSecAccumulated = 0;
  6330. this._lastSecTime = 0;
  6331. this._lastSecValueCount = 0;
  6332. }
  6333. Object.defineProperty(PerfCounter.prototype, "min", {
  6334. /**
  6335. * Returns the smallest value ever
  6336. */
  6337. get: function () {
  6338. return this._min;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "max", {
  6344. /**
  6345. * Returns the biggest value ever
  6346. */
  6347. get: function () {
  6348. return this._max;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "average", {
  6354. /**
  6355. * Returns the average value since the performance counter is running
  6356. */
  6357. get: function () {
  6358. return this._average;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6364. /**
  6365. * Returns the average value of the last second the counter was monitored
  6366. */
  6367. get: function () {
  6368. return this._lastSecAverage;
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. Object.defineProperty(PerfCounter.prototype, "current", {
  6374. /**
  6375. * Returns the current value
  6376. */
  6377. get: function () {
  6378. return this._current;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(PerfCounter.prototype, "total", {
  6384. get: function () {
  6385. return this._totalAccumulated;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. /**
  6391. * Call this method to start monitoring a new frame.
  6392. * 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.
  6393. */
  6394. PerfCounter.prototype.fetchNewFrame = function () {
  6395. this._totalValueCount++;
  6396. this._current = 0;
  6397. this._lastSecValueCount++;
  6398. };
  6399. /**
  6400. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6401. * @param newCount the count value to add to the monitored count
  6402. * @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.
  6403. */
  6404. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6405. if (!PerfCounter.Enabled) {
  6406. return;
  6407. }
  6408. this._current += newCount;
  6409. if (fetchResult) {
  6410. this._fetchResult();
  6411. }
  6412. };
  6413. /**
  6414. * Start monitoring this performance counter
  6415. */
  6416. PerfCounter.prototype.beginMonitoring = function () {
  6417. if (!PerfCounter.Enabled) {
  6418. return;
  6419. }
  6420. this._startMonitoringTime = Tools.Now;
  6421. };
  6422. /**
  6423. * Compute the time lapsed since the previous beginMonitoring() call.
  6424. * @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
  6425. */
  6426. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6427. if (newFrame === void 0) { newFrame = true; }
  6428. if (!PerfCounter.Enabled) {
  6429. return;
  6430. }
  6431. if (newFrame) {
  6432. this.fetchNewFrame();
  6433. }
  6434. var currentTime = Tools.Now;
  6435. this._current = currentTime - this._startMonitoringTime;
  6436. if (newFrame) {
  6437. this._fetchResult();
  6438. }
  6439. };
  6440. PerfCounter.prototype._fetchResult = function () {
  6441. this._totalAccumulated += this._current;
  6442. this._lastSecAccumulated += this._current;
  6443. // Min/Max update
  6444. this._min = Math.min(this._min, this._current);
  6445. this._max = Math.max(this._max, this._current);
  6446. this._average = this._totalAccumulated / this._totalValueCount;
  6447. // Reset last sec?
  6448. var now = Tools.Now;
  6449. if ((now - this._lastSecTime) > 1000) {
  6450. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6451. this._lastSecTime = now;
  6452. this._lastSecAccumulated = 0;
  6453. this._lastSecValueCount = 0;
  6454. }
  6455. };
  6456. return PerfCounter;
  6457. }());
  6458. PerfCounter.Enabled = true;
  6459. BABYLON.PerfCounter = PerfCounter;
  6460. /**
  6461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6464. * @param name The name of the class, case should be preserved
  6465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6466. */
  6467. function className(name, module) {
  6468. return function (target) {
  6469. target["__bjsclassName__"] = name;
  6470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6471. };
  6472. }
  6473. BABYLON.className = className;
  6474. /**
  6475. * An implementation of a loop for asynchronous functions.
  6476. */
  6477. var AsyncLoop = (function () {
  6478. /**
  6479. * Constroctor.
  6480. * @param iterations the number of iterations.
  6481. * @param _fn the function to run each iteration
  6482. * @param _successCallback the callback that will be called upon succesful execution
  6483. * @param offset starting offset.
  6484. */
  6485. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6486. if (offset === void 0) { offset = 0; }
  6487. this.iterations = iterations;
  6488. this._fn = _fn;
  6489. this._successCallback = _successCallback;
  6490. this.index = offset - 1;
  6491. this._done = false;
  6492. }
  6493. /**
  6494. * Execute the next iteration. Must be called after the last iteration was finished.
  6495. */
  6496. AsyncLoop.prototype.executeNext = function () {
  6497. if (!this._done) {
  6498. if (this.index + 1 < this.iterations) {
  6499. ++this.index;
  6500. this._fn(this);
  6501. }
  6502. else {
  6503. this.breakLoop();
  6504. }
  6505. }
  6506. };
  6507. /**
  6508. * Break the loop and run the success callback.
  6509. */
  6510. AsyncLoop.prototype.breakLoop = function () {
  6511. this._done = true;
  6512. this._successCallback();
  6513. };
  6514. /**
  6515. * Helper function
  6516. */
  6517. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6518. if (offset === void 0) { offset = 0; }
  6519. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6520. loop.executeNext();
  6521. return loop;
  6522. };
  6523. /**
  6524. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6525. * @param iterations total number of iterations
  6526. * @param syncedIterations number of synchronous iterations in each async iteration.
  6527. * @param fn the function to call each iteration.
  6528. * @param callback a success call back that will be called when iterating stops.
  6529. * @param breakFunction a break condition (optional)
  6530. * @param timeout timeout settings for the setTimeout function. default - 0.
  6531. * @constructor
  6532. */
  6533. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6534. if (timeout === void 0) { timeout = 0; }
  6535. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6536. if (breakFunction && breakFunction())
  6537. loop.breakLoop();
  6538. else {
  6539. setTimeout(function () {
  6540. for (var i = 0; i < syncedIterations; ++i) {
  6541. var iteration = (loop.index * syncedIterations) + i;
  6542. if (iteration >= iterations)
  6543. break;
  6544. fn(iteration);
  6545. if (breakFunction && breakFunction()) {
  6546. loop.breakLoop();
  6547. break;
  6548. }
  6549. }
  6550. loop.executeNext();
  6551. }, timeout);
  6552. }
  6553. }, callback);
  6554. };
  6555. return AsyncLoop;
  6556. }());
  6557. BABYLON.AsyncLoop = AsyncLoop;
  6558. })(BABYLON || (BABYLON = {}));
  6559. //# sourceMappingURL=babylon.tools.js.map
  6560. var BABYLON;
  6561. (function (BABYLON) {
  6562. var Internals;
  6563. (function (Internals) {
  6564. var _AlphaState = (function () {
  6565. /**
  6566. * Initializes the state.
  6567. */
  6568. function _AlphaState() {
  6569. this._isAlphaBlendDirty = false;
  6570. this._isBlendFunctionParametersDirty = false;
  6571. this._isBlendEquationParametersDirty = false;
  6572. this._isBlendConstantsDirty = false;
  6573. this._alphaBlend = false;
  6574. this._blendFunctionParameters = new Array(4);
  6575. this._blendEquationParameters = new Array(2);
  6576. this._blendConstants = new Array(4);
  6577. this.reset();
  6578. }
  6579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6580. get: function () {
  6581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6587. get: function () {
  6588. return this._alphaBlend;
  6589. },
  6590. set: function (value) {
  6591. if (this._alphaBlend === value) {
  6592. return;
  6593. }
  6594. this._alphaBlend = value;
  6595. this._isAlphaBlendDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6601. if (this._blendConstants[0] === r &&
  6602. this._blendConstants[1] === g &&
  6603. this._blendConstants[2] === b &&
  6604. this._blendConstants[3] === a) {
  6605. return;
  6606. }
  6607. this._blendConstants[0] = r;
  6608. this._blendConstants[1] = g;
  6609. this._blendConstants[2] = b;
  6610. this._blendConstants[3] = a;
  6611. this._isBlendConstantsDirty = true;
  6612. };
  6613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6614. if (this._blendFunctionParameters[0] === value0 &&
  6615. this._blendFunctionParameters[1] === value1 &&
  6616. this._blendFunctionParameters[2] === value2 &&
  6617. this._blendFunctionParameters[3] === value3) {
  6618. return;
  6619. }
  6620. this._blendFunctionParameters[0] = value0;
  6621. this._blendFunctionParameters[1] = value1;
  6622. this._blendFunctionParameters[2] = value2;
  6623. this._blendFunctionParameters[3] = value3;
  6624. this._isBlendFunctionParametersDirty = true;
  6625. };
  6626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6627. if (this._blendEquationParameters[0] === rgb &&
  6628. this._blendEquationParameters[1] === alpha) {
  6629. return;
  6630. }
  6631. this._blendEquationParameters[0] = rgb;
  6632. this._blendEquationParameters[1] = alpha;
  6633. this._isBlendEquationParametersDirty = true;
  6634. };
  6635. _AlphaState.prototype.reset = function () {
  6636. this._alphaBlend = false;
  6637. this._blendFunctionParameters[0] = null;
  6638. this._blendFunctionParameters[1] = null;
  6639. this._blendFunctionParameters[2] = null;
  6640. this._blendFunctionParameters[3] = null;
  6641. this._blendEquationParameters[0] = null;
  6642. this._blendEquationParameters[1] = null;
  6643. this._blendConstants[0] = null;
  6644. this._blendConstants[1] = null;
  6645. this._blendConstants[2] = null;
  6646. this._blendConstants[3] = null;
  6647. this._isAlphaBlendDirty = true;
  6648. this._isBlendFunctionParametersDirty = false;
  6649. this._isBlendEquationParametersDirty = false;
  6650. this._isBlendConstantsDirty = false;
  6651. };
  6652. _AlphaState.prototype.apply = function (gl) {
  6653. if (!this.isDirty) {
  6654. return;
  6655. }
  6656. // Alpha blend
  6657. if (this._isAlphaBlendDirty) {
  6658. if (this._alphaBlend) {
  6659. gl.enable(gl.BLEND);
  6660. }
  6661. else {
  6662. gl.disable(gl.BLEND);
  6663. }
  6664. this._isAlphaBlendDirty = false;
  6665. }
  6666. // Alpha function
  6667. if (this._isBlendFunctionParametersDirty) {
  6668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6669. this._isBlendFunctionParametersDirty = false;
  6670. }
  6671. // Alpha equation
  6672. if (this._isBlendEquationParametersDirty) {
  6673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6674. this._isBlendEquationParametersDirty = false;
  6675. }
  6676. // Constants
  6677. if (this._isBlendConstantsDirty) {
  6678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6679. this._isBlendConstantsDirty = false;
  6680. }
  6681. };
  6682. return _AlphaState;
  6683. }());
  6684. Internals._AlphaState = _AlphaState;
  6685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6686. })(BABYLON || (BABYLON = {}));
  6687. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6688. var BABYLON;
  6689. (function (BABYLON) {
  6690. var Internals;
  6691. (function (Internals) {
  6692. var _DepthCullingState = (function () {
  6693. /**
  6694. * Initializes the state.
  6695. */
  6696. function _DepthCullingState() {
  6697. this._isDepthTestDirty = false;
  6698. this._isDepthMaskDirty = false;
  6699. this._isDepthFuncDirty = false;
  6700. this._isCullFaceDirty = false;
  6701. this._isCullDirty = false;
  6702. this._isZOffsetDirty = false;
  6703. this.reset();
  6704. }
  6705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6706. get: function () {
  6707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6713. get: function () {
  6714. return this._zOffset;
  6715. },
  6716. set: function (value) {
  6717. if (this._zOffset === value) {
  6718. return;
  6719. }
  6720. this._zOffset = value;
  6721. this._isZOffsetDirty = true;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6727. get: function () {
  6728. return this._cullFace;
  6729. },
  6730. set: function (value) {
  6731. if (this._cullFace === value) {
  6732. return;
  6733. }
  6734. this._cullFace = value;
  6735. this._isCullFaceDirty = true;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6741. get: function () {
  6742. return this._cull;
  6743. },
  6744. set: function (value) {
  6745. if (this._cull === value) {
  6746. return;
  6747. }
  6748. this._cull = value;
  6749. this._isCullDirty = true;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6755. get: function () {
  6756. return this._depthFunc;
  6757. },
  6758. set: function (value) {
  6759. if (this._depthFunc === value) {
  6760. return;
  6761. }
  6762. this._depthFunc = value;
  6763. this._isDepthFuncDirty = true;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6769. get: function () {
  6770. return this._depthMask;
  6771. },
  6772. set: function (value) {
  6773. if (this._depthMask === value) {
  6774. return;
  6775. }
  6776. this._depthMask = value;
  6777. this._isDepthMaskDirty = true;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6783. get: function () {
  6784. return this._depthTest;
  6785. },
  6786. set: function (value) {
  6787. if (this._depthTest === value) {
  6788. return;
  6789. }
  6790. this._depthTest = value;
  6791. this._isDepthTestDirty = true;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. _DepthCullingState.prototype.reset = function () {
  6797. this._depthMask = true;
  6798. this._depthTest = true;
  6799. this._depthFunc = null;
  6800. this._cullFace = null;
  6801. this._cull = null;
  6802. this._zOffset = 0;
  6803. this._isDepthTestDirty = true;
  6804. this._isDepthMaskDirty = true;
  6805. this._isDepthFuncDirty = false;
  6806. this._isCullFaceDirty = false;
  6807. this._isCullDirty = false;
  6808. this._isZOffsetDirty = false;
  6809. };
  6810. _DepthCullingState.prototype.apply = function (gl) {
  6811. if (!this.isDirty) {
  6812. return;
  6813. }
  6814. // Cull
  6815. if (this._isCullDirty) {
  6816. if (this.cull) {
  6817. gl.enable(gl.CULL_FACE);
  6818. }
  6819. else {
  6820. gl.disable(gl.CULL_FACE);
  6821. }
  6822. this._isCullDirty = false;
  6823. }
  6824. // Cull face
  6825. if (this._isCullFaceDirty) {
  6826. gl.cullFace(this.cullFace);
  6827. this._isCullFaceDirty = false;
  6828. }
  6829. // Depth mask
  6830. if (this._isDepthMaskDirty) {
  6831. gl.depthMask(this.depthMask);
  6832. this._isDepthMaskDirty = false;
  6833. }
  6834. // Depth test
  6835. if (this._isDepthTestDirty) {
  6836. if (this.depthTest) {
  6837. gl.enable(gl.DEPTH_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.DEPTH_TEST);
  6841. }
  6842. this._isDepthTestDirty = false;
  6843. }
  6844. // Depth func
  6845. if (this._isDepthFuncDirty) {
  6846. gl.depthFunc(this.depthFunc);
  6847. this._isDepthFuncDirty = false;
  6848. }
  6849. // zOffset
  6850. if (this._isZOffsetDirty) {
  6851. if (this.zOffset) {
  6852. gl.enable(gl.POLYGON_OFFSET_FILL);
  6853. gl.polygonOffset(this.zOffset, 0);
  6854. }
  6855. else {
  6856. gl.disable(gl.POLYGON_OFFSET_FILL);
  6857. }
  6858. this._isZOffsetDirty = false;
  6859. }
  6860. };
  6861. return _DepthCullingState;
  6862. }());
  6863. Internals._DepthCullingState = _DepthCullingState;
  6864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6865. })(BABYLON || (BABYLON = {}));
  6866. //# sourceMappingURL=babylon.depthCullingState.js.map
  6867. var BABYLON;
  6868. (function (BABYLON) {
  6869. var Internals;
  6870. (function (Internals) {
  6871. var _StencilState = (function () {
  6872. function _StencilState() {
  6873. this._isStencilTestDirty = false;
  6874. this._isStencilMaskDirty = false;
  6875. this._isStencilFuncDirty = false;
  6876. this._isStencilOpDirty = false;
  6877. this.reset();
  6878. }
  6879. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6880. get: function () {
  6881. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6887. get: function () {
  6888. return this._stencilFunc;
  6889. },
  6890. set: function (value) {
  6891. if (this._stencilFunc === value) {
  6892. return;
  6893. }
  6894. this._stencilFunc = value;
  6895. this._isStencilFuncDirty = true;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6901. get: function () {
  6902. return this._stencilFuncRef;
  6903. },
  6904. set: function (value) {
  6905. if (this._stencilFuncRef === value) {
  6906. return;
  6907. }
  6908. this._stencilFuncRef = value;
  6909. this._isStencilFuncDirty = true;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6915. get: function () {
  6916. return this._stencilFuncMask;
  6917. },
  6918. set: function (value) {
  6919. if (this._stencilFuncMask === value) {
  6920. return;
  6921. }
  6922. this._stencilFuncMask = value;
  6923. this._isStencilFuncDirty = true;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6929. get: function () {
  6930. return this._stencilOpStencilFail;
  6931. },
  6932. set: function (value) {
  6933. if (this._stencilOpStencilFail === value) {
  6934. return;
  6935. }
  6936. this._stencilOpStencilFail = value;
  6937. this._isStencilOpDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6943. get: function () {
  6944. return this._stencilOpDepthFail;
  6945. },
  6946. set: function (value) {
  6947. if (this._stencilOpDepthFail === value) {
  6948. return;
  6949. }
  6950. this._stencilOpDepthFail = value;
  6951. this._isStencilOpDirty = true;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6957. get: function () {
  6958. return this._stencilOpStencilDepthPass;
  6959. },
  6960. set: function (value) {
  6961. if (this._stencilOpStencilDepthPass === value) {
  6962. return;
  6963. }
  6964. this._stencilOpStencilDepthPass = value;
  6965. this._isStencilOpDirty = true;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6971. get: function () {
  6972. return this._stencilMask;
  6973. },
  6974. set: function (value) {
  6975. if (this._stencilMask === value) {
  6976. return;
  6977. }
  6978. this._stencilMask = value;
  6979. this._isStencilMaskDirty = true;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6985. get: function () {
  6986. return this._stencilTest;
  6987. },
  6988. set: function (value) {
  6989. if (this._stencilTest === value) {
  6990. return;
  6991. }
  6992. this._stencilTest = value;
  6993. this._isStencilTestDirty = true;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. _StencilState.prototype.reset = function () {
  6999. this._stencilTest = false;
  7000. this._stencilMask = 0xFF;
  7001. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7002. this._stencilFuncRef = 1;
  7003. this._stencilFuncMask = 0xFF;
  7004. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7005. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7006. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7007. this._isStencilTestDirty = true;
  7008. this._isStencilMaskDirty = true;
  7009. this._isStencilFuncDirty = true;
  7010. this._isStencilOpDirty = true;
  7011. };
  7012. _StencilState.prototype.apply = function (gl) {
  7013. if (!this.isDirty) {
  7014. return;
  7015. }
  7016. // Stencil test
  7017. if (this._isStencilTestDirty) {
  7018. if (this.stencilTest) {
  7019. gl.enable(gl.STENCIL_TEST);
  7020. }
  7021. else {
  7022. gl.disable(gl.STENCIL_TEST);
  7023. }
  7024. this._isStencilTestDirty = false;
  7025. }
  7026. // Stencil mask
  7027. if (this._isStencilMaskDirty) {
  7028. gl.stencilMask(this.stencilMask);
  7029. this._isStencilMaskDirty = false;
  7030. }
  7031. // Stencil func
  7032. if (this._isStencilFuncDirty) {
  7033. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7034. this._isStencilFuncDirty = false;
  7035. }
  7036. // Stencil op
  7037. if (this._isStencilOpDirty) {
  7038. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7039. this._isStencilOpDirty = false;
  7040. }
  7041. };
  7042. return _StencilState;
  7043. }());
  7044. Internals._StencilState = _StencilState;
  7045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.stencilState.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7051. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7052. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7053. gl.compileShader(shader);
  7054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7055. throw new Error(gl.getShaderInfoLog(shader));
  7056. }
  7057. return shader;
  7058. };
  7059. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7060. var magFilter = gl.NEAREST;
  7061. var minFilter = gl.NEAREST;
  7062. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7063. magFilter = gl.LINEAR;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7066. }
  7067. else {
  7068. minFilter = gl.LINEAR;
  7069. }
  7070. }
  7071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7072. magFilter = gl.LINEAR;
  7073. if (generateMipMaps) {
  7074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7075. }
  7076. else {
  7077. minFilter = gl.LINEAR;
  7078. }
  7079. }
  7080. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7081. magFilter = gl.NEAREST;
  7082. if (generateMipMaps) {
  7083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7084. }
  7085. else {
  7086. minFilter = gl.NEAREST;
  7087. }
  7088. }
  7089. return {
  7090. min: minFilter,
  7091. mag: magFilter
  7092. };
  7093. };
  7094. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7096. var engine = scene.getEngine();
  7097. if (!engine) {
  7098. return;
  7099. }
  7100. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7101. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7102. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7104. texture._baseWidth = width;
  7105. texture._baseHeight = height;
  7106. texture._width = potWidth;
  7107. texture._height = potHeight;
  7108. texture.isReady = true;
  7109. processFunction(potWidth, potHeight);
  7110. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7113. if (!noMipmap && !isCompressed) {
  7114. gl.generateMipmap(gl.TEXTURE_2D);
  7115. }
  7116. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7117. engine.resetTextureCache();
  7118. scene._removePendingData(texture);
  7119. texture.onLoadedCallbacks.forEach(function (callback) {
  7120. callback();
  7121. });
  7122. texture.onLoadedCallbacks = [];
  7123. };
  7124. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7125. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7126. var img;
  7127. var onload = function () {
  7128. loadedImages[index] = img;
  7129. loadedImages._internalCount++;
  7130. scene._removePendingData(img);
  7131. if (loadedImages._internalCount === 6) {
  7132. onfinish(loadedImages);
  7133. }
  7134. };
  7135. var onerror = function () {
  7136. scene._removePendingData(img);
  7137. if (onErrorCallBack) {
  7138. onErrorCallBack();
  7139. }
  7140. };
  7141. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7142. scene._addPendingData(img);
  7143. };
  7144. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7145. if (onError === void 0) { onError = null; }
  7146. var loadedImages = [];
  7147. loadedImages._internalCount = 0;
  7148. for (var index = 0; index < 6; index++) {
  7149. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7150. }
  7151. };
  7152. var InstancingAttributeInfo = (function () {
  7153. function InstancingAttributeInfo() {
  7154. }
  7155. return InstancingAttributeInfo;
  7156. }());
  7157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7158. var EngineCapabilities = (function () {
  7159. function EngineCapabilities() {
  7160. }
  7161. return EngineCapabilities;
  7162. }());
  7163. BABYLON.EngineCapabilities = EngineCapabilities;
  7164. /**
  7165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7166. */
  7167. var Engine = (function () {
  7168. /**
  7169. * @constructor
  7170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7171. * @param {boolean} [antialias] - enable antialias
  7172. * @param options - further options to be sent to the getContext function
  7173. */
  7174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7176. var _this = this;
  7177. // Public members
  7178. this.isFullscreen = false;
  7179. this.isPointerLock = false;
  7180. this.cullBackFaces = true;
  7181. this.renderEvenInBackground = true;
  7182. this.preventCacheWipeBetweenFrames = false;
  7183. // To enable/disable IDB support and avoid XHR on .manifest
  7184. this.enableOfflineSupport = BABYLON.Database;
  7185. this.scenes = new Array();
  7186. // Observables
  7187. /**
  7188. * Observable event triggered each time the rendering canvas is resized
  7189. */
  7190. this.onResizeObservable = new BABYLON.Observable();
  7191. /**
  7192. * Observable event triggered each time the canvas lost focus
  7193. */
  7194. this.onCanvasBlurObservable = new BABYLON.Observable();
  7195. this._windowIsBackground = false;
  7196. this._webGLVersion = 1.0;
  7197. this._badOS = false;
  7198. this._drawCalls = new BABYLON.PerfCounter();
  7199. this._renderingQueueLaunched = false;
  7200. this._activeRenderLoops = [];
  7201. // FPS
  7202. this.fpsRange = 60;
  7203. this.previousFramesDuration = [];
  7204. this.fps = 60;
  7205. this.deltaTime = 0;
  7206. // States
  7207. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7208. this._stencilState = new BABYLON.Internals._StencilState();
  7209. this._alphaState = new BABYLON.Internals._AlphaState();
  7210. this._alphaMode = Engine.ALPHA_DISABLE;
  7211. // Cache
  7212. this._loadedTexturesCache = new Array();
  7213. this._maxTextureChannels = 16;
  7214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7215. this._compiledEffects = {};
  7216. this._vertexAttribArraysEnabled = [];
  7217. this._uintIndicesCurrentlySet = false;
  7218. this._currentBoundBuffer = new Array();
  7219. this._currentBufferPointers = [];
  7220. this._currentInstanceLocations = new Array();
  7221. this._currentInstanceBuffers = new Array();
  7222. this._vaoRecordInProgress = false;
  7223. this._mustWipeVertexAttributes = false;
  7224. // Hardware supported Compressed Textures
  7225. this._texturesSupported = new Array();
  7226. this._onVRFullScreenTriggered = function () {
  7227. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7228. //get the old size before we change
  7229. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7230. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7231. //get the width and height, change the render size
  7232. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7233. var width, height;
  7234. _this.setHardwareScalingLevel(1);
  7235. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7236. }
  7237. else {
  7238. //When the specs are implemented, need to uncomment this.
  7239. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7240. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7241. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7242. _this._vrDisplayEnabled = undefined;
  7243. }
  7244. };
  7245. this._renderingCanvas = canvas;
  7246. Engine.Instances.push(this);
  7247. options = options || {};
  7248. if (antialias != null) {
  7249. options.antialias = antialias;
  7250. }
  7251. if (options.preserveDrawingBuffer === undefined) {
  7252. options.preserveDrawingBuffer = false;
  7253. }
  7254. if (options.audioEngine === undefined) {
  7255. options.audioEngine = true;
  7256. }
  7257. if (options.stencil === undefined) {
  7258. options.stencil = true;
  7259. }
  7260. // GL
  7261. if (!options.disableWebGL2Support) {
  7262. try {
  7263. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7264. if (this._gl) {
  7265. this._webGLVersion = 2.0;
  7266. }
  7267. }
  7268. catch (e) {
  7269. // Do nothing
  7270. }
  7271. }
  7272. if (!this._gl) {
  7273. if (!canvas) {
  7274. throw new Error("The provided canvas is null or undefined.");
  7275. }
  7276. try {
  7277. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7278. }
  7279. catch (e) {
  7280. throw new Error("WebGL not supported");
  7281. }
  7282. }
  7283. if (!this._gl) {
  7284. throw new Error("WebGL not supported");
  7285. }
  7286. this._onBlur = function () {
  7287. _this._windowIsBackground = true;
  7288. };
  7289. this._onFocus = function () {
  7290. _this._windowIsBackground = false;
  7291. };
  7292. this._onCanvasBlur = function () {
  7293. _this.onCanvasBlurObservable.notifyObservers(_this);
  7294. };
  7295. window.addEventListener("blur", this._onBlur);
  7296. window.addEventListener("focus", this._onFocus);
  7297. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7298. // Viewport
  7299. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7300. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7301. this.resize();
  7302. // Caps
  7303. this._isStencilEnable = options.stencil;
  7304. this._caps = new EngineCapabilities();
  7305. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7306. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7307. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7308. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7309. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7310. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7311. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7312. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7313. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7314. // Infos
  7315. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7316. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7317. if (rendererInfo != null) {
  7318. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7319. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7320. }
  7321. if (!this._glVendor) {
  7322. this._glVendor = "Unknown vendor";
  7323. }
  7324. if (!this._glRenderer) {
  7325. this._glRenderer = "Unknown renderer";
  7326. }
  7327. // Extensions
  7328. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7329. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7331. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7332. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7333. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7334. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7335. 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');
  7336. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7337. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7338. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7339. this._caps.highPrecisionShaderSupported = true;
  7340. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7341. // Checks if some of the format renders first to allow the use of webgl inspector.
  7342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7343. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7346. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7347. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7348. if (this._webGLVersion > 1) {
  7349. Engine.HALF_FLOAT_OES = 0x140B;
  7350. }
  7351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7352. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7353. // Vertex array object
  7354. if (this._webGLVersion > 1) {
  7355. this._caps.vertexArrayObject = true;
  7356. }
  7357. else {
  7358. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7359. if (vertexArrayObjectExtension != null) {
  7360. this._caps.vertexArrayObject = true;
  7361. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7362. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7363. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7364. }
  7365. else {
  7366. this._caps.vertexArrayObject = false;
  7367. }
  7368. }
  7369. // Instances count
  7370. if (this._webGLVersion > 1) {
  7371. this._caps.instancedArrays = true;
  7372. }
  7373. else {
  7374. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7375. if (instanceExtension != null) {
  7376. this._caps.instancedArrays = true;
  7377. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7378. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7379. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7380. }
  7381. else {
  7382. this._caps.instancedArrays = false;
  7383. }
  7384. }
  7385. // Intelligently add supported compressed formats in order to check for.
  7386. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7387. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7388. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7389. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7390. if (this._caps.astc)
  7391. this.texturesSupported.push('-astc.ktx');
  7392. if (this._caps.s3tc)
  7393. this.texturesSupported.push('-dxt.ktx');
  7394. if (this._caps.pvrtc)
  7395. this.texturesSupported.push('-pvrtc.ktx');
  7396. if (this._caps.etc2)
  7397. this.texturesSupported.push('-etc2.ktx');
  7398. if (this._caps.etc1)
  7399. this.texturesSupported.push('-etc1.ktx');
  7400. if (this._gl.getShaderPrecisionFormat) {
  7401. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7402. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7403. }
  7404. // Depth buffer
  7405. this.setDepthBuffer(true);
  7406. this.setDepthFunctionToLessOrEqual();
  7407. this.setDepthWrite(true);
  7408. // Fullscreen
  7409. this._onFullscreenChange = function () {
  7410. if (document.fullscreen !== undefined) {
  7411. _this.isFullscreen = document.fullscreen;
  7412. }
  7413. else if (document.mozFullScreen !== undefined) {
  7414. _this.isFullscreen = document.mozFullScreen;
  7415. }
  7416. else if (document.webkitIsFullScreen !== undefined) {
  7417. _this.isFullscreen = document.webkitIsFullScreen;
  7418. }
  7419. else if (document.msIsFullScreen !== undefined) {
  7420. _this.isFullscreen = document.msIsFullScreen;
  7421. }
  7422. // Pointer lock
  7423. if (_this.isFullscreen && _this._pointerLockRequested) {
  7424. canvas.requestPointerLock = canvas.requestPointerLock ||
  7425. canvas.msRequestPointerLock ||
  7426. canvas.mozRequestPointerLock ||
  7427. canvas.webkitRequestPointerLock;
  7428. if (canvas.requestPointerLock) {
  7429. canvas.requestPointerLock();
  7430. }
  7431. }
  7432. };
  7433. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7434. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7435. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7436. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7437. // Pointer lock
  7438. this._onPointerLockChange = function () {
  7439. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7440. document.webkitPointerLockElement === canvas ||
  7441. document.msPointerLockElement === canvas ||
  7442. document.pointerLockElement === canvas);
  7443. };
  7444. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7445. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7446. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7447. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7448. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7449. Engine.audioEngine = new BABYLON.AudioEngine();
  7450. }
  7451. //Load WebVR Devices
  7452. if (options.autoEnableWebVR) {
  7453. this.initWebVR();
  7454. }
  7455. //Detect if we are running on a faulty buggy OS.
  7456. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7457. //ua sniffing is the tool of the devil.
  7458. this._badOS = regexp.test(navigator.userAgent);
  7459. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7460. }
  7461. Object.defineProperty(Engine, "LastCreatedEngine", {
  7462. get: function () {
  7463. if (Engine.Instances.length === 0) {
  7464. return null;
  7465. }
  7466. return Engine.Instances[Engine.Instances.length - 1];
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(Engine, "LastCreatedScene", {
  7472. get: function () {
  7473. var lastCreatedEngine = Engine.LastCreatedEngine;
  7474. if (!lastCreatedEngine) {
  7475. return null;
  7476. }
  7477. if (lastCreatedEngine.scenes.length === 0) {
  7478. return null;
  7479. }
  7480. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. /**
  7486. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7487. */
  7488. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7489. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7490. var engine = Engine.Instances[engineIndex];
  7491. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7492. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7493. }
  7494. }
  7495. };
  7496. Object.defineProperty(Engine, "NEVER", {
  7497. get: function () {
  7498. return Engine._NEVER;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Engine, "ALWAYS", {
  7504. get: function () {
  7505. return Engine._ALWAYS;
  7506. },
  7507. enumerable: true,
  7508. configurable: true
  7509. });
  7510. Object.defineProperty(Engine, "LESS", {
  7511. get: function () {
  7512. return Engine._LESS;
  7513. },
  7514. enumerable: true,
  7515. configurable: true
  7516. });
  7517. Object.defineProperty(Engine, "EQUAL", {
  7518. get: function () {
  7519. return Engine._EQUAL;
  7520. },
  7521. enumerable: true,
  7522. configurable: true
  7523. });
  7524. Object.defineProperty(Engine, "LEQUAL", {
  7525. get: function () {
  7526. return Engine._LEQUAL;
  7527. },
  7528. enumerable: true,
  7529. configurable: true
  7530. });
  7531. Object.defineProperty(Engine, "GREATER", {
  7532. get: function () {
  7533. return Engine._GREATER;
  7534. },
  7535. enumerable: true,
  7536. configurable: true
  7537. });
  7538. Object.defineProperty(Engine, "GEQUAL", {
  7539. get: function () {
  7540. return Engine._GEQUAL;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Engine, "NOTEQUAL", {
  7546. get: function () {
  7547. return Engine._NOTEQUAL;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(Engine, "KEEP", {
  7553. get: function () {
  7554. return Engine._KEEP;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(Engine, "REPLACE", {
  7560. get: function () {
  7561. return Engine._REPLACE;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(Engine, "INCR", {
  7567. get: function () {
  7568. return Engine._INCR;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. Object.defineProperty(Engine, "DECR", {
  7574. get: function () {
  7575. return Engine._DECR;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Engine, "INVERT", {
  7581. get: function () {
  7582. return Engine._INVERT;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Engine, "INCR_WRAP", {
  7588. get: function () {
  7589. return Engine._INCR_WRAP;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Engine, "DECR_WRAP", {
  7595. get: function () {
  7596. return Engine._DECR_WRAP;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7602. get: function () {
  7603. return Engine._ALPHA_DISABLE;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7609. get: function () {
  7610. return Engine._ALPHA_ONEONE;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Engine, "ALPHA_ADD", {
  7616. get: function () {
  7617. return Engine._ALPHA_ADD;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7623. get: function () {
  7624. return Engine._ALPHA_COMBINE;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7630. get: function () {
  7631. return Engine._ALPHA_SUBTRACT;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7637. get: function () {
  7638. return Engine._ALPHA_MULTIPLY;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7644. get: function () {
  7645. return Engine._ALPHA_MAXIMIZED;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7651. get: function () {
  7652. return Engine._ALPHA_PREMULTIPLIED;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7658. get: function () {
  7659. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7665. get: function () {
  7666. return Engine._ALPHA_INTERPOLATE;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7672. get: function () {
  7673. return Engine._ALPHA_SCREENMODE;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7679. get: function () {
  7680. return Engine._DELAYLOADSTATE_NONE;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7686. get: function () {
  7687. return Engine._DELAYLOADSTATE_LOADED;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7693. get: function () {
  7694. return Engine._DELAYLOADSTATE_LOADING;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7700. get: function () {
  7701. return Engine._DELAYLOADSTATE_NOTLOADED;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7707. get: function () {
  7708. return Engine._TEXTUREFORMAT_ALPHA;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7714. get: function () {
  7715. return Engine._TEXTUREFORMAT_LUMINANCE;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7721. get: function () {
  7722. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7723. },
  7724. enumerable: true,
  7725. configurable: true
  7726. });
  7727. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7728. get: function () {
  7729. return Engine._TEXTUREFORMAT_RGB;
  7730. },
  7731. enumerable: true,
  7732. configurable: true
  7733. });
  7734. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7735. get: function () {
  7736. return Engine._TEXTUREFORMAT_RGBA;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7742. get: function () {
  7743. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7744. },
  7745. enumerable: true,
  7746. configurable: true
  7747. });
  7748. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7749. get: function () {
  7750. return Engine._TEXTURETYPE_FLOAT;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7756. get: function () {
  7757. return Engine._TEXTURETYPE_HALF_FLOAT;
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7763. get: function () {
  7764. return Engine._SCALEMODE_FLOOR;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7770. get: function () {
  7771. return Engine._SCALEMODE_NEAREST;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7777. get: function () {
  7778. return Engine._SCALEMODE_CEILING;
  7779. },
  7780. enumerable: true,
  7781. configurable: true
  7782. });
  7783. Object.defineProperty(Engine, "Version", {
  7784. get: function () {
  7785. return "3.0-rc";
  7786. },
  7787. enumerable: true,
  7788. configurable: true
  7789. });
  7790. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7791. get: function () {
  7792. return this._texturesSupported;
  7793. },
  7794. enumerable: true,
  7795. configurable: true
  7796. });
  7797. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7798. get: function () {
  7799. return this._textureFormatInUse;
  7800. },
  7801. enumerable: true,
  7802. configurable: true
  7803. });
  7804. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7805. // Empty texture
  7806. get: function () {
  7807. if (!this._emptyTexture) {
  7808. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7809. }
  7810. return this._emptyTexture;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7816. get: function () {
  7817. if (!this._emptyCubeTexture) {
  7818. var faceData = new Uint8Array(4);
  7819. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7820. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7821. }
  7822. return this._emptyCubeTexture;
  7823. },
  7824. enumerable: true,
  7825. configurable: true
  7826. });
  7827. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7828. get: function () {
  7829. return this._webGLVersion;
  7830. },
  7831. enumerable: true,
  7832. configurable: true
  7833. });
  7834. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7835. /**
  7836. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7837. */
  7838. get: function () {
  7839. return this._isStencilEnable;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Engine.prototype._prepareWorkingCanvas = function () {
  7845. if (this._workingCanvas) {
  7846. return;
  7847. }
  7848. this._workingCanvas = document.createElement("canvas");
  7849. this._workingContext = this._workingCanvas.getContext("2d");
  7850. };
  7851. Engine.prototype.resetTextureCache = function () {
  7852. for (var index = 0; index < this._maxTextureChannels; index++) {
  7853. this._activeTexturesCache[index] = null;
  7854. }
  7855. };
  7856. Engine.prototype.getGlInfo = function () {
  7857. return {
  7858. vendor: this._glVendor,
  7859. renderer: this._glRenderer,
  7860. version: this._glVersion
  7861. };
  7862. };
  7863. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7864. if (useScreen === void 0) { useScreen = false; }
  7865. var viewport = camera.viewport;
  7866. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7867. };
  7868. Engine.prototype.getRenderWidth = function (useScreen) {
  7869. if (useScreen === void 0) { useScreen = false; }
  7870. if (!useScreen && this._currentRenderTarget) {
  7871. return this._currentRenderTarget._width;
  7872. }
  7873. return this._renderingCanvas.width;
  7874. };
  7875. Engine.prototype.getRenderHeight = function (useScreen) {
  7876. if (useScreen === void 0) { useScreen = false; }
  7877. if (!useScreen && this._currentRenderTarget) {
  7878. return this._currentRenderTarget._height;
  7879. }
  7880. return this._renderingCanvas.height;
  7881. };
  7882. Engine.prototype.getRenderingCanvas = function () {
  7883. return this._renderingCanvas;
  7884. };
  7885. Engine.prototype.getRenderingCanvasClientRect = function () {
  7886. return this._renderingCanvas.getBoundingClientRect();
  7887. };
  7888. Engine.prototype.setHardwareScalingLevel = function (level) {
  7889. this._hardwareScalingLevel = level;
  7890. this.resize();
  7891. };
  7892. Engine.prototype.getHardwareScalingLevel = function () {
  7893. return this._hardwareScalingLevel;
  7894. };
  7895. Engine.prototype.getLoadedTexturesCache = function () {
  7896. return this._loadedTexturesCache;
  7897. };
  7898. Engine.prototype.getCaps = function () {
  7899. return this._caps;
  7900. };
  7901. Object.defineProperty(Engine.prototype, "drawCalls", {
  7902. get: function () {
  7903. return this._drawCalls.current;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7909. get: function () {
  7910. return this._drawCalls;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Engine.prototype.getDepthFunction = function () {
  7916. return this._depthCullingState.depthFunc;
  7917. };
  7918. Engine.prototype.setDepthFunction = function (depthFunc) {
  7919. this._depthCullingState.depthFunc = depthFunc;
  7920. };
  7921. Engine.prototype.setDepthFunctionToGreater = function () {
  7922. this._depthCullingState.depthFunc = this._gl.GREATER;
  7923. };
  7924. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7925. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7926. };
  7927. Engine.prototype.setDepthFunctionToLess = function () {
  7928. this._depthCullingState.depthFunc = this._gl.LESS;
  7929. };
  7930. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7931. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7932. };
  7933. Engine.prototype.getStencilBuffer = function () {
  7934. return this._stencilState.stencilTest;
  7935. };
  7936. Engine.prototype.setStencilBuffer = function (enable) {
  7937. this._stencilState.stencilTest = enable;
  7938. };
  7939. Engine.prototype.getStencilMask = function () {
  7940. return this._stencilState.stencilMask;
  7941. };
  7942. Engine.prototype.setStencilMask = function (mask) {
  7943. this._stencilState.stencilMask = mask;
  7944. };
  7945. Engine.prototype.getStencilFunction = function () {
  7946. return this._stencilState.stencilFunc;
  7947. };
  7948. Engine.prototype.getStencilFunctionReference = function () {
  7949. return this._stencilState.stencilFuncRef;
  7950. };
  7951. Engine.prototype.getStencilFunctionMask = function () {
  7952. return this._stencilState.stencilFuncMask;
  7953. };
  7954. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7955. this._stencilState.stencilFunc = stencilFunc;
  7956. };
  7957. Engine.prototype.setStencilFunctionReference = function (reference) {
  7958. this._stencilState.stencilFuncRef = reference;
  7959. };
  7960. Engine.prototype.setStencilFunctionMask = function (mask) {
  7961. this._stencilState.stencilFuncMask = mask;
  7962. };
  7963. Engine.prototype.getStencilOperationFail = function () {
  7964. return this._stencilState.stencilOpStencilFail;
  7965. };
  7966. Engine.prototype.getStencilOperationDepthFail = function () {
  7967. return this._stencilState.stencilOpDepthFail;
  7968. };
  7969. Engine.prototype.getStencilOperationPass = function () {
  7970. return this._stencilState.stencilOpStencilDepthPass;
  7971. };
  7972. Engine.prototype.setStencilOperationFail = function (operation) {
  7973. this._stencilState.stencilOpStencilFail = operation;
  7974. };
  7975. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7976. this._stencilState.stencilOpDepthFail = operation;
  7977. };
  7978. Engine.prototype.setStencilOperationPass = function (operation) {
  7979. this._stencilState.stencilOpStencilDepthPass = operation;
  7980. };
  7981. Engine.prototype.setDitheringState = function (value) {
  7982. if (value) {
  7983. this._gl.enable(this._gl.DITHER);
  7984. }
  7985. else {
  7986. this._gl.disable(this._gl.DITHER);
  7987. }
  7988. };
  7989. /**
  7990. * stop executing a render loop function and remove it from the execution array
  7991. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7992. */
  7993. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7994. if (!renderFunction) {
  7995. this._activeRenderLoops = [];
  7996. return;
  7997. }
  7998. var index = this._activeRenderLoops.indexOf(renderFunction);
  7999. if (index >= 0) {
  8000. this._activeRenderLoops.splice(index, 1);
  8001. }
  8002. };
  8003. Engine.prototype._renderLoop = function () {
  8004. var shouldRender = true;
  8005. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8006. shouldRender = false;
  8007. }
  8008. if (shouldRender) {
  8009. // Start new frame
  8010. this.beginFrame();
  8011. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8012. var renderFunction = this._activeRenderLoops[index];
  8013. renderFunction();
  8014. }
  8015. // Present
  8016. this.endFrame();
  8017. }
  8018. if (this._activeRenderLoops.length > 0) {
  8019. // Register new frame
  8020. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8021. }
  8022. else {
  8023. this._renderingQueueLaunched = false;
  8024. }
  8025. };
  8026. /**
  8027. * Register and execute a render loop. The engine can have more than one render function.
  8028. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8029. * @example
  8030. * engine.runRenderLoop(function () {
  8031. * scene.render()
  8032. * })
  8033. */
  8034. Engine.prototype.runRenderLoop = function (renderFunction) {
  8035. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8036. return;
  8037. }
  8038. this._activeRenderLoops.push(renderFunction);
  8039. if (!this._renderingQueueLaunched) {
  8040. this._renderingQueueLaunched = true;
  8041. this._bindedRenderFunction = this._renderLoop.bind(this);
  8042. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8043. }
  8044. };
  8045. /**
  8046. * Toggle full screen mode.
  8047. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8048. * @param {any} options - an options object to be sent to the requestFullscreen function
  8049. */
  8050. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8051. if (this.isFullscreen) {
  8052. BABYLON.Tools.ExitFullscreen();
  8053. }
  8054. else {
  8055. this._pointerLockRequested = requestPointerLock;
  8056. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8057. }
  8058. };
  8059. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8060. if (stencil === void 0) { stencil = false; }
  8061. this.applyStates();
  8062. var mode = 0;
  8063. if (backBuffer && color) {
  8064. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8065. mode |= this._gl.COLOR_BUFFER_BIT;
  8066. }
  8067. if (depth) {
  8068. this._gl.clearDepth(1.0);
  8069. mode |= this._gl.DEPTH_BUFFER_BIT;
  8070. }
  8071. if (stencil) {
  8072. this._gl.clearStencil(0);
  8073. mode |= this._gl.STENCIL_BUFFER_BIT;
  8074. }
  8075. this._gl.clear(mode);
  8076. };
  8077. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8078. var gl = this._gl;
  8079. // Save state
  8080. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8081. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8082. // Change state
  8083. gl.enable(gl.SCISSOR_TEST);
  8084. gl.scissor(x, y, width, height);
  8085. // Clear
  8086. this.clear(clearColor, true, true, true);
  8087. // Restore state
  8088. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8089. if (curScissor === true) {
  8090. gl.enable(gl.SCISSOR_TEST);
  8091. }
  8092. else {
  8093. gl.disable(gl.SCISSOR_TEST);
  8094. }
  8095. };
  8096. /**
  8097. * Set the WebGL's viewport
  8098. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8099. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8100. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8101. */
  8102. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8103. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8104. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8105. var x = viewport.x || 0;
  8106. var y = viewport.y || 0;
  8107. this._cachedViewport = viewport;
  8108. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8109. };
  8110. /**
  8111. * Directly set the WebGL Viewport
  8112. * The x, y, width & height are directly passed to the WebGL call
  8113. * @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.
  8114. */
  8115. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8116. var currentViewport = this._cachedViewport;
  8117. this._cachedViewport = null;
  8118. this._gl.viewport(x, y, width, height);
  8119. return currentViewport;
  8120. };
  8121. Engine.prototype.beginFrame = function () {
  8122. this._measureFps();
  8123. };
  8124. Engine.prototype.endFrame = function () {
  8125. //force a flush in case we are using a bad OS.
  8126. if (this._badOS) {
  8127. this.flushFramebuffer();
  8128. }
  8129. //submit frame to the vr device, if enabled
  8130. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8131. this._vrDisplayEnabled.submitFrame();
  8132. }
  8133. };
  8134. /**
  8135. * resize the view according to the canvas' size.
  8136. * @example
  8137. * window.addEventListener("resize", function () {
  8138. * engine.resize();
  8139. * });
  8140. */
  8141. Engine.prototype.resize = function () {
  8142. // We're not resizing the size of the canvas while in VR mode & presenting
  8143. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8144. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8145. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8146. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8147. }
  8148. };
  8149. /**
  8150. * force a specific size of the canvas
  8151. * @param {number} width - the new canvas' width
  8152. * @param {number} height - the new canvas' height
  8153. */
  8154. Engine.prototype.setSize = function (width, height) {
  8155. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8156. return;
  8157. }
  8158. this._renderingCanvas.width = width;
  8159. this._renderingCanvas.height = height;
  8160. for (var index = 0; index < this.scenes.length; index++) {
  8161. var scene = this.scenes[index];
  8162. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8163. var cam = scene.cameras[camIndex];
  8164. cam._currentRenderId = 0;
  8165. }
  8166. }
  8167. if (this.onResizeObservable.hasObservers) {
  8168. this.onResizeObservable.notifyObservers(this);
  8169. }
  8170. };
  8171. //WebVR functions
  8172. Engine.prototype.isVRDevicePresent = function (callback) {
  8173. this.getVRDevice(null, function (device) {
  8174. callback(device !== null);
  8175. });
  8176. };
  8177. Engine.prototype.getVRDevice = function (name, callback) {
  8178. if (!this.vrDisplaysPromise) {
  8179. callback(null);
  8180. return;
  8181. }
  8182. this.vrDisplaysPromise.then(function (devices) {
  8183. if (devices.length > 0) {
  8184. if (name) {
  8185. var found = devices.some(function (device) {
  8186. if (device.displayName === name) {
  8187. callback(device);
  8188. return true;
  8189. }
  8190. else {
  8191. return false;
  8192. }
  8193. });
  8194. if (!found) {
  8195. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8196. callback(devices[0]);
  8197. }
  8198. }
  8199. else {
  8200. //choose the first one
  8201. callback(devices[0]);
  8202. }
  8203. }
  8204. else {
  8205. BABYLON.Tools.Error("No WebVR devices found!");
  8206. callback(null);
  8207. }
  8208. });
  8209. };
  8210. Engine.prototype.initWebVR = function () {
  8211. if (!this.vrDisplaysPromise) {
  8212. this._getVRDisplays();
  8213. }
  8214. };
  8215. Engine.prototype.enableVR = function (vrDevice) {
  8216. this._vrDisplayEnabled = vrDevice;
  8217. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8218. };
  8219. Engine.prototype.disableVR = function () {
  8220. if (this._vrDisplayEnabled) {
  8221. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8222. }
  8223. };
  8224. Engine.prototype._getVRDisplays = function () {
  8225. var _this = this;
  8226. var getWebVRDevices = function (devices) {
  8227. var size = devices.length;
  8228. var i = 0;
  8229. _this._vrDisplays = devices.filter(function (device) {
  8230. return devices[i] instanceof VRDisplay;
  8231. });
  8232. return _this._vrDisplays;
  8233. };
  8234. //using a key due to typescript
  8235. if (navigator.getVRDisplays) {
  8236. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8237. }
  8238. };
  8239. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8240. this._currentRenderTarget = texture;
  8241. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8242. var gl = this._gl;
  8243. if (texture.isCube) {
  8244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8245. }
  8246. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8247. this.wipeCaches();
  8248. };
  8249. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8250. if (this._currentFramebuffer !== framebuffer) {
  8251. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8252. this._currentFramebuffer = framebuffer;
  8253. }
  8254. };
  8255. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8256. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8257. this._currentRenderTarget = null;
  8258. // If MSAA, we need to bitblt back to main texture
  8259. var gl = this._gl;
  8260. if (texture._MSAAFramebuffer) {
  8261. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8262. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8263. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8264. }
  8265. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8266. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8267. gl.generateMipmap(gl.TEXTURE_2D);
  8268. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8269. }
  8270. if (onBeforeUnbind) {
  8271. if (texture._MSAAFramebuffer) {
  8272. // Bind the correct framebuffer
  8273. this.bindUnboundFramebuffer(texture._framebuffer);
  8274. }
  8275. onBeforeUnbind();
  8276. }
  8277. this.bindUnboundFramebuffer(null);
  8278. };
  8279. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8280. if (texture.generateMipMaps) {
  8281. var gl = this._gl;
  8282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8283. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8285. }
  8286. };
  8287. Engine.prototype.flushFramebuffer = function () {
  8288. this._gl.flush();
  8289. };
  8290. Engine.prototype.restoreDefaultFramebuffer = function () {
  8291. this._currentRenderTarget = null;
  8292. this.bindUnboundFramebuffer(null);
  8293. if (this._cachedViewport) {
  8294. this.setViewport(this._cachedViewport);
  8295. }
  8296. this.wipeCaches();
  8297. };
  8298. // UBOs
  8299. Engine.prototype.createUniformBuffer = function (elements) {
  8300. var ubo = this._gl.createBuffer();
  8301. this.bindUniformBuffer(ubo);
  8302. if (elements instanceof Float32Array) {
  8303. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8304. }
  8305. else {
  8306. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8307. }
  8308. this.bindUniformBuffer(null);
  8309. ubo.references = 1;
  8310. return ubo;
  8311. };
  8312. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8313. var ubo = this._gl.createBuffer();
  8314. this.bindUniformBuffer(ubo);
  8315. if (elements instanceof Float32Array) {
  8316. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8317. }
  8318. else {
  8319. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8320. }
  8321. this.bindUniformBuffer(null);
  8322. ubo.references = 1;
  8323. return ubo;
  8324. };
  8325. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8326. this.bindUniformBuffer(uniformBuffer);
  8327. if (offset === undefined) {
  8328. offset = 0;
  8329. }
  8330. if (count === undefined) {
  8331. if (elements instanceof Float32Array) {
  8332. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8333. }
  8334. else {
  8335. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8336. }
  8337. }
  8338. else {
  8339. if (elements instanceof Float32Array) {
  8340. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8341. }
  8342. else {
  8343. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8344. }
  8345. }
  8346. this.bindUniformBuffer(null);
  8347. };
  8348. // VBOs
  8349. Engine.prototype._resetVertexBufferBinding = function () {
  8350. this.bindArrayBuffer(null);
  8351. this._cachedVertexBuffers = null;
  8352. };
  8353. Engine.prototype.createVertexBuffer = function (vertices) {
  8354. var vbo = this._gl.createBuffer();
  8355. this.bindArrayBuffer(vbo);
  8356. if (vertices instanceof Float32Array) {
  8357. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8358. }
  8359. else {
  8360. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8361. }
  8362. this._resetVertexBufferBinding();
  8363. vbo.references = 1;
  8364. return vbo;
  8365. };
  8366. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8367. var vbo = this._gl.createBuffer();
  8368. this.bindArrayBuffer(vbo);
  8369. if (vertices instanceof Float32Array) {
  8370. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8371. }
  8372. else {
  8373. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8374. }
  8375. this._resetVertexBufferBinding();
  8376. vbo.references = 1;
  8377. return vbo;
  8378. };
  8379. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8380. this.bindArrayBuffer(vertexBuffer);
  8381. if (offset === undefined) {
  8382. offset = 0;
  8383. }
  8384. if (count === undefined) {
  8385. if (vertices instanceof Float32Array) {
  8386. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8387. }
  8388. else {
  8389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8390. }
  8391. }
  8392. else {
  8393. if (vertices instanceof Float32Array) {
  8394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8395. }
  8396. else {
  8397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8398. }
  8399. }
  8400. this._resetVertexBufferBinding();
  8401. };
  8402. Engine.prototype._resetIndexBufferBinding = function () {
  8403. this.bindIndexBuffer(null);
  8404. this._cachedIndexBuffer = null;
  8405. };
  8406. Engine.prototype.createIndexBuffer = function (indices) {
  8407. var vbo = this._gl.createBuffer();
  8408. this.bindIndexBuffer(vbo);
  8409. // Check for 32 bits indices
  8410. var arrayBuffer;
  8411. var need32Bits = false;
  8412. if (indices instanceof Uint16Array) {
  8413. arrayBuffer = indices;
  8414. }
  8415. else {
  8416. //check 32 bit support
  8417. if (this._caps.uintIndices) {
  8418. if (indices instanceof Uint32Array) {
  8419. arrayBuffer = indices;
  8420. need32Bits = true;
  8421. }
  8422. else {
  8423. //number[] or Int32Array, check if 32 bit is necessary
  8424. for (var index = 0; index < indices.length; index++) {
  8425. if (indices[index] > 65535) {
  8426. need32Bits = true;
  8427. break;
  8428. }
  8429. }
  8430. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8431. }
  8432. }
  8433. else {
  8434. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8435. arrayBuffer = new Uint16Array(indices);
  8436. }
  8437. }
  8438. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8439. this._resetIndexBufferBinding();
  8440. vbo.references = 1;
  8441. vbo.is32Bits = need32Bits;
  8442. return vbo;
  8443. };
  8444. Engine.prototype.bindArrayBuffer = function (buffer) {
  8445. if (!this._vaoRecordInProgress) {
  8446. this._unBindVertexArrayObject();
  8447. }
  8448. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8449. };
  8450. Engine.prototype.bindUniformBuffer = function (buffer) {
  8451. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8452. };
  8453. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8454. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8455. };
  8456. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8457. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8458. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8459. };
  8460. ;
  8461. Engine.prototype.bindIndexBuffer = function (buffer) {
  8462. if (!this._vaoRecordInProgress) {
  8463. this._unBindVertexArrayObject();
  8464. }
  8465. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8466. };
  8467. Engine.prototype.bindBuffer = function (buffer, target) {
  8468. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8469. this._gl.bindBuffer(target, buffer);
  8470. this._currentBoundBuffer[target] = buffer;
  8471. }
  8472. };
  8473. Engine.prototype.updateArrayBuffer = function (data) {
  8474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8475. };
  8476. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8477. var pointer = this._currentBufferPointers[indx];
  8478. var changed = false;
  8479. if (!pointer) {
  8480. changed = true;
  8481. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8482. }
  8483. else {
  8484. if (pointer.buffer !== buffer) {
  8485. pointer.buffer = buffer;
  8486. changed = true;
  8487. }
  8488. if (pointer.size !== size) {
  8489. pointer.size = size;
  8490. changed = true;
  8491. }
  8492. if (pointer.type !== type) {
  8493. pointer.type = type;
  8494. changed = true;
  8495. }
  8496. if (pointer.normalized !== normalized) {
  8497. pointer.normalized = normalized;
  8498. changed = true;
  8499. }
  8500. if (pointer.stride !== stride) {
  8501. pointer.stride = stride;
  8502. changed = true;
  8503. }
  8504. if (pointer.offset !== offset) {
  8505. pointer.offset = offset;
  8506. changed = true;
  8507. }
  8508. }
  8509. if (changed || this._vaoRecordInProgress) {
  8510. this.bindArrayBuffer(buffer);
  8511. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8512. }
  8513. };
  8514. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8515. if (indexBuffer == null) {
  8516. return;
  8517. }
  8518. if (this._cachedIndexBuffer !== indexBuffer) {
  8519. this._cachedIndexBuffer = indexBuffer;
  8520. this.bindIndexBuffer(indexBuffer);
  8521. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8522. }
  8523. };
  8524. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8525. var attributes = effect.getAttributesNames();
  8526. if (!this._vaoRecordInProgress) {
  8527. this._unBindVertexArrayObject();
  8528. }
  8529. this.unbindAllAttributes();
  8530. for (var index = 0; index < attributes.length; index++) {
  8531. var order = effect.getAttributeLocation(index);
  8532. if (order >= 0) {
  8533. var vertexBuffer = vertexBuffers[attributes[index]];
  8534. if (!vertexBuffer) {
  8535. continue;
  8536. }
  8537. this._gl.enableVertexAttribArray(order);
  8538. if (!this._vaoRecordInProgress) {
  8539. this._vertexAttribArraysEnabled[order] = true;
  8540. }
  8541. var buffer = vertexBuffer.getBuffer();
  8542. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8543. if (vertexBuffer.getIsInstanced()) {
  8544. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8545. if (!this._vaoRecordInProgress) {
  8546. this._currentInstanceLocations.push(order);
  8547. this._currentInstanceBuffers.push(buffer);
  8548. }
  8549. }
  8550. }
  8551. }
  8552. };
  8553. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8554. var vao = this._gl.createVertexArray();
  8555. this._vaoRecordInProgress = true;
  8556. this._gl.bindVertexArray(vao);
  8557. this._mustWipeVertexAttributes = true;
  8558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8559. this.bindIndexBuffer(indexBuffer);
  8560. this._vaoRecordInProgress = false;
  8561. this._gl.bindVertexArray(null);
  8562. return vao;
  8563. };
  8564. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8565. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8566. this._cachedVertexArrayObject = vertexArrayObject;
  8567. this._gl.bindVertexArray(vertexArrayObject);
  8568. this._cachedVertexBuffers = null;
  8569. this._cachedIndexBuffer = null;
  8570. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8571. this._mustWipeVertexAttributes = true;
  8572. }
  8573. };
  8574. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8575. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8576. this._cachedVertexBuffers = vertexBuffer;
  8577. this._cachedEffectForVertexBuffers = effect;
  8578. var attributesCount = effect.getAttributesCount();
  8579. this._unBindVertexArrayObject();
  8580. this.unbindAllAttributes();
  8581. var offset = 0;
  8582. for (var index = 0; index < attributesCount; index++) {
  8583. if (index < vertexDeclaration.length) {
  8584. var order = effect.getAttributeLocation(index);
  8585. if (order >= 0) {
  8586. this._gl.enableVertexAttribArray(order);
  8587. this._vertexAttribArraysEnabled[order] = true;
  8588. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8589. }
  8590. offset += vertexDeclaration[index] * 4;
  8591. }
  8592. }
  8593. }
  8594. this._bindIndexBufferWithCache(indexBuffer);
  8595. };
  8596. Engine.prototype._unBindVertexArrayObject = function () {
  8597. if (!this._cachedVertexArrayObject) {
  8598. return;
  8599. }
  8600. this._cachedVertexArrayObject = null;
  8601. this._gl.bindVertexArray(null);
  8602. };
  8603. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8604. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8605. this._cachedVertexBuffers = vertexBuffers;
  8606. this._cachedEffectForVertexBuffers = effect;
  8607. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8608. }
  8609. this._bindIndexBufferWithCache(indexBuffer);
  8610. };
  8611. Engine.prototype.unbindInstanceAttributes = function () {
  8612. var boundBuffer;
  8613. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8614. var instancesBuffer = this._currentInstanceBuffers[i];
  8615. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8616. boundBuffer = instancesBuffer;
  8617. this.bindArrayBuffer(instancesBuffer);
  8618. }
  8619. var offsetLocation = this._currentInstanceLocations[i];
  8620. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8621. }
  8622. this._currentInstanceBuffers.length = 0;
  8623. this._currentInstanceLocations.length = 0;
  8624. };
  8625. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8626. this._gl.deleteVertexArray(vao);
  8627. };
  8628. Engine.prototype._releaseBuffer = function (buffer) {
  8629. buffer.references--;
  8630. if (buffer.references === 0) {
  8631. this._gl.deleteBuffer(buffer);
  8632. return true;
  8633. }
  8634. return false;
  8635. };
  8636. Engine.prototype.createInstancesBuffer = function (capacity) {
  8637. var buffer = this._gl.createBuffer();
  8638. buffer.capacity = capacity;
  8639. this.bindArrayBuffer(buffer);
  8640. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8641. return buffer;
  8642. };
  8643. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8644. this._gl.deleteBuffer(buffer);
  8645. };
  8646. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8647. this.bindArrayBuffer(instancesBuffer);
  8648. if (data) {
  8649. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8650. }
  8651. if (offsetLocations[0].index !== undefined) {
  8652. var stride = 0;
  8653. for (var i = 0; i < offsetLocations.length; i++) {
  8654. var ai = offsetLocations[i];
  8655. stride += ai.attributeSize * 4;
  8656. }
  8657. for (var i = 0; i < offsetLocations.length; i++) {
  8658. var ai = offsetLocations[i];
  8659. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8660. this._gl.enableVertexAttribArray(ai.index);
  8661. this._vertexAttribArraysEnabled[ai.index] = true;
  8662. }
  8663. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8664. this._gl.vertexAttribDivisor(ai.index, 1);
  8665. this._currentInstanceLocations.push(ai.index);
  8666. this._currentInstanceBuffers.push(instancesBuffer);
  8667. }
  8668. }
  8669. else {
  8670. for (var index = 0; index < 4; index++) {
  8671. var offsetLocation = offsetLocations[index];
  8672. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8673. this._gl.enableVertexAttribArray(offsetLocation);
  8674. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8675. }
  8676. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8677. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8678. this._currentInstanceLocations.push(offsetLocation);
  8679. this._currentInstanceBuffers.push(instancesBuffer);
  8680. }
  8681. }
  8682. };
  8683. Engine.prototype.applyStates = function () {
  8684. this._depthCullingState.apply(this._gl);
  8685. this._stencilState.apply(this._gl);
  8686. this._alphaState.apply(this._gl);
  8687. };
  8688. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8689. // Apply states
  8690. this.applyStates();
  8691. this._drawCalls.addCount(1, false);
  8692. // Render
  8693. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8694. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8695. if (instancesCount) {
  8696. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8697. return;
  8698. }
  8699. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8700. };
  8701. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8702. // Apply states
  8703. this.applyStates();
  8704. this._drawCalls.addCount(1, false);
  8705. if (instancesCount) {
  8706. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8707. return;
  8708. }
  8709. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8710. };
  8711. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8712. // Apply states
  8713. this.applyStates();
  8714. this._drawCalls.addCount(1, false);
  8715. if (instancesCount) {
  8716. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8717. return;
  8718. }
  8719. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8720. };
  8721. // Shaders
  8722. Engine.prototype._releaseEffect = function (effect) {
  8723. if (this._compiledEffects[effect._key]) {
  8724. delete this._compiledEffects[effect._key];
  8725. if (effect.getProgram()) {
  8726. this._gl.deleteProgram(effect.getProgram());
  8727. }
  8728. }
  8729. };
  8730. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8731. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8732. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8733. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8734. if (this._compiledEffects[name]) {
  8735. var compiledEffect = this._compiledEffects[name];
  8736. if (onCompiled && compiledEffect.isReady()) {
  8737. onCompiled(compiledEffect);
  8738. }
  8739. return compiledEffect;
  8740. }
  8741. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8742. effect._key = name;
  8743. this._compiledEffects[name] = effect;
  8744. return effect;
  8745. };
  8746. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8747. if (uniformsNames === void 0) { uniformsNames = []; }
  8748. if (samplers === void 0) { samplers = []; }
  8749. if (defines === void 0) { defines = ""; }
  8750. return this.createEffect({
  8751. vertex: "particles",
  8752. fragmentElement: fragmentName
  8753. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8754. };
  8755. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8756. context = context || this._gl;
  8757. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8758. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8759. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8760. var shaderProgram = context.createProgram();
  8761. context.attachShader(shaderProgram, vertexShader);
  8762. context.attachShader(shaderProgram, fragmentShader);
  8763. context.linkProgram(shaderProgram);
  8764. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8765. if (!linked) {
  8766. var error = context.getProgramInfoLog(shaderProgram);
  8767. if (error) {
  8768. throw new Error(error);
  8769. }
  8770. }
  8771. context.deleteShader(vertexShader);
  8772. context.deleteShader(fragmentShader);
  8773. return shaderProgram;
  8774. };
  8775. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8776. var results = [];
  8777. for (var index = 0; index < uniformsNames.length; index++) {
  8778. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8779. }
  8780. return results;
  8781. };
  8782. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8783. var results = [];
  8784. for (var index = 0; index < attributesNames.length; index++) {
  8785. try {
  8786. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8787. }
  8788. catch (e) {
  8789. results.push(-1);
  8790. }
  8791. }
  8792. return results;
  8793. };
  8794. Engine.prototype.enableEffect = function (effect) {
  8795. // Use program
  8796. this.setProgram(effect.getProgram());
  8797. this._currentEffect = effect;
  8798. if (effect.onBind) {
  8799. effect.onBind(effect);
  8800. }
  8801. effect.onBindObservable.notifyObservers(effect);
  8802. };
  8803. Engine.prototype.setIntArray = function (uniform, array) {
  8804. if (!uniform)
  8805. return;
  8806. this._gl.uniform1iv(uniform, array);
  8807. };
  8808. Engine.prototype.setIntArray2 = function (uniform, array) {
  8809. if (!uniform || array.length % 2 !== 0)
  8810. return;
  8811. this._gl.uniform2iv(uniform, array);
  8812. };
  8813. Engine.prototype.setIntArray3 = function (uniform, array) {
  8814. if (!uniform || array.length % 3 !== 0)
  8815. return;
  8816. this._gl.uniform3iv(uniform, array);
  8817. };
  8818. Engine.prototype.setIntArray4 = function (uniform, array) {
  8819. if (!uniform || array.length % 4 !== 0)
  8820. return;
  8821. this._gl.uniform4iv(uniform, array);
  8822. };
  8823. Engine.prototype.setFloatArray = function (uniform, array) {
  8824. if (!uniform)
  8825. return;
  8826. this._gl.uniform1fv(uniform, array);
  8827. };
  8828. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8829. if (!uniform || array.length % 2 !== 0)
  8830. return;
  8831. this._gl.uniform2fv(uniform, array);
  8832. };
  8833. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8834. if (!uniform || array.length % 3 !== 0)
  8835. return;
  8836. this._gl.uniform3fv(uniform, array);
  8837. };
  8838. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8839. if (!uniform || array.length % 4 !== 0)
  8840. return;
  8841. this._gl.uniform4fv(uniform, array);
  8842. };
  8843. Engine.prototype.setArray = function (uniform, array) {
  8844. if (!uniform)
  8845. return;
  8846. this._gl.uniform1fv(uniform, array);
  8847. };
  8848. Engine.prototype.setArray2 = function (uniform, array) {
  8849. if (!uniform || array.length % 2 !== 0)
  8850. return;
  8851. this._gl.uniform2fv(uniform, array);
  8852. };
  8853. Engine.prototype.setArray3 = function (uniform, array) {
  8854. if (!uniform || array.length % 3 !== 0)
  8855. return;
  8856. this._gl.uniform3fv(uniform, array);
  8857. };
  8858. Engine.prototype.setArray4 = function (uniform, array) {
  8859. if (!uniform || array.length % 4 !== 0)
  8860. return;
  8861. this._gl.uniform4fv(uniform, array);
  8862. };
  8863. Engine.prototype.setMatrices = function (uniform, matrices) {
  8864. if (!uniform)
  8865. return;
  8866. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8867. };
  8868. Engine.prototype.setMatrix = function (uniform, matrix) {
  8869. if (!uniform)
  8870. return;
  8871. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8872. };
  8873. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8874. if (!uniform)
  8875. return;
  8876. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8877. };
  8878. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8879. if (!uniform)
  8880. return;
  8881. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8882. };
  8883. Engine.prototype.setFloat = function (uniform, value) {
  8884. if (!uniform)
  8885. return;
  8886. this._gl.uniform1f(uniform, value);
  8887. };
  8888. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8889. if (!uniform)
  8890. return;
  8891. this._gl.uniform2f(uniform, x, y);
  8892. };
  8893. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8894. if (!uniform)
  8895. return;
  8896. this._gl.uniform3f(uniform, x, y, z);
  8897. };
  8898. Engine.prototype.setBool = function (uniform, bool) {
  8899. if (!uniform)
  8900. return;
  8901. this._gl.uniform1i(uniform, bool);
  8902. };
  8903. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8904. if (!uniform)
  8905. return;
  8906. this._gl.uniform4f(uniform, x, y, z, w);
  8907. };
  8908. Engine.prototype.setColor3 = function (uniform, color3) {
  8909. if (!uniform)
  8910. return;
  8911. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8912. };
  8913. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8914. if (!uniform)
  8915. return;
  8916. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8917. };
  8918. // States
  8919. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8920. if (zOffset === void 0) { zOffset = 0; }
  8921. if (reverseSide === void 0) { reverseSide = false; }
  8922. // Culling
  8923. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8924. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8925. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8926. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8927. if (culling) {
  8928. this._depthCullingState.cullFace = cullFace;
  8929. this._depthCullingState.cull = true;
  8930. }
  8931. else {
  8932. this._depthCullingState.cull = false;
  8933. }
  8934. }
  8935. // Z offset
  8936. this.setZOffset(zOffset);
  8937. };
  8938. Engine.prototype.setZOffset = function (value) {
  8939. this._depthCullingState.zOffset = value;
  8940. };
  8941. Engine.prototype.getZOffset = function () {
  8942. return this._depthCullingState.zOffset;
  8943. };
  8944. Engine.prototype.setDepthBuffer = function (enable) {
  8945. this._depthCullingState.depthTest = enable;
  8946. };
  8947. Engine.prototype.getDepthWrite = function () {
  8948. return this._depthCullingState.depthMask;
  8949. };
  8950. Engine.prototype.setDepthWrite = function (enable) {
  8951. this._depthCullingState.depthMask = enable;
  8952. };
  8953. Engine.prototype.setColorWrite = function (enable) {
  8954. this._gl.colorMask(enable, enable, enable, enable);
  8955. };
  8956. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8957. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8958. };
  8959. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8960. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8961. if (this._alphaMode === mode) {
  8962. return;
  8963. }
  8964. switch (mode) {
  8965. case Engine.ALPHA_DISABLE:
  8966. this._alphaState.alphaBlend = false;
  8967. break;
  8968. case Engine.ALPHA_PREMULTIPLIED:
  8969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8970. this._alphaState.alphaBlend = true;
  8971. break;
  8972. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_COMBINE:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_ONEONE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_ADD:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. case Engine.ALPHA_SUBTRACT:
  8989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8990. this._alphaState.alphaBlend = true;
  8991. break;
  8992. case Engine.ALPHA_MULTIPLY:
  8993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8994. this._alphaState.alphaBlend = true;
  8995. break;
  8996. case Engine.ALPHA_MAXIMIZED:
  8997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8998. this._alphaState.alphaBlend = true;
  8999. break;
  9000. case Engine.ALPHA_INTERPOLATE:
  9001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9002. this._alphaState.alphaBlend = true;
  9003. break;
  9004. case Engine.ALPHA_SCREENMODE:
  9005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9006. this._alphaState.alphaBlend = true;
  9007. break;
  9008. }
  9009. if (!noDepthWriteChange) {
  9010. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9011. }
  9012. this._alphaMode = mode;
  9013. };
  9014. Engine.prototype.getAlphaMode = function () {
  9015. return this._alphaMode;
  9016. };
  9017. Engine.prototype.setAlphaTesting = function (enable) {
  9018. this._alphaTest = enable;
  9019. };
  9020. Engine.prototype.getAlphaTesting = function () {
  9021. return !!this._alphaTest;
  9022. };
  9023. // Textures
  9024. Engine.prototype.wipeCaches = function (bruteForce) {
  9025. if (this.preventCacheWipeBetweenFrames) {
  9026. return;
  9027. }
  9028. this.resetTextureCache();
  9029. this._currentEffect = null;
  9030. // 6/8/2017: deltakosh: Should not be required anymore.
  9031. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9032. if (bruteForce) {
  9033. this._stencilState.reset();
  9034. this._depthCullingState.reset();
  9035. this.setDepthFunctionToLessOrEqual();
  9036. this._alphaState.reset();
  9037. }
  9038. this._cachedVertexBuffers = null;
  9039. this._cachedIndexBuffer = null;
  9040. this._cachedEffectForVertexBuffers = null;
  9041. this._unBindVertexArrayObject();
  9042. this.bindIndexBuffer(null);
  9043. this.bindArrayBuffer(null);
  9044. };
  9045. /**
  9046. * Set the compressed texture format to use, based on the formats you have, and the formats
  9047. * supported by the hardware / browser.
  9048. *
  9049. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9050. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9051. * to API arguments needed to compressed textures. This puts the burden on the container
  9052. * generator to house the arcane code for determining these for current & future formats.
  9053. *
  9054. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9055. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9056. *
  9057. * Note: The result of this call is not taken into account when a texture is base64.
  9058. *
  9059. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9060. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9061. *
  9062. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9063. * @returns The extension selected.
  9064. */
  9065. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9066. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9067. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9068. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9069. return this._textureFormatInUse = this._texturesSupported[i];
  9070. }
  9071. }
  9072. }
  9073. // actively set format to nothing, to allow this to be called more than once
  9074. // and possibly fail the 2nd time
  9075. return this._textureFormatInUse = null;
  9076. };
  9077. /**
  9078. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9079. * @param {string} urlArg- This contains one of the following:
  9080. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9081. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9082. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9083. *
  9084. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9085. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9086. * @param {Scene} scene- Needed for loading to the correct scene.
  9087. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9088. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9089. * @param {callback} onError- Optional callback to be called upon failure.
  9090. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9091. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9092. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9093. *
  9094. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9095. */
  9096. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9097. var _this = this;
  9098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9099. if (onLoad === void 0) { onLoad = null; }
  9100. if (onError === void 0) { onError = null; }
  9101. if (buffer === void 0) { buffer = null; }
  9102. var texture = fallBack ? fallBack : this._gl.createTexture();
  9103. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9104. var fromData = url.substr(0, 5) === "data:";
  9105. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9106. // establish the file extension, if possible
  9107. var lastDot = url.lastIndexOf('.');
  9108. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9109. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9110. if (isDDS) {
  9111. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9112. }
  9113. var isTGA = (extension === ".tga");
  9114. // determine if a ktx file should be substituted
  9115. var isKTX = false;
  9116. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9117. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9118. isKTX = true;
  9119. }
  9120. scene._addPendingData(texture);
  9121. texture.url = url;
  9122. texture.noMipmap = noMipmap;
  9123. texture.references = 1;
  9124. texture.samplingMode = samplingMode;
  9125. texture.onLoadedCallbacks = [];
  9126. if (onLoad) {
  9127. texture.onLoadedCallbacks.push(onLoad);
  9128. }
  9129. if (!fallBack)
  9130. this._loadedTexturesCache.push(texture);
  9131. var onerror = function () {
  9132. scene._removePendingData(texture);
  9133. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9134. if (isKTX) {
  9135. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9136. }
  9137. else if (onError) {
  9138. onError();
  9139. }
  9140. };
  9141. var callback;
  9142. // processing for non-image formats
  9143. if (isKTX || isTGA || isDDS) {
  9144. if (isKTX) {
  9145. callback = function (data) {
  9146. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9147. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9148. ktx.uploadLevels(_this._gl, !noMipmap);
  9149. }, samplingMode);
  9150. };
  9151. }
  9152. else if (isTGA) {
  9153. callback = function (arrayBuffer) {
  9154. var data = new Uint8Array(arrayBuffer);
  9155. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9156. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9157. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9158. }, samplingMode);
  9159. };
  9160. }
  9161. else if (isDDS) {
  9162. callback = function (data) {
  9163. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9164. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9165. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9166. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9167. }, samplingMode);
  9168. };
  9169. }
  9170. if (!buffer) {
  9171. BABYLON.Tools.LoadFile(url, function (data) {
  9172. callback(data);
  9173. }, null, scene.database, true, onerror);
  9174. }
  9175. else {
  9176. callback(buffer);
  9177. }
  9178. // image format processing
  9179. }
  9180. else {
  9181. var onload = function (img) {
  9182. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9183. var isPot = (img.width === potWidth && img.height === potHeight);
  9184. if (!isPot) {
  9185. _this._prepareWorkingCanvas();
  9186. _this._workingCanvas.width = potWidth;
  9187. _this._workingCanvas.height = potHeight;
  9188. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9189. _this._workingContext.imageSmoothingEnabled = false;
  9190. _this._workingContext.mozImageSmoothingEnabled = false;
  9191. _this._workingContext.oImageSmoothingEnabled = false;
  9192. _this._workingContext.webkitImageSmoothingEnabled = false;
  9193. _this._workingContext.msImageSmoothingEnabled = false;
  9194. }
  9195. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9196. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9197. _this._workingContext.imageSmoothingEnabled = true;
  9198. _this._workingContext.mozImageSmoothingEnabled = true;
  9199. _this._workingContext.oImageSmoothingEnabled = true;
  9200. _this._workingContext.webkitImageSmoothingEnabled = true;
  9201. _this._workingContext.msImageSmoothingEnabled = true;
  9202. }
  9203. }
  9204. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9205. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9206. }, samplingMode);
  9207. };
  9208. if (!fromData || isBase64)
  9209. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9210. else if (buffer instanceof Array || typeof buffer === "string")
  9211. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9212. else
  9213. onload(buffer);
  9214. }
  9215. return texture;
  9216. };
  9217. Engine.prototype._getInternalFormat = function (format) {
  9218. var internalFormat = this._gl.RGBA;
  9219. switch (format) {
  9220. case Engine.TEXTUREFORMAT_ALPHA:
  9221. internalFormat = this._gl.ALPHA;
  9222. break;
  9223. case Engine.TEXTUREFORMAT_LUMINANCE:
  9224. internalFormat = this._gl.LUMINANCE;
  9225. break;
  9226. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9227. internalFormat = this._gl.LUMINANCE_ALPHA;
  9228. break;
  9229. case Engine.TEXTUREFORMAT_RGB:
  9230. internalFormat = this._gl.RGB;
  9231. break;
  9232. case Engine.TEXTUREFORMAT_RGBA:
  9233. internalFormat = this._gl.RGBA;
  9234. break;
  9235. }
  9236. return internalFormat;
  9237. };
  9238. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9239. if (compression === void 0) { compression = null; }
  9240. var internalFormat = this._getInternalFormat(format);
  9241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9243. if (texture._width % 4 !== 0) {
  9244. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9245. }
  9246. if (compression) {
  9247. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9248. }
  9249. else {
  9250. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9251. }
  9252. if (texture.generateMipMaps) {
  9253. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9254. }
  9255. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9256. this.resetTextureCache();
  9257. texture.isReady = true;
  9258. };
  9259. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9260. if (compression === void 0) { compression = null; }
  9261. var texture = this._gl.createTexture();
  9262. texture._baseWidth = width;
  9263. texture._baseHeight = height;
  9264. texture._width = width;
  9265. texture._height = height;
  9266. texture.references = 1;
  9267. this.updateRawTexture(texture, data, format, invertY, compression);
  9268. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9269. // Filters
  9270. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9273. if (generateMipMaps) {
  9274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9275. }
  9276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9277. texture.samplingMode = samplingMode;
  9278. this._loadedTexturesCache.push(texture);
  9279. return texture;
  9280. };
  9281. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9282. var texture = this._gl.createTexture();
  9283. texture._baseWidth = width;
  9284. texture._baseHeight = height;
  9285. if (generateMipMaps) {
  9286. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9287. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9288. }
  9289. this.resetTextureCache();
  9290. texture._width = width;
  9291. texture._height = height;
  9292. texture.isReady = false;
  9293. texture.generateMipMaps = generateMipMaps;
  9294. texture.references = 1;
  9295. texture.samplingMode = samplingMode;
  9296. this.updateTextureSamplingMode(samplingMode, texture);
  9297. this._loadedTexturesCache.push(texture);
  9298. return texture;
  9299. };
  9300. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9301. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9302. if (texture.isCube) {
  9303. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9305. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9307. }
  9308. else {
  9309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9313. }
  9314. texture.samplingMode = samplingMode;
  9315. };
  9316. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9317. if (premulAlpha === void 0) { premulAlpha = false; }
  9318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9319. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9320. if (premulAlpha) {
  9321. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9322. }
  9323. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9325. if (texture.generateMipMaps) {
  9326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9327. }
  9328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9329. if (premulAlpha) {
  9330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9331. }
  9332. this.resetTextureCache();
  9333. texture.isReady = true;
  9334. };
  9335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9336. if (texture._isDisabled) {
  9337. return;
  9338. }
  9339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9341. try {
  9342. // Testing video texture support
  9343. if (this._videoTextureSupported === undefined) {
  9344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9345. if (this._gl.getError() !== 0) {
  9346. this._videoTextureSupported = false;
  9347. }
  9348. else {
  9349. this._videoTextureSupported = true;
  9350. }
  9351. }
  9352. // Copy video through the current working canvas if video texture is not supported
  9353. if (!this._videoTextureSupported) {
  9354. if (!texture._workingCanvas) {
  9355. texture._workingCanvas = document.createElement("canvas");
  9356. texture._workingContext = texture._workingCanvas.getContext("2d");
  9357. texture._workingCanvas.width = texture._width;
  9358. texture._workingCanvas.height = texture._height;
  9359. }
  9360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9362. }
  9363. else {
  9364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9365. }
  9366. if (texture.generateMipMaps) {
  9367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9368. }
  9369. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9370. this.resetTextureCache();
  9371. texture.isReady = true;
  9372. }
  9373. catch (ex) {
  9374. // Something unexpected
  9375. // Let's disable the texture
  9376. texture._isDisabled = true;
  9377. }
  9378. };
  9379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9380. // old version had a "generateMipMaps" arg instead of options.
  9381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9382. // in the same way, generateDepthBuffer is defaulted to true
  9383. var generateMipMaps = false;
  9384. var generateDepthBuffer = true;
  9385. var generateStencilBuffer = false;
  9386. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9387. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9388. if (options !== undefined) {
  9389. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9390. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9391. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9392. type = options.type === undefined ? type : options.type;
  9393. if (options.samplingMode !== undefined) {
  9394. samplingMode = options.samplingMode;
  9395. }
  9396. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9397. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9398. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9399. }
  9400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9401. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9403. }
  9404. }
  9405. var gl = this._gl;
  9406. var texture = gl.createTexture();
  9407. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9408. var width = size.width || size;
  9409. var height = size.height || size;
  9410. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9411. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9412. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9413. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9414. }
  9415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9419. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9420. // Create the framebuffer
  9421. var framebuffer = gl.createFramebuffer();
  9422. this.bindUnboundFramebuffer(framebuffer);
  9423. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9424. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9425. if (generateMipMaps) {
  9426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9427. }
  9428. // Unbind
  9429. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9431. this.bindUnboundFramebuffer(null);
  9432. texture._framebuffer = framebuffer;
  9433. texture._baseWidth = width;
  9434. texture._baseHeight = height;
  9435. texture._width = width;
  9436. texture._height = height;
  9437. texture.isReady = true;
  9438. texture.samples = 1;
  9439. texture.generateMipMaps = generateMipMaps;
  9440. texture.references = 1;
  9441. texture.samplingMode = samplingMode;
  9442. texture.type = type;
  9443. texture._generateDepthBuffer = generateDepthBuffer;
  9444. texture._generateStencilBuffer = generateStencilBuffer;
  9445. this.resetTextureCache();
  9446. this._loadedTexturesCache.push(texture);
  9447. return texture;
  9448. };
  9449. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9450. var generateMipMaps = false;
  9451. var generateDepthBuffer = true;
  9452. var generateStencilBuffer = false;
  9453. var generateDepthTexture = false;
  9454. var textureCount = 1;
  9455. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9456. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9457. var types = [], samplingModes = [];
  9458. if (options !== undefined) {
  9459. generateMipMaps = options.generateMipMaps;
  9460. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9461. generateStencilBuffer = options.generateStencilBuffer;
  9462. generateDepthTexture = options.generateDepthTexture;
  9463. textureCount = options.textureCount || 1;
  9464. if (options.types) {
  9465. types = options.types;
  9466. }
  9467. if (options.samplingModes) {
  9468. samplingModes = options.samplingModes;
  9469. }
  9470. }
  9471. var gl = this._gl;
  9472. // Create the framebuffer
  9473. var framebuffer = gl.createFramebuffer();
  9474. this.bindUnboundFramebuffer(framebuffer);
  9475. var width = size.width || size;
  9476. var height = size.height || size;
  9477. var textures = [];
  9478. var attachments = [];
  9479. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9480. for (var i = 0; i < textureCount; i++) {
  9481. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9482. var type = types[i] || defaultType;
  9483. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9484. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9485. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9486. }
  9487. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9488. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9490. }
  9491. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9492. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9493. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9494. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9495. }
  9496. var texture = gl.createTexture();
  9497. var attachment = gl["COLOR_ATTACHMENT" + i];
  9498. textures.push(texture);
  9499. attachments.push(attachment);
  9500. gl.activeTexture(gl["TEXTURE" + i]);
  9501. gl.bindTexture(gl.TEXTURE_2D, texture);
  9502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9506. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9507. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9508. if (generateMipMaps) {
  9509. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9510. }
  9511. // Unbind
  9512. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9513. texture._framebuffer = framebuffer;
  9514. texture._depthStencilBuffer = depthStencilBuffer;
  9515. texture._baseWidth = width;
  9516. texture._baseHeight = height;
  9517. texture._width = width;
  9518. texture._height = height;
  9519. texture.isReady = true;
  9520. texture.samples = 1;
  9521. texture.generateMipMaps = generateMipMaps;
  9522. texture.references = 1;
  9523. texture.samplingMode = samplingMode;
  9524. texture.type = type;
  9525. texture._generateDepthBuffer = generateDepthBuffer;
  9526. texture._generateStencilBuffer = generateStencilBuffer;
  9527. this._loadedTexturesCache.push(texture);
  9528. }
  9529. if (generateDepthTexture) {
  9530. // Depth texture
  9531. var depthTexture = gl.createTexture();
  9532. gl.activeTexture(gl.TEXTURE0);
  9533. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9535. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9536. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9537. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9538. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9539. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9540. depthTexture._framebuffer = framebuffer;
  9541. depthTexture._baseWidth = width;
  9542. depthTexture._baseHeight = height;
  9543. depthTexture._width = width;
  9544. depthTexture._height = height;
  9545. depthTexture.isReady = true;
  9546. depthTexture.samples = 1;
  9547. depthTexture.generateMipMaps = generateMipMaps;
  9548. depthTexture.references = 1;
  9549. depthTexture.samplingMode = gl.NEAREST;
  9550. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9551. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9552. textures.push(depthTexture);
  9553. this._loadedTexturesCache.push(depthTexture);
  9554. }
  9555. gl.drawBuffers(attachments);
  9556. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9557. this.bindUnboundFramebuffer(null);
  9558. this.resetTextureCache();
  9559. return textures;
  9560. };
  9561. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9562. if (samples === void 0) { samples = 1; }
  9563. var depthStencilBuffer = null;
  9564. var gl = this._gl;
  9565. // Create the depth/stencil buffer
  9566. if (generateStencilBuffer) {
  9567. depthStencilBuffer = gl.createRenderbuffer();
  9568. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9569. if (samples > 1) {
  9570. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9571. }
  9572. else {
  9573. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9574. }
  9575. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9576. }
  9577. else if (generateDepthBuffer) {
  9578. depthStencilBuffer = gl.createRenderbuffer();
  9579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9580. if (samples > 1) {
  9581. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9582. }
  9583. else {
  9584. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9585. }
  9586. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9587. }
  9588. return depthStencilBuffer;
  9589. };
  9590. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9591. if (this.webGLVersion < 2) {
  9592. return 1;
  9593. }
  9594. if (texture.samples === samples) {
  9595. return samples;
  9596. }
  9597. var gl = this._gl;
  9598. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9599. // Dispose previous render buffers
  9600. if (texture._depthStencilBuffer) {
  9601. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9602. }
  9603. if (texture._MSAAFramebuffer) {
  9604. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9605. }
  9606. if (texture._MSAARenderBuffer) {
  9607. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9608. }
  9609. if (samples > 1) {
  9610. texture._MSAAFramebuffer = gl.createFramebuffer();
  9611. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9612. var colorRenderbuffer = gl.createRenderbuffer();
  9613. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9614. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9615. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9616. texture._MSAARenderBuffer = colorRenderbuffer;
  9617. }
  9618. else {
  9619. this.bindUnboundFramebuffer(texture._framebuffer);
  9620. }
  9621. texture.samples = samples;
  9622. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9623. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9624. this.bindUnboundFramebuffer(null);
  9625. return samples;
  9626. };
  9627. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9628. var gl = this._gl;
  9629. var texture = gl.createTexture();
  9630. var generateMipMaps = true;
  9631. var generateDepthBuffer = true;
  9632. var generateStencilBuffer = false;
  9633. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9634. if (options !== undefined) {
  9635. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9636. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9637. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9638. if (options.samplingMode !== undefined) {
  9639. samplingMode = options.samplingMode;
  9640. }
  9641. }
  9642. texture.isCube = true;
  9643. texture.references = 1;
  9644. texture.generateMipMaps = generateMipMaps;
  9645. texture.references = 1;
  9646. texture.samples = 1;
  9647. texture.samplingMode = samplingMode;
  9648. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9650. for (var face = 0; face < 6; face++) {
  9651. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9652. }
  9653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9657. // Create the framebuffer
  9658. var framebuffer = gl.createFramebuffer();
  9659. this.bindUnboundFramebuffer(framebuffer);
  9660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9661. // Mipmaps
  9662. if (texture.generateMipMaps) {
  9663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9664. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9665. }
  9666. // Unbind
  9667. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9668. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9669. this.bindUnboundFramebuffer(null);
  9670. texture._framebuffer = framebuffer;
  9671. texture._width = size;
  9672. texture._height = size;
  9673. texture.isReady = true;
  9674. this.resetTextureCache();
  9675. this._loadedTexturesCache.push(texture);
  9676. return texture;
  9677. };
  9678. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9679. var _this = this;
  9680. if (onLoad === void 0) { onLoad = null; }
  9681. if (onError === void 0) { onError = null; }
  9682. var gl = this._gl;
  9683. var texture = gl.createTexture();
  9684. texture.isCube = true;
  9685. texture.url = rootUrl;
  9686. texture.references = 1;
  9687. texture.onLoadedCallbacks = [];
  9688. var isKTX = false;
  9689. var lastDot = rootUrl.lastIndexOf('.');
  9690. var extension = rootUrl.substring(lastDot).toLowerCase();
  9691. if (this._textureFormatInUse) {
  9692. extension = this._textureFormatInUse;
  9693. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9694. isKTX = true;
  9695. }
  9696. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9697. if (isDDS) {
  9698. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9699. }
  9700. if (isKTX) {
  9701. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9702. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9703. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9705. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9706. ktx.uploadLevels(_this._gl, !noMipmap);
  9707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9711. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9712. _this.resetTextureCache();
  9713. texture._width = ktx.pixelWidth;
  9714. texture._height = ktx.pixelHeight;
  9715. texture.isReady = true;
  9716. }, null, null, true, onError);
  9717. }
  9718. else if (isDDS) {
  9719. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9720. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9721. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9723. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9724. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9725. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9726. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9727. }
  9728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9733. _this.resetTextureCache();
  9734. texture._width = info.width;
  9735. texture._height = info.height;
  9736. texture.isReady = true;
  9737. }, null, null, true, onError);
  9738. }
  9739. else {
  9740. cascadeLoad(rootUrl, scene, function (imgs) {
  9741. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9742. var height = width;
  9743. _this._prepareWorkingCanvas();
  9744. _this._workingCanvas.width = width;
  9745. _this._workingCanvas.height = height;
  9746. var faces = [
  9747. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9748. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9749. ];
  9750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9751. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9752. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9753. for (var index = 0; index < faces.length; index++) {
  9754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9755. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9756. }
  9757. if (!noMipmap) {
  9758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9759. }
  9760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9765. _this.resetTextureCache();
  9766. texture._width = width;
  9767. texture._height = height;
  9768. texture.isReady = true;
  9769. texture.onLoadedCallbacks.forEach(function (callback) {
  9770. callback();
  9771. });
  9772. if (onLoad) {
  9773. onLoad();
  9774. }
  9775. }, files, onError);
  9776. }
  9777. this._loadedTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9781. texture._width = width;
  9782. texture._height = height;
  9783. texture._size = width * height;
  9784. texture._baseWidth = width;
  9785. texture._baseHeight = height;
  9786. };
  9787. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9788. if (compression === void 0) { compression = null; }
  9789. if (level === void 0) { level = 0; }
  9790. var gl = this._gl;
  9791. var textureType = this._getWebGLTextureType(type);
  9792. var internalFormat = this._getInternalFormat(format);
  9793. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9794. var needConversion = false;
  9795. if (internalFormat === gl.RGB) {
  9796. internalFormat = gl.RGBA;
  9797. needConversion = true;
  9798. }
  9799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9800. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9801. if (texture._width % 4 !== 0) {
  9802. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9803. }
  9804. var facesIndex = [
  9805. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9806. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9807. ];
  9808. // Data are known to be in +X +Y +Z -X -Y -Z
  9809. for (var index = 0; index < facesIndex.length; index++) {
  9810. var faceData = data[index];
  9811. if (compression) {
  9812. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9813. }
  9814. else {
  9815. if (needConversion) {
  9816. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9817. }
  9818. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9819. }
  9820. }
  9821. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9822. if (isPot && texture.generateMipMaps && level === 0) {
  9823. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9824. }
  9825. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9826. this.resetTextureCache();
  9827. texture.isReady = true;
  9828. };
  9829. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9830. if (compression === void 0) { compression = null; }
  9831. var gl = this._gl;
  9832. var texture = gl.createTexture();
  9833. texture.isCube = true;
  9834. texture.references = 1;
  9835. var textureType = this._getWebGLTextureType(type);
  9836. var internalFormat = this._getInternalFormat(format);
  9837. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9838. var needConversion = false;
  9839. if (internalFormat === gl.RGB) {
  9840. internalFormat = gl.RGBA;
  9841. needConversion = true;
  9842. }
  9843. var width = size;
  9844. var height = width;
  9845. texture._width = width;
  9846. texture._height = height;
  9847. // Double check on POT to generate Mips.
  9848. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9849. if (!isPot) {
  9850. generateMipMaps = false;
  9851. }
  9852. texture.generateMipMaps = generateMipMaps;
  9853. // Upload data if needed. The texture won t be ready until then.
  9854. if (data) {
  9855. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9856. }
  9857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9858. // Filters
  9859. if (data && generateMipMaps) {
  9860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9861. }
  9862. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9865. }
  9866. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9869. }
  9870. else {
  9871. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9874. }
  9875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9878. this._loadedTexturesCache.push(texture);
  9879. return texture;
  9880. };
  9881. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9882. var _this = this;
  9883. if (onLoad === void 0) { onLoad = null; }
  9884. if (onError === void 0) { onError = null; }
  9885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9886. if (invertY === void 0) { invertY = false; }
  9887. var gl = this._gl;
  9888. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9889. scene._addPendingData(texture);
  9890. texture.url = url;
  9891. var onerror = function () {
  9892. scene._removePendingData(texture);
  9893. if (onError) {
  9894. onError();
  9895. }
  9896. };
  9897. var internalCallback = function (data) {
  9898. var rgbeDataArrays = callback(data);
  9899. var facesIndex = [
  9900. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9901. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9902. ];
  9903. var width = texture._width;
  9904. var height = texture._height;
  9905. if (mipmmapGenerator) {
  9906. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9907. // I ll remove ASAP.
  9908. var textureType = _this._getWebGLTextureType(type);
  9909. var internalFormat = _this._getInternalFormat(format);
  9910. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9911. var needConversion = false;
  9912. if (internalFormat === gl.RGB) {
  9913. internalFormat = gl.RGBA;
  9914. needConversion = true;
  9915. }
  9916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9918. var arrayTemp = [];
  9919. // Data are known to be in +X +Y +Z -X -Y -Z
  9920. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9921. arrayTemp.push(rgbeDataArrays[0]); // +X
  9922. arrayTemp.push(rgbeDataArrays[3]); // -X
  9923. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9924. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9925. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9926. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9927. var mipData = mipmmapGenerator(arrayTemp);
  9928. // mipData is order in +X -X +Y -Y +Z -Z
  9929. var mipFaces = [0, 2, 4, 1, 3, 5];
  9930. for (var level = 0; level < mipData.length; level++) {
  9931. var mipSize = width >> level;
  9932. for (var mipIndex in mipFaces) {
  9933. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9934. if (needConversion) {
  9935. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9936. }
  9937. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9938. }
  9939. }
  9940. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9941. }
  9942. else {
  9943. texture.generateMipMaps = !noMipmap;
  9944. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9945. }
  9946. texture.isReady = true;
  9947. _this.resetTextureCache();
  9948. scene._removePendingData(texture);
  9949. if (onLoad) {
  9950. onLoad();
  9951. }
  9952. };
  9953. BABYLON.Tools.LoadFile(url, function (data) {
  9954. internalCallback(data);
  9955. }, onerror, scene.database, true);
  9956. return texture;
  9957. };
  9958. ;
  9959. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9960. // Create new RGBA data container.
  9961. var rgbaData;
  9962. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9963. rgbaData = new Float32Array(width * height * 4);
  9964. }
  9965. else {
  9966. rgbaData = new Uint32Array(width * height * 4);
  9967. }
  9968. // Convert each pixel.
  9969. for (var x = 0; x < width; x++) {
  9970. for (var y = 0; y < height; y++) {
  9971. var index = (y * width + x) * 3;
  9972. var newIndex = (y * width + x) * 4;
  9973. // Map Old Value to new value.
  9974. rgbaData[newIndex + 0] = rgbData[index + 0];
  9975. rgbaData[newIndex + 1] = rgbData[index + 1];
  9976. rgbaData[newIndex + 2] = rgbData[index + 2];
  9977. // Add fully opaque alpha channel.
  9978. rgbaData[newIndex + 3] = 1;
  9979. }
  9980. }
  9981. return rgbaData;
  9982. };
  9983. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9984. var gl = this._gl;
  9985. if (texture._framebuffer) {
  9986. gl.deleteFramebuffer(texture._framebuffer);
  9987. texture._framebuffer = null;
  9988. }
  9989. if (texture._depthStencilBuffer) {
  9990. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9991. texture._depthStencilBuffer = null;
  9992. }
  9993. if (texture._MSAAFramebuffer) {
  9994. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9995. texture._MSAAFramebuffer = null;
  9996. }
  9997. if (texture._MSAARenderBuffer) {
  9998. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9999. texture._MSAARenderBuffer = null;
  10000. }
  10001. };
  10002. Engine.prototype._releaseTexture = function (texture) {
  10003. var gl = this._gl;
  10004. this._releaseFramebufferObjects(texture);
  10005. gl.deleteTexture(texture);
  10006. // Unbind channels
  10007. this.unbindAllTextures();
  10008. var index = this._loadedTexturesCache.indexOf(texture);
  10009. if (index !== -1) {
  10010. this._loadedTexturesCache.splice(index, 1);
  10011. }
  10012. };
  10013. Engine.prototype.setProgram = function (program) {
  10014. if (this._currentProgram !== program) {
  10015. this._gl.useProgram(program);
  10016. this._currentProgram = program;
  10017. }
  10018. };
  10019. Engine.prototype.bindSamplers = function (effect) {
  10020. this.setProgram(effect.getProgram());
  10021. var samplers = effect.getSamplers();
  10022. for (var index = 0; index < samplers.length; index++) {
  10023. var uniform = effect.getUniform(samplers[index]);
  10024. this._gl.uniform1i(uniform, index);
  10025. }
  10026. this._currentEffect = null;
  10027. };
  10028. Engine.prototype.activateTexture = function (texture) {
  10029. if (this._activeTexture !== texture) {
  10030. this._gl.activeTexture(texture);
  10031. this._activeTexture = texture;
  10032. }
  10033. };
  10034. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10035. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10036. this._gl.bindTexture(target, texture);
  10037. this._activeTexturesCache[this._activeTexture] = texture;
  10038. }
  10039. };
  10040. Engine.prototype._bindTexture = function (channel, texture) {
  10041. if (channel < 0) {
  10042. return;
  10043. }
  10044. this.activateTexture(this._gl.TEXTURE0 + channel);
  10045. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10046. };
  10047. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10048. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10049. };
  10050. Engine.prototype.unbindAllTextures = function () {
  10051. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10052. this.activateTexture(this._gl["TEXTURE" + channel]);
  10053. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10054. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10055. }
  10056. };
  10057. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10058. if (channel < 0) {
  10059. return;
  10060. }
  10061. this._gl.uniform1i(uniform, channel);
  10062. this._setTexture(channel, texture);
  10063. };
  10064. Engine.prototype._setTexture = function (channel, texture) {
  10065. // Not ready?
  10066. if (!texture) {
  10067. if (this._activeTexturesCache[channel] != null) {
  10068. this.activateTexture(this._gl["TEXTURE" + channel]);
  10069. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10071. }
  10072. return;
  10073. }
  10074. // Video
  10075. var alreadyActivated = false;
  10076. if (texture.video) {
  10077. this.activateTexture(this._gl["TEXTURE" + channel]);
  10078. alreadyActivated = true;
  10079. texture.update();
  10080. }
  10081. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10082. texture.delayLoad();
  10083. return;
  10084. }
  10085. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10086. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10087. if (this._activeTexturesCache[channel] === internalTexture) {
  10088. return;
  10089. }
  10090. if (!alreadyActivated) {
  10091. this.activateTexture(this._gl["TEXTURE" + channel]);
  10092. }
  10093. if (internalTexture.isCube) {
  10094. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10095. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10096. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10097. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10098. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10099. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10100. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10101. }
  10102. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10103. }
  10104. else {
  10105. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10106. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10107. internalTexture._cachedWrapU = texture.wrapU;
  10108. switch (texture.wrapU) {
  10109. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10110. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10111. break;
  10112. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10113. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10114. break;
  10115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10116. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10117. break;
  10118. }
  10119. }
  10120. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10121. internalTexture._cachedWrapV = texture.wrapV;
  10122. switch (texture.wrapV) {
  10123. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10124. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10125. break;
  10126. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10128. break;
  10129. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10130. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10131. break;
  10132. }
  10133. }
  10134. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10135. }
  10136. };
  10137. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10138. if (channel < 0) {
  10139. return;
  10140. }
  10141. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10142. this._textureUnits = new Int32Array(textures.length);
  10143. }
  10144. for (var i = 0; i < textures.length; i++) {
  10145. this._textureUnits[i] = channel + i;
  10146. }
  10147. this._gl.uniform1iv(uniform, this._textureUnits);
  10148. for (var index = 0; index < textures.length; index++) {
  10149. this._setTexture(channel + index, textures[index]);
  10150. }
  10151. };
  10152. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10153. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10154. var value = texture.anisotropicFilteringLevel;
  10155. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10156. value = 1;
  10157. }
  10158. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10159. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10160. texture._cachedAnisotropicFilteringLevel = value;
  10161. }
  10162. };
  10163. Engine.prototype.readPixels = function (x, y, width, height) {
  10164. var data = new Uint8Array(height * width * 4);
  10165. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10166. return data;
  10167. };
  10168. /**
  10169. * Add an externaly attached data from its key.
  10170. * This method call will fail and return false, if such key already exists.
  10171. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10172. * @param key the unique key that identifies the data
  10173. * @param data the data object to associate to the key for this Engine instance
  10174. * @return true if no such key were already present and the data was added successfully, false otherwise
  10175. */
  10176. Engine.prototype.addExternalData = function (key, data) {
  10177. if (!this._externalData) {
  10178. this._externalData = new BABYLON.StringDictionary();
  10179. }
  10180. return this._externalData.add(key, data);
  10181. };
  10182. /**
  10183. * Get an externaly attached data from its key
  10184. * @param key the unique key that identifies the data
  10185. * @return the associated data, if present (can be null), or undefined if not present
  10186. */
  10187. Engine.prototype.getExternalData = function (key) {
  10188. if (!this._externalData) {
  10189. this._externalData = new BABYLON.StringDictionary();
  10190. }
  10191. return this._externalData.get(key);
  10192. };
  10193. /**
  10194. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10195. * @param key the unique key that identifies the data
  10196. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10197. * @return the associated data, can be null if the factory returned null.
  10198. */
  10199. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10200. if (!this._externalData) {
  10201. this._externalData = new BABYLON.StringDictionary();
  10202. }
  10203. return this._externalData.getOrAddWithFactory(key, factory);
  10204. };
  10205. /**
  10206. * Remove an externaly attached data from the Engine instance
  10207. * @param key the unique key that identifies the data
  10208. * @return true if the data was successfully removed, false if it doesn't exist
  10209. */
  10210. Engine.prototype.removeExternalData = function (key) {
  10211. if (!this._externalData) {
  10212. this._externalData = new BABYLON.StringDictionary();
  10213. }
  10214. return this._externalData.remove(key);
  10215. };
  10216. Engine.prototype.releaseInternalTexture = function (texture) {
  10217. if (!texture) {
  10218. return;
  10219. }
  10220. texture.references--;
  10221. // Final reference ?
  10222. if (texture.references === 0) {
  10223. var texturesCache = this.getLoadedTexturesCache();
  10224. var index = texturesCache.indexOf(texture);
  10225. if (index > -1) {
  10226. texturesCache.splice(index, 1);
  10227. }
  10228. this._releaseTexture(texture);
  10229. }
  10230. };
  10231. Engine.prototype.unbindAllAttributes = function () {
  10232. if (this._mustWipeVertexAttributes) {
  10233. this._mustWipeVertexAttributes = false;
  10234. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10235. this._gl.disableVertexAttribArray(i);
  10236. this._vertexAttribArraysEnabled[i] = false;
  10237. this._currentBufferPointers[i] = null;
  10238. }
  10239. return;
  10240. }
  10241. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10242. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10243. continue;
  10244. }
  10245. this._gl.disableVertexAttribArray(i);
  10246. this._vertexAttribArraysEnabled[i] = false;
  10247. this._currentBufferPointers[i] = null;
  10248. }
  10249. };
  10250. Engine.prototype.releaseEffects = function () {
  10251. for (var name in this._compiledEffects) {
  10252. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10253. }
  10254. this._compiledEffects = {};
  10255. };
  10256. // Dispose
  10257. Engine.prototype.dispose = function () {
  10258. this.hideLoadingUI();
  10259. this.stopRenderLoop();
  10260. // Empty texture
  10261. if (this._emptyTexture) {
  10262. this._releaseTexture(this._emptyTexture);
  10263. this._emptyTexture = null;
  10264. }
  10265. if (this._emptyCubeTexture) {
  10266. this._releaseTexture(this._emptyCubeTexture);
  10267. this._emptyCubeTexture = null;
  10268. }
  10269. // Release scenes
  10270. while (this.scenes.length) {
  10271. this.scenes[0].dispose();
  10272. }
  10273. // Release audio engine
  10274. if (Engine.audioEngine) {
  10275. Engine.audioEngine.dispose();
  10276. }
  10277. // Release effects
  10278. this.releaseEffects();
  10279. // Unbind
  10280. this.unbindAllAttributes();
  10281. if (this._dummyFramebuffer) {
  10282. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10283. }
  10284. this._gl = null;
  10285. //WebVR
  10286. this.disableVR();
  10287. // Events
  10288. window.removeEventListener("blur", this._onBlur);
  10289. window.removeEventListener("focus", this._onFocus);
  10290. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10291. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10292. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10293. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10294. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10295. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10296. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10297. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10298. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10299. // Remove from Instances
  10300. var index = Engine.Instances.indexOf(this);
  10301. if (index >= 0) {
  10302. Engine.Instances.splice(index, 1);
  10303. }
  10304. };
  10305. // Loading screen
  10306. Engine.prototype.displayLoadingUI = function () {
  10307. var loadingScreen = this.loadingScreen;
  10308. if (loadingScreen) {
  10309. loadingScreen.displayLoadingUI();
  10310. }
  10311. };
  10312. Engine.prototype.hideLoadingUI = function () {
  10313. var loadingScreen = this.loadingScreen;
  10314. if (loadingScreen) {
  10315. loadingScreen.hideLoadingUI();
  10316. }
  10317. };
  10318. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10319. get: function () {
  10320. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10321. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10322. return this._loadingScreen;
  10323. },
  10324. set: function (loadingScreen) {
  10325. this._loadingScreen = loadingScreen;
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10331. set: function (text) {
  10332. this.loadingScreen.loadingUIText = text;
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10338. set: function (color) {
  10339. this.loadingScreen.loadingUIBackgroundColor = color;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. Engine.prototype.attachContextLostEvent = function (callback) {
  10345. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10346. };
  10347. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10348. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10349. };
  10350. Engine.prototype.getVertexShaderSource = function (program) {
  10351. var shaders = this._gl.getAttachedShaders(program);
  10352. return this._gl.getShaderSource(shaders[0]);
  10353. };
  10354. Engine.prototype.getFragmentShaderSource = function (program) {
  10355. var shaders = this._gl.getAttachedShaders(program);
  10356. return this._gl.getShaderSource(shaders[1]);
  10357. };
  10358. Engine.prototype.getError = function () {
  10359. return this._gl.getError();
  10360. };
  10361. // FPS
  10362. Engine.prototype.getFps = function () {
  10363. return this.fps;
  10364. };
  10365. Engine.prototype.getDeltaTime = function () {
  10366. return this.deltaTime;
  10367. };
  10368. Engine.prototype._measureFps = function () {
  10369. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10370. var length = this.previousFramesDuration.length;
  10371. if (length >= 2) {
  10372. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10373. }
  10374. if (length >= this.fpsRange) {
  10375. if (length > this.fpsRange) {
  10376. this.previousFramesDuration.splice(0, 1);
  10377. length = this.previousFramesDuration.length;
  10378. }
  10379. var sum = 0;
  10380. for (var id = 0; id < length - 1; id++) {
  10381. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10382. }
  10383. this.fps = 1000.0 / (sum / (length - 1));
  10384. }
  10385. };
  10386. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10387. if (faceIndex === void 0) { faceIndex = -1; }
  10388. var gl = this._gl;
  10389. if (!this._dummyFramebuffer) {
  10390. this._dummyFramebuffer = gl.createFramebuffer();
  10391. }
  10392. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10393. if (faceIndex > -1) {
  10394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10395. }
  10396. else {
  10397. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10398. }
  10399. var readFormat = gl.RGBA;
  10400. var readType = gl.UNSIGNED_BYTE;
  10401. var buffer = new Uint8Array(4 * width * height);
  10402. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10403. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10404. return buffer;
  10405. };
  10406. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10407. if (this._webGLVersion > 1) {
  10408. return this._caps.colorBufferFloat;
  10409. }
  10410. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10411. };
  10412. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10413. if (this._webGLVersion > 1) {
  10414. return this._caps.colorBufferFloat;
  10415. }
  10416. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10417. };
  10418. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10419. Engine.prototype._canRenderToFramebuffer = function (type) {
  10420. var gl = this._gl;
  10421. //clear existing errors
  10422. while (gl.getError() !== gl.NO_ERROR) { }
  10423. var successful = true;
  10424. var texture = gl.createTexture();
  10425. gl.bindTexture(gl.TEXTURE_2D, texture);
  10426. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10429. var fb = gl.createFramebuffer();
  10430. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10431. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10432. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10433. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10434. successful = successful && (gl.getError() === gl.NO_ERROR);
  10435. //try render by clearing frame buffer's color buffer
  10436. if (successful) {
  10437. gl.clear(gl.COLOR_BUFFER_BIT);
  10438. successful = successful && (gl.getError() === gl.NO_ERROR);
  10439. }
  10440. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10441. if (successful) {
  10442. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10443. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10444. var readFormat = gl.RGBA;
  10445. var readType = gl.UNSIGNED_BYTE;
  10446. var buffer = new Uint8Array(4);
  10447. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10448. successful = successful && (gl.getError() === gl.NO_ERROR);
  10449. }
  10450. //clean up
  10451. gl.deleteTexture(texture);
  10452. gl.deleteFramebuffer(fb);
  10453. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10454. //clear accumulated errors
  10455. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10456. return successful;
  10457. };
  10458. Engine.prototype._getWebGLTextureType = function (type) {
  10459. if (type === Engine.TEXTURETYPE_FLOAT) {
  10460. return this._gl.FLOAT;
  10461. }
  10462. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10463. // Add Half Float Constant.
  10464. return Engine.HALF_FLOAT_OES;
  10465. }
  10466. return this._gl.UNSIGNED_BYTE;
  10467. };
  10468. ;
  10469. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10470. if (this._webGLVersion === 1) {
  10471. return this._gl.RGBA;
  10472. }
  10473. if (type === Engine.TEXTURETYPE_FLOAT) {
  10474. return Engine.RGBA32F;
  10475. }
  10476. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10477. return Engine.RGBA16F;
  10478. }
  10479. return this._gl.RGBA;
  10480. };
  10481. ;
  10482. // Statics
  10483. Engine.isSupported = function () {
  10484. try {
  10485. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10486. if (navigator.isCocoonJS) {
  10487. return true;
  10488. }
  10489. var tempcanvas = document.createElement("canvas");
  10490. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10491. return gl != null && !!window.WebGLRenderingContext;
  10492. }
  10493. catch (e) {
  10494. return false;
  10495. }
  10496. };
  10497. return Engine;
  10498. }());
  10499. Engine.Instances = new Array();
  10500. // Const statics
  10501. Engine._ALPHA_DISABLE = 0;
  10502. Engine._ALPHA_ADD = 1;
  10503. Engine._ALPHA_COMBINE = 2;
  10504. Engine._ALPHA_SUBTRACT = 3;
  10505. Engine._ALPHA_MULTIPLY = 4;
  10506. Engine._ALPHA_MAXIMIZED = 5;
  10507. Engine._ALPHA_ONEONE = 6;
  10508. Engine._ALPHA_PREMULTIPLIED = 7;
  10509. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10510. Engine._ALPHA_INTERPOLATE = 9;
  10511. Engine._ALPHA_SCREENMODE = 10;
  10512. Engine._DELAYLOADSTATE_NONE = 0;
  10513. Engine._DELAYLOADSTATE_LOADED = 1;
  10514. Engine._DELAYLOADSTATE_LOADING = 2;
  10515. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10516. Engine._TEXTUREFORMAT_ALPHA = 0;
  10517. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10518. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10519. Engine._TEXTUREFORMAT_RGB = 4;
  10520. Engine._TEXTUREFORMAT_RGBA = 5;
  10521. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10522. Engine._TEXTURETYPE_FLOAT = 1;
  10523. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10524. // Depht or Stencil test Constants.
  10525. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10526. 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.
  10527. 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.
  10528. 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.
  10529. 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.
  10530. 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.
  10531. 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.
  10532. 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.
  10533. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10534. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10535. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10536. // Stencil Actions Constants.
  10537. Engine._KEEP = 0x1E00;
  10538. Engine._REPLACE = 0x1E01;
  10539. Engine._INCR = 0x1E02;
  10540. Engine._DECR = 0x1E03;
  10541. Engine._INVERT = 0x150A;
  10542. Engine._INCR_WRAP = 0x8507;
  10543. Engine._DECR_WRAP = 0x8508;
  10544. // Texture rescaling mode
  10545. Engine._SCALEMODE_FLOOR = 1;
  10546. Engine._SCALEMODE_NEAREST = 2;
  10547. Engine._SCALEMODE_CEILING = 3;
  10548. // Updatable statics so stick with vars here
  10549. Engine.CollisionsEpsilon = 0.001;
  10550. Engine.CodeRepository = "src/";
  10551. Engine.ShadersRepository = "src/Shaders/";
  10552. BABYLON.Engine = Engine;
  10553. })(BABYLON || (BABYLON = {}));
  10554. //# sourceMappingURL=babylon.engine.js.map
  10555. /// <reference path="Tools\babylon.decorators.ts" />
  10556. var BABYLON;
  10557. (function (BABYLON) {
  10558. /**
  10559. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10560. */
  10561. var Node = (function () {
  10562. /**
  10563. * @constructor
  10564. * @param {string} name - the name and id to be given to this node
  10565. * @param {BABYLON.Scene} the scene this node will be added to
  10566. */
  10567. function Node(name, scene) {
  10568. this.state = "";
  10569. this.metadata = null;
  10570. this.doNotSerialize = false;
  10571. this.animations = new Array();
  10572. this._ranges = {};
  10573. this._childrenFlag = -1;
  10574. this._isEnabled = true;
  10575. this._isReady = true;
  10576. this._currentRenderId = -1;
  10577. this._parentRenderId = -1;
  10578. /**
  10579. * An event triggered when the mesh is disposed.
  10580. * @type {BABYLON.Observable}
  10581. */
  10582. this.onDisposeObservable = new BABYLON.Observable();
  10583. this.name = name;
  10584. this.id = name;
  10585. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10586. this._initCache();
  10587. }
  10588. Object.defineProperty(Node.prototype, "parent", {
  10589. get: function () {
  10590. return this._parentNode;
  10591. },
  10592. set: function (parent) {
  10593. if (this._parentNode === parent) {
  10594. return;
  10595. }
  10596. if (this._parentNode) {
  10597. var index = this._parentNode._children.indexOf(this);
  10598. if (index !== -1) {
  10599. this._parentNode._children.splice(index, 1);
  10600. }
  10601. }
  10602. this._parentNode = parent;
  10603. if (this._parentNode) {
  10604. if (!this._parentNode._children) {
  10605. this._parentNode._children = new Array();
  10606. }
  10607. this._parentNode._children.push(this);
  10608. }
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Node.prototype.getClassName = function () {
  10614. return "Node";
  10615. };
  10616. Object.defineProperty(Node.prototype, "onDispose", {
  10617. set: function (callback) {
  10618. if (this._onDisposeObserver) {
  10619. this.onDisposeObservable.remove(this._onDisposeObserver);
  10620. }
  10621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Node.prototype.getScene = function () {
  10627. return this._scene;
  10628. };
  10629. Node.prototype.getEngine = function () {
  10630. return this._scene.getEngine();
  10631. };
  10632. // override it in derived class
  10633. Node.prototype.getWorldMatrix = function () {
  10634. return BABYLON.Matrix.Identity();
  10635. };
  10636. // override it in derived class if you add new variables to the cache
  10637. // and call the parent class method
  10638. Node.prototype._initCache = function () {
  10639. this._cache = {};
  10640. this._cache.parent = undefined;
  10641. };
  10642. Node.prototype.updateCache = function (force) {
  10643. if (!force && this.isSynchronized())
  10644. return;
  10645. this._cache.parent = this.parent;
  10646. this._updateCache();
  10647. };
  10648. // override it in derived class if you add new variables to the cache
  10649. // and call the parent class method if !ignoreParentClass
  10650. Node.prototype._updateCache = function (ignoreParentClass) {
  10651. };
  10652. // override it in derived class if you add new variables to the cache
  10653. Node.prototype._isSynchronized = function () {
  10654. return true;
  10655. };
  10656. Node.prototype._markSyncedWithParent = function () {
  10657. this._parentRenderId = this.parent._currentRenderId;
  10658. };
  10659. Node.prototype.isSynchronizedWithParent = function () {
  10660. if (!this.parent) {
  10661. return true;
  10662. }
  10663. if (this._parentRenderId !== this.parent._currentRenderId) {
  10664. return false;
  10665. }
  10666. return this.parent.isSynchronized();
  10667. };
  10668. Node.prototype.isSynchronized = function (updateCache) {
  10669. var check = this.hasNewParent();
  10670. check = check || !this.isSynchronizedWithParent();
  10671. check = check || !this._isSynchronized();
  10672. if (updateCache)
  10673. this.updateCache(true);
  10674. return !check;
  10675. };
  10676. Node.prototype.hasNewParent = function (update) {
  10677. if (this._cache.parent === this.parent)
  10678. return false;
  10679. if (update)
  10680. this._cache.parent = this.parent;
  10681. return true;
  10682. };
  10683. /**
  10684. * Is this node ready to be used/rendered
  10685. * @return {boolean} is it ready
  10686. */
  10687. Node.prototype.isReady = function () {
  10688. return this._isReady;
  10689. };
  10690. /**
  10691. * Is this node enabled.
  10692. * If the node has a parent and is enabled, the parent will be inspected as well.
  10693. * @return {boolean} whether this node (and its parent) is enabled.
  10694. * @see setEnabled
  10695. */
  10696. Node.prototype.isEnabled = function () {
  10697. if (!this._isEnabled) {
  10698. return false;
  10699. }
  10700. if (this.parent) {
  10701. return this.parent.isEnabled();
  10702. }
  10703. return true;
  10704. };
  10705. /**
  10706. * Set the enabled state of this node.
  10707. * @param {boolean} value - the new enabled state
  10708. * @see isEnabled
  10709. */
  10710. Node.prototype.setEnabled = function (value) {
  10711. this._isEnabled = value;
  10712. };
  10713. /**
  10714. * Is this node a descendant of the given node.
  10715. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10716. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10717. * @see parent
  10718. */
  10719. Node.prototype.isDescendantOf = function (ancestor) {
  10720. if (this.parent) {
  10721. if (this.parent === ancestor) {
  10722. return true;
  10723. }
  10724. return this.parent.isDescendantOf(ancestor);
  10725. }
  10726. return false;
  10727. };
  10728. /**
  10729. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10730. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10731. * @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.
  10732. * @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.
  10733. */
  10734. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10735. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10736. if (!this._children) {
  10737. return;
  10738. }
  10739. for (var index = 0; index < this._children.length; index++) {
  10740. var item = this._children[index];
  10741. if (!predicate || predicate(item)) {
  10742. results.push(item);
  10743. }
  10744. if (!directDescendantsOnly) {
  10745. item._getDescendants(results, false, predicate);
  10746. }
  10747. }
  10748. };
  10749. /**
  10750. * Will return all nodes that have this node as ascendant.
  10751. * @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.
  10752. * @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.
  10753. * @return {BABYLON.Node[]} all children nodes of all types.
  10754. */
  10755. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10756. var results = [];
  10757. this._getDescendants(results, directDescendantsOnly, predicate);
  10758. return results;
  10759. };
  10760. /**
  10761. * Get all child-meshes of this node.
  10762. */
  10763. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10764. var results = [];
  10765. this._getDescendants(results, directDecendantsOnly, function (node) {
  10766. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10767. });
  10768. return results;
  10769. };
  10770. /**
  10771. * Get all direct children of this node.
  10772. */
  10773. Node.prototype.getChildren = function (predicate) {
  10774. return this.getDescendants(true, predicate);
  10775. };
  10776. Node.prototype._setReady = function (state) {
  10777. if (state === this._isReady) {
  10778. return;
  10779. }
  10780. if (!state) {
  10781. this._isReady = false;
  10782. return;
  10783. }
  10784. this._isReady = true;
  10785. if (this.onReady) {
  10786. this.onReady(this);
  10787. }
  10788. };
  10789. Node.prototype.getAnimationByName = function (name) {
  10790. for (var i = 0; i < this.animations.length; i++) {
  10791. var animation = this.animations[i];
  10792. if (animation.name === name) {
  10793. return animation;
  10794. }
  10795. }
  10796. return null;
  10797. };
  10798. Node.prototype.createAnimationRange = function (name, from, to) {
  10799. // check name not already in use
  10800. if (!this._ranges[name]) {
  10801. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10802. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10803. if (this.animations[i]) {
  10804. this.animations[i].createRange(name, from, to);
  10805. }
  10806. }
  10807. }
  10808. };
  10809. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10810. if (deleteFrames === void 0) { deleteFrames = true; }
  10811. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10812. if (this.animations[i]) {
  10813. this.animations[i].deleteRange(name, deleteFrames);
  10814. }
  10815. }
  10816. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10817. };
  10818. Node.prototype.getAnimationRange = function (name) {
  10819. return this._ranges[name];
  10820. };
  10821. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10822. var range = this.getAnimationRange(name);
  10823. if (!range) {
  10824. return null;
  10825. }
  10826. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10827. };
  10828. Node.prototype.serializeAnimationRanges = function () {
  10829. var serializationRanges = [];
  10830. for (var name in this._ranges) {
  10831. var range = {};
  10832. range.name = name;
  10833. range.from = this._ranges[name].from;
  10834. range.to = this._ranges[name].to;
  10835. serializationRanges.push(range);
  10836. }
  10837. return serializationRanges;
  10838. };
  10839. Node.prototype.dispose = function () {
  10840. this.parent = null;
  10841. // Callback
  10842. this.onDisposeObservable.notifyObservers(this);
  10843. this.onDisposeObservable.clear();
  10844. };
  10845. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10846. if (parsedNode.ranges) {
  10847. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10848. var data = parsedNode.ranges[index];
  10849. node.createAnimationRange(data.name, data.from, data.to);
  10850. }
  10851. }
  10852. };
  10853. return Node;
  10854. }());
  10855. __decorate([
  10856. BABYLON.serialize()
  10857. ], Node.prototype, "name", void 0);
  10858. __decorate([
  10859. BABYLON.serialize()
  10860. ], Node.prototype, "id", void 0);
  10861. __decorate([
  10862. BABYLON.serialize()
  10863. ], Node.prototype, "uniqueId", void 0);
  10864. __decorate([
  10865. BABYLON.serialize()
  10866. ], Node.prototype, "state", void 0);
  10867. __decorate([
  10868. BABYLON.serialize()
  10869. ], Node.prototype, "metadata", void 0);
  10870. BABYLON.Node = Node;
  10871. })(BABYLON || (BABYLON = {}));
  10872. //# sourceMappingURL=babylon.node.js.map
  10873. var BABYLON;
  10874. (function (BABYLON) {
  10875. var BoundingSphere = (function () {
  10876. function BoundingSphere(minimum, maximum) {
  10877. this.minimum = minimum;
  10878. this.maximum = maximum;
  10879. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10880. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10881. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10882. this.radius = distance * 0.5;
  10883. this.centerWorld = BABYLON.Vector3.Zero();
  10884. this._update(BABYLON.Matrix.Identity());
  10885. }
  10886. // Methods
  10887. BoundingSphere.prototype._update = function (world) {
  10888. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10889. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10890. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10891. };
  10892. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10893. for (var i = 0; i < 6; i++) {
  10894. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10895. return false;
  10896. }
  10897. return true;
  10898. };
  10899. BoundingSphere.prototype.intersectsPoint = function (point) {
  10900. var x = this.centerWorld.x - point.x;
  10901. var y = this.centerWorld.y - point.y;
  10902. var z = this.centerWorld.z - point.z;
  10903. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10904. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10905. return false;
  10906. return true;
  10907. };
  10908. // Statics
  10909. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10910. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10911. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10912. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10913. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10914. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10915. return false;
  10916. return true;
  10917. };
  10918. return BoundingSphere;
  10919. }());
  10920. BABYLON.BoundingSphere = BoundingSphere;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.boundingSphere.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. var BoundingBox = (function () {
  10926. function BoundingBox(minimum, maximum) {
  10927. this.minimum = minimum;
  10928. this.maximum = maximum;
  10929. this.vectors = new Array();
  10930. this.vectorsWorld = new Array();
  10931. // Bounding vectors
  10932. this.vectors.push(this.minimum.clone());
  10933. this.vectors.push(this.maximum.clone());
  10934. this.vectors.push(this.minimum.clone());
  10935. this.vectors[2].x = this.maximum.x;
  10936. this.vectors.push(this.minimum.clone());
  10937. this.vectors[3].y = this.maximum.y;
  10938. this.vectors.push(this.minimum.clone());
  10939. this.vectors[4].z = this.maximum.z;
  10940. this.vectors.push(this.maximum.clone());
  10941. this.vectors[5].z = this.minimum.z;
  10942. this.vectors.push(this.maximum.clone());
  10943. this.vectors[6].x = this.minimum.x;
  10944. this.vectors.push(this.maximum.clone());
  10945. this.vectors[7].y = this.minimum.y;
  10946. // OBB
  10947. this.center = this.maximum.add(this.minimum).scale(0.5);
  10948. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10949. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10950. // World
  10951. for (var index = 0; index < this.vectors.length; index++) {
  10952. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10953. }
  10954. this.minimumWorld = BABYLON.Vector3.Zero();
  10955. this.maximumWorld = BABYLON.Vector3.Zero();
  10956. this.centerWorld = BABYLON.Vector3.Zero();
  10957. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10958. this._update(BABYLON.Matrix.Identity());
  10959. }
  10960. // Methods
  10961. BoundingBox.prototype.getWorldMatrix = function () {
  10962. return this._worldMatrix;
  10963. };
  10964. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10965. this._worldMatrix.copyFrom(matrix);
  10966. return this;
  10967. };
  10968. BoundingBox.prototype._update = function (world) {
  10969. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10970. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10971. for (var index = 0; index < this.vectors.length; index++) {
  10972. var v = this.vectorsWorld[index];
  10973. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10974. if (v.x < this.minimumWorld.x)
  10975. this.minimumWorld.x = v.x;
  10976. if (v.y < this.minimumWorld.y)
  10977. this.minimumWorld.y = v.y;
  10978. if (v.z < this.minimumWorld.z)
  10979. this.minimumWorld.z = v.z;
  10980. if (v.x > this.maximumWorld.x)
  10981. this.maximumWorld.x = v.x;
  10982. if (v.y > this.maximumWorld.y)
  10983. this.maximumWorld.y = v.y;
  10984. if (v.z > this.maximumWorld.z)
  10985. this.maximumWorld.z = v.z;
  10986. }
  10987. // Extend
  10988. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10989. this.extendSizeWorld.scaleInPlace(0.5);
  10990. // OBB
  10991. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10992. this.centerWorld.scaleInPlace(0.5);
  10993. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10994. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10995. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10996. this._worldMatrix = world;
  10997. };
  10998. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10999. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11000. };
  11001. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11002. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11003. };
  11004. BoundingBox.prototype.intersectsPoint = function (point) {
  11005. var delta = -BABYLON.Epsilon;
  11006. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11007. return false;
  11008. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11009. return false;
  11010. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11011. return false;
  11012. return true;
  11013. };
  11014. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11015. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11016. };
  11017. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11018. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11019. return false;
  11020. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11021. return false;
  11022. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11023. return false;
  11024. return true;
  11025. };
  11026. // Statics
  11027. BoundingBox.Intersects = function (box0, box1) {
  11028. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11029. return false;
  11030. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11031. return false;
  11032. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11033. return false;
  11034. return true;
  11035. };
  11036. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11037. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11038. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11039. return (num <= (sphereRadius * sphereRadius));
  11040. };
  11041. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11042. for (var p = 0; p < 6; p++) {
  11043. for (var i = 0; i < 8; i++) {
  11044. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11045. return false;
  11046. }
  11047. }
  11048. }
  11049. return true;
  11050. };
  11051. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11052. for (var p = 0; p < 6; p++) {
  11053. var inCount = 8;
  11054. for (var i = 0; i < 8; i++) {
  11055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11056. --inCount;
  11057. }
  11058. else {
  11059. break;
  11060. }
  11061. }
  11062. if (inCount === 0)
  11063. return false;
  11064. }
  11065. return true;
  11066. };
  11067. return BoundingBox;
  11068. }());
  11069. BABYLON.BoundingBox = BoundingBox;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.boundingBox.js.map
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var computeBoxExtents = function (axis, box) {
  11075. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11076. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11077. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11078. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11079. var r = r0 + r1 + r2;
  11080. return {
  11081. min: p - r,
  11082. max: p + r
  11083. };
  11084. };
  11085. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11086. var axisOverlap = function (axis, box0, box1) {
  11087. var result0 = computeBoxExtents(axis, box0);
  11088. var result1 = computeBoxExtents(axis, box1);
  11089. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11090. };
  11091. var BoundingInfo = (function () {
  11092. function BoundingInfo(minimum, maximum) {
  11093. this.minimum = minimum;
  11094. this.maximum = maximum;
  11095. this._isLocked = false;
  11096. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11097. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11098. }
  11099. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11100. get: function () {
  11101. return this._isLocked;
  11102. },
  11103. set: function (value) {
  11104. this._isLocked = value;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. // Methods
  11110. BoundingInfo.prototype.update = function (world) {
  11111. if (this._isLocked) {
  11112. return;
  11113. }
  11114. this.boundingBox._update(world);
  11115. this.boundingSphere._update(world);
  11116. };
  11117. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11118. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11119. return false;
  11120. return this.boundingBox.isInFrustum(frustumPlanes);
  11121. };
  11122. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11123. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11124. };
  11125. BoundingInfo.prototype._checkCollision = function (collider) {
  11126. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11127. };
  11128. BoundingInfo.prototype.intersectsPoint = function (point) {
  11129. if (!this.boundingSphere.centerWorld) {
  11130. return false;
  11131. }
  11132. if (!this.boundingSphere.intersectsPoint(point)) {
  11133. return false;
  11134. }
  11135. if (!this.boundingBox.intersectsPoint(point)) {
  11136. return false;
  11137. }
  11138. return true;
  11139. };
  11140. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11141. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11142. return false;
  11143. }
  11144. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11145. return false;
  11146. }
  11147. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11148. return false;
  11149. }
  11150. if (!precise) {
  11151. return true;
  11152. }
  11153. var box0 = this.boundingBox;
  11154. var box1 = boundingInfo.boundingBox;
  11155. if (!axisOverlap(box0.directions[0], box0, box1))
  11156. return false;
  11157. if (!axisOverlap(box0.directions[1], box0, box1))
  11158. return false;
  11159. if (!axisOverlap(box0.directions[2], box0, box1))
  11160. return false;
  11161. if (!axisOverlap(box1.directions[0], box0, box1))
  11162. return false;
  11163. if (!axisOverlap(box1.directions[1], box0, box1))
  11164. return false;
  11165. if (!axisOverlap(box1.directions[2], box0, box1))
  11166. return false;
  11167. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11168. return false;
  11169. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11170. return false;
  11171. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11172. return false;
  11173. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11174. return false;
  11175. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11176. return false;
  11177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11178. return false;
  11179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11180. return false;
  11181. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11182. return false;
  11183. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11184. return false;
  11185. return true;
  11186. };
  11187. return BoundingInfo;
  11188. }());
  11189. BABYLON.BoundingInfo = BoundingInfo;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.boundingInfo.js.map
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var AbstractMesh = (function (_super) {
  11195. __extends(AbstractMesh, _super);
  11196. // Constructor
  11197. function AbstractMesh(name, scene) {
  11198. var _this = _super.call(this, name, scene) || this;
  11199. _this._facetNb = 0; // facet number
  11200. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11201. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11202. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11203. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11204. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11205. _this._subDiv = {
  11206. max: 1,
  11207. X: 1,
  11208. Y: 1,
  11209. Z: 1
  11210. };
  11211. // Events
  11212. /**
  11213. * An event triggered when this mesh collides with another one
  11214. * @type {BABYLON.Observable}
  11215. */
  11216. _this.onCollideObservable = new BABYLON.Observable();
  11217. /**
  11218. * An event triggered when the collision's position changes
  11219. * @type {BABYLON.Observable}
  11220. */
  11221. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11222. /**
  11223. * An event triggered after the world matrix is updated
  11224. * @type {BABYLON.Observable}
  11225. */
  11226. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11227. // Properties
  11228. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11229. _this.position = BABYLON.Vector3.Zero();
  11230. _this._rotation = BABYLON.Vector3.Zero();
  11231. _this._scaling = BABYLON.Vector3.One();
  11232. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11233. _this.visibility = 1.0;
  11234. _this.alphaIndex = Number.MAX_VALUE;
  11235. _this.infiniteDistance = false;
  11236. _this.isVisible = true;
  11237. _this.isPickable = true;
  11238. _this.showBoundingBox = false;
  11239. _this.showSubMeshesBoundingBox = false;
  11240. _this.isBlocker = false;
  11241. _this.renderingGroupId = 0;
  11242. _this._receiveShadows = false;
  11243. _this.renderOutline = false;
  11244. _this.outlineColor = BABYLON.Color3.Red();
  11245. _this.outlineWidth = 0.02;
  11246. _this.renderOverlay = false;
  11247. _this.overlayColor = BABYLON.Color3.Red();
  11248. _this.overlayAlpha = 0.5;
  11249. _this._hasVertexAlpha = false;
  11250. _this._useVertexColors = true;
  11251. _this._computeBonesUsingShaders = true;
  11252. _this._numBoneInfluencers = 4;
  11253. _this._applyFog = true;
  11254. _this.scalingDeterminant = 1;
  11255. _this.useOctreeForRenderingSelection = true;
  11256. _this.useOctreeForPicking = true;
  11257. _this.useOctreeForCollisions = true;
  11258. _this.layerMask = 0x0FFFFFFF;
  11259. /**
  11260. * True if the mesh must be rendered in any case.
  11261. */
  11262. _this.alwaysSelectAsActiveMesh = false;
  11263. // Collisions
  11264. _this._checkCollisions = false;
  11265. _this._collisionMask = -1;
  11266. _this._collisionGroup = -1;
  11267. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11268. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11269. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11270. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11271. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11272. // Edges
  11273. _this.edgesWidth = 1;
  11274. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11275. // Cache
  11276. _this._localWorld = BABYLON.Matrix.Zero();
  11277. _this._worldMatrix = BABYLON.Matrix.Zero();
  11278. _this._absolutePosition = BABYLON.Vector3.Zero();
  11279. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11280. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11281. _this._isDirty = false;
  11282. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11283. _this._isDisposed = false;
  11284. _this._renderId = 0;
  11285. _this._intersectionsInProgress = new Array();
  11286. _this._isWorldMatrixFrozen = false;
  11287. _this._unIndexed = false;
  11288. _this._lightSources = new Array();
  11289. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11290. if (collidedMesh === void 0) { collidedMesh = null; }
  11291. //TODO move this to the collision coordinator!
  11292. if (_this.getScene().workerCollisions)
  11293. newPosition.multiplyInPlace(_this._collider.radius);
  11294. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11295. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11296. _this.position.addInPlace(_this._diffPositionForCollisions);
  11297. }
  11298. if (collidedMesh) {
  11299. _this.onCollideObservable.notifyObservers(collidedMesh);
  11300. }
  11301. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11302. };
  11303. _this.getScene().addMesh(_this);
  11304. _this._resyncLightSources();
  11305. return _this;
  11306. }
  11307. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11308. get: function () {
  11309. return AbstractMesh._BILLBOARDMODE_NONE;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11315. get: function () {
  11316. return AbstractMesh._BILLBOARDMODE_X;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11322. get: function () {
  11323. return AbstractMesh._BILLBOARDMODE_Y;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11329. get: function () {
  11330. return AbstractMesh._BILLBOARDMODE_Z;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11336. get: function () {
  11337. return AbstractMesh._BILLBOARDMODE_ALL;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11343. /**
  11344. * Read-only : the number of facets in the mesh
  11345. */
  11346. get: function () {
  11347. return this._facetNb;
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11353. /**
  11354. * The number (integer) of subdivisions per axis in the partioning space
  11355. */
  11356. get: function () {
  11357. return this._partitioningSubdivisions;
  11358. },
  11359. set: function (nb) {
  11360. this._partitioningSubdivisions = nb;
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11366. /**
  11367. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11368. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11369. */
  11370. get: function () {
  11371. return this._partitioningBBoxRatio;
  11372. },
  11373. set: function (ratio) {
  11374. this._partitioningBBoxRatio = ratio;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11380. /**
  11381. * Read-only boolean : is the feature facetData enabled ?
  11382. */
  11383. get: function () {
  11384. return this._facetDataEnabled;
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11390. set: function (callback) {
  11391. if (this._onCollideObserver) {
  11392. this.onCollideObservable.remove(this._onCollideObserver);
  11393. }
  11394. this._onCollideObserver = this.onCollideObservable.add(callback);
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11400. set: function (callback) {
  11401. if (this._onCollisionPositionChangeObserver) {
  11402. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11403. }
  11404. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(AbstractMesh.prototype, "material", {
  11410. get: function () {
  11411. return this._material;
  11412. },
  11413. set: function (value) {
  11414. if (this._material === value) {
  11415. return;
  11416. }
  11417. this._material = value;
  11418. if (!this.subMeshes) {
  11419. return;
  11420. }
  11421. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11422. var subMesh = _a[_i];
  11423. subMesh.setEffect(null);
  11424. }
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11430. get: function () {
  11431. return this._receiveShadows;
  11432. },
  11433. set: function (value) {
  11434. if (this._receiveShadows === value) {
  11435. return;
  11436. }
  11437. this._receiveShadows = value;
  11438. this._markSubMeshesAsLightDirty();
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11444. get: function () {
  11445. return this._hasVertexAlpha;
  11446. },
  11447. set: function (value) {
  11448. if (this._hasVertexAlpha === value) {
  11449. return;
  11450. }
  11451. this._hasVertexAlpha = value;
  11452. this._markSubMeshesAsAttributesDirty();
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11458. get: function () {
  11459. return this._useVertexColors;
  11460. },
  11461. set: function (value) {
  11462. if (this._useVertexColors === value) {
  11463. return;
  11464. }
  11465. this._useVertexColors = value;
  11466. this._markSubMeshesAsAttributesDirty();
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11472. get: function () {
  11473. return this._computeBonesUsingShaders;
  11474. },
  11475. set: function (value) {
  11476. if (this._computeBonesUsingShaders === value) {
  11477. return;
  11478. }
  11479. this._computeBonesUsingShaders = value;
  11480. this._markSubMeshesAsAttributesDirty();
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11486. get: function () {
  11487. return this._numBoneInfluencers;
  11488. },
  11489. set: function (value) {
  11490. if (this._numBoneInfluencers === value) {
  11491. return;
  11492. }
  11493. this._numBoneInfluencers = value;
  11494. this._markSubMeshesAsAttributesDirty();
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11500. get: function () {
  11501. return this._applyFog;
  11502. },
  11503. set: function (value) {
  11504. if (this._applyFog === value) {
  11505. return;
  11506. }
  11507. this._applyFog = value;
  11508. this._markSubMeshesAsMiscDirty();
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11514. get: function () {
  11515. return this._collisionMask;
  11516. },
  11517. set: function (mask) {
  11518. this._collisionMask = !isNaN(mask) ? mask : -1;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11524. get: function () {
  11525. return this._collisionGroup;
  11526. },
  11527. set: function (mask) {
  11528. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11529. },
  11530. enumerable: true,
  11531. configurable: true
  11532. });
  11533. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11534. get: function () {
  11535. return null;
  11536. },
  11537. enumerable: true,
  11538. configurable: true
  11539. });
  11540. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11541. get: function () {
  11542. return this._skeleton;
  11543. },
  11544. set: function (value) {
  11545. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11546. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11547. }
  11548. if (value && value.needInitialSkinMatrix) {
  11549. value._registerMeshWithPoseMatrix(this);
  11550. }
  11551. this._skeleton = value;
  11552. if (!this._skeleton) {
  11553. this._bonesTransformMatrices = null;
  11554. }
  11555. this._markSubMeshesAsAttributesDirty();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. /**
  11561. * Returns the string "AbstractMesh"
  11562. */
  11563. AbstractMesh.prototype.getClassName = function () {
  11564. return "AbstractMesh";
  11565. };
  11566. /**
  11567. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11568. */
  11569. AbstractMesh.prototype.toString = function (fullDetails) {
  11570. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11571. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11572. if (this._skeleton) {
  11573. ret += ", skeleton: " + this._skeleton.name;
  11574. }
  11575. if (fullDetails) {
  11576. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11577. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11578. }
  11579. return ret;
  11580. };
  11581. AbstractMesh.prototype._resyncLightSources = function () {
  11582. this._lightSources.length = 0;
  11583. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11584. var light = _a[_i];
  11585. if (!light.isEnabled()) {
  11586. continue;
  11587. }
  11588. if (light.canAffectMesh(this)) {
  11589. this._lightSources.push(light);
  11590. }
  11591. }
  11592. this._markSubMeshesAsLightDirty();
  11593. };
  11594. AbstractMesh.prototype._resyncLighSource = function (light) {
  11595. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11596. var index = this._lightSources.indexOf(light);
  11597. if (index === -1) {
  11598. if (!isIn) {
  11599. return;
  11600. }
  11601. this._lightSources.push(light);
  11602. }
  11603. else {
  11604. if (isIn) {
  11605. return;
  11606. }
  11607. this._lightSources.splice(index, 1);
  11608. }
  11609. this._markSubMeshesAsLightDirty();
  11610. };
  11611. AbstractMesh.prototype._removeLightSource = function (light) {
  11612. var index = this._lightSources.indexOf(light);
  11613. if (index === -1) {
  11614. return;
  11615. }
  11616. this._lightSources.splice(index, 1);
  11617. };
  11618. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11619. if (!this.subMeshes) {
  11620. return;
  11621. }
  11622. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11623. var subMesh = _a[_i];
  11624. if (subMesh._materialDefines) {
  11625. func(subMesh._materialDefines);
  11626. }
  11627. }
  11628. };
  11629. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11630. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11631. };
  11632. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11633. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11634. };
  11635. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11636. if (!this.subMeshes) {
  11637. return;
  11638. }
  11639. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11640. var subMesh = _a[_i];
  11641. var material = subMesh.getMaterial();
  11642. if (material) {
  11643. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11644. }
  11645. }
  11646. };
  11647. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11648. /**
  11649. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11650. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11651. * Default : (0.0, 0.0, 0.0)
  11652. */
  11653. get: function () {
  11654. return this._rotation;
  11655. },
  11656. set: function (newRotation) {
  11657. this._rotation = newRotation;
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11663. /**
  11664. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11665. * Default : (1.0, 1.0, 1.0)
  11666. */
  11667. get: function () {
  11668. return this._scaling;
  11669. },
  11670. set: function (newScaling) {
  11671. this._scaling = newScaling;
  11672. if (this.physicsImpostor) {
  11673. this.physicsImpostor.forceUpdate();
  11674. }
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11680. /**
  11681. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11682. * It's null by default.
  11683. * 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)
  11684. */
  11685. get: function () {
  11686. return this._rotationQuaternion;
  11687. },
  11688. set: function (quaternion) {
  11689. this._rotationQuaternion = quaternion;
  11690. //reset the rotation vector.
  11691. if (quaternion && this.rotation.length()) {
  11692. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11693. }
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. // Methods
  11699. /**
  11700. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11701. * Returns the AbstractMesh.
  11702. */
  11703. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11704. this._poseMatrix.copyFrom(matrix);
  11705. return this;
  11706. };
  11707. /**
  11708. * Returns the mesh Pose matrix.
  11709. * Returned object : Matrix
  11710. */
  11711. AbstractMesh.prototype.getPoseMatrix = function () {
  11712. return this._poseMatrix;
  11713. };
  11714. /**
  11715. * Disables the mesh edger rendering mode.
  11716. * Returns the AbstractMesh.
  11717. */
  11718. AbstractMesh.prototype.disableEdgesRendering = function () {
  11719. if (this._edgesRenderer !== undefined) {
  11720. this._edgesRenderer.dispose();
  11721. this._edgesRenderer = undefined;
  11722. }
  11723. return this;
  11724. };
  11725. /**
  11726. * Enables the edge rendering mode on the mesh.
  11727. * This mode makes the mesh edges visible.
  11728. * Returns the AbstractMesh.
  11729. */
  11730. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11731. if (epsilon === void 0) { epsilon = 0.95; }
  11732. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11733. this.disableEdgesRendering();
  11734. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11735. return this;
  11736. };
  11737. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11738. /**
  11739. * Returns true if the mesh is blocked. Used by the class Mesh.
  11740. * Returns the boolean `false` by default.
  11741. */
  11742. get: function () {
  11743. return false;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. /**
  11749. * Returns the mesh itself by default, used by the class Mesh.
  11750. * Returned type : AbstractMesh
  11751. */
  11752. AbstractMesh.prototype.getLOD = function (camera) {
  11753. return this;
  11754. };
  11755. /**
  11756. * Returns 0 by default, used by the class Mesh.
  11757. * Returns an integer.
  11758. */
  11759. AbstractMesh.prototype.getTotalVertices = function () {
  11760. return 0;
  11761. };
  11762. /**
  11763. * Returns null by default, used by the class Mesh.
  11764. * Returned type : integer array
  11765. */
  11766. AbstractMesh.prototype.getIndices = function () {
  11767. return null;
  11768. };
  11769. /**
  11770. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11771. * Returned type : float array or Float32Array
  11772. */
  11773. AbstractMesh.prototype.getVerticesData = function (kind) {
  11774. return null;
  11775. };
  11776. /**
  11777. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11778. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11779. * The `data` are either a numeric array either a Float32Array.
  11780. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11781. * 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).
  11782. * Note that a new underlying VertexBuffer object is created each call.
  11783. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11784. *
  11785. * Possible `kind` values :
  11786. * - BABYLON.VertexBuffer.PositionKind
  11787. * - BABYLON.VertexBuffer.UVKind
  11788. * - BABYLON.VertexBuffer.UV2Kind
  11789. * - BABYLON.VertexBuffer.UV3Kind
  11790. * - BABYLON.VertexBuffer.UV4Kind
  11791. * - BABYLON.VertexBuffer.UV5Kind
  11792. * - BABYLON.VertexBuffer.UV6Kind
  11793. * - BABYLON.VertexBuffer.ColorKind
  11794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11798. *
  11799. * Returns the Mesh.
  11800. */
  11801. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11802. return null;
  11803. };
  11804. /**
  11805. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11806. * If the mesh has no geometry, it is simply returned as it is.
  11807. * The `data` are either a numeric array either a Float32Array.
  11808. * No new underlying VertexBuffer object is created.
  11809. * 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.
  11810. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11811. *
  11812. * Possible `kind` values :
  11813. * - BABYLON.VertexBuffer.PositionKind
  11814. * - BABYLON.VertexBuffer.UVKind
  11815. * - BABYLON.VertexBuffer.UV2Kind
  11816. * - BABYLON.VertexBuffer.UV3Kind
  11817. * - BABYLON.VertexBuffer.UV4Kind
  11818. * - BABYLON.VertexBuffer.UV5Kind
  11819. * - BABYLON.VertexBuffer.UV6Kind
  11820. * - BABYLON.VertexBuffer.ColorKind
  11821. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11822. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11823. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11824. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11825. *
  11826. * Returns the Mesh.
  11827. */
  11828. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11829. return null;
  11830. };
  11831. /**
  11832. * Sets the mesh indices.
  11833. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11834. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11835. * This method creates a new index buffer each call.
  11836. * Returns the Mesh.
  11837. */
  11838. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11839. return null;
  11840. };
  11841. /** Returns false by default, used by the class Mesh.
  11842. * Returns a boolean
  11843. */
  11844. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11845. return false;
  11846. };
  11847. /**
  11848. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11849. * Returns a BoundingInfo
  11850. */
  11851. AbstractMesh.prototype.getBoundingInfo = function () {
  11852. if (this._masterMesh) {
  11853. return this._masterMesh.getBoundingInfo();
  11854. }
  11855. if (!this._boundingInfo) {
  11856. this._updateBoundingInfo();
  11857. }
  11858. return this._boundingInfo;
  11859. };
  11860. /**
  11861. * Sets a mesh new object BoundingInfo.
  11862. * Returns the AbstractMesh.
  11863. */
  11864. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11865. this._boundingInfo = boundingInfo;
  11866. return this;
  11867. };
  11868. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11869. get: function () {
  11870. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. AbstractMesh.prototype._preActivate = function () {
  11876. };
  11877. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11878. };
  11879. AbstractMesh.prototype._activate = function (renderId) {
  11880. this._renderId = renderId;
  11881. };
  11882. /**
  11883. * Returns the last update of the World matrix
  11884. * Returns a Matrix.
  11885. */
  11886. AbstractMesh.prototype.getWorldMatrix = function () {
  11887. if (this._masterMesh) {
  11888. return this._masterMesh.getWorldMatrix();
  11889. }
  11890. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11891. this.computeWorldMatrix();
  11892. }
  11893. return this._worldMatrix;
  11894. };
  11895. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11896. /**
  11897. * Returns directly the last state of the mesh World matrix.
  11898. * A Matrix is returned.
  11899. */
  11900. get: function () {
  11901. return this._worldMatrix;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11907. /**
  11908. * Returns the current mesh absolute position.
  11909. * Retuns a Vector3.
  11910. */
  11911. get: function () {
  11912. return this._absolutePosition;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. /**
  11918. * Prevents the World matrix to be computed any longer.
  11919. * Returns the AbstractMesh.
  11920. */
  11921. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11922. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11923. this.computeWorldMatrix(true);
  11924. this._isWorldMatrixFrozen = true;
  11925. return this;
  11926. };
  11927. /**
  11928. * Allows back the World matrix computation.
  11929. * Returns the AbstractMesh.
  11930. */
  11931. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11932. this._isWorldMatrixFrozen = false;
  11933. this.computeWorldMatrix(true);
  11934. return this;
  11935. };
  11936. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11937. /**
  11938. * True if the World matrix has been frozen.
  11939. * Returns a boolean.
  11940. */
  11941. get: function () {
  11942. return this._isWorldMatrixFrozen;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. /**
  11948. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11949. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11950. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11951. * The passed axis is also normalized.
  11952. * Returns the AbstractMesh.
  11953. */
  11954. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11955. axis.normalize();
  11956. if (!this.rotationQuaternion) {
  11957. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11958. this.rotation = BABYLON.Vector3.Zero();
  11959. }
  11960. var rotationQuaternion;
  11961. if (!space || space === BABYLON.Space.LOCAL) {
  11962. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11963. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11964. }
  11965. else {
  11966. if (this.parent) {
  11967. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11968. invertParentWorldMatrix.invert();
  11969. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11970. }
  11971. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11972. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11973. }
  11974. return this;
  11975. };
  11976. /**
  11977. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  11978. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11979. * The passed axis is also normalized.
  11980. * Returns the AbstractMesh.
  11981. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  11982. */
  11983. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  11984. axis.normalize();
  11985. if (!this.rotationQuaternion) {
  11986. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11987. this.rotation.copyFromFloats(0, 0, 0);
  11988. }
  11989. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  11990. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  11991. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  11992. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  11993. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  11994. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  11995. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  11996. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  11997. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  11998. return this;
  11999. };
  12000. /**
  12001. * Translates the mesh along the axis vector for the passed distance in the given space.
  12002. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12003. * Returns the AbstractMesh.
  12004. */
  12005. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12006. var displacementVector = axis.scale(distance);
  12007. if (!space || space === BABYLON.Space.LOCAL) {
  12008. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12009. this.setPositionWithLocalVector(tempV3);
  12010. }
  12011. else {
  12012. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12013. }
  12014. return this;
  12015. };
  12016. /**
  12017. * Adds a rotation step to the mesh current rotation.
  12018. * x, y, z are Euler angles expressed in radians.
  12019. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12020. * This means this rotation is made in the mesh local space only.
  12021. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12022. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12023. * ```javascript
  12024. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12025. * ```
  12026. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12027. * 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.
  12028. * Returns the AbstractMesh.
  12029. */
  12030. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12031. var rotationQuaternion;
  12032. if (this.rotationQuaternion) {
  12033. rotationQuaternion = this.rotationQuaternion;
  12034. }
  12035. else {
  12036. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12037. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12038. }
  12039. var accumulation = BABYLON.Tmp.Quaternion[0];
  12040. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12041. rotationQuaternion.multiplyInPlace(accumulation);
  12042. if (!this.rotationQuaternion) {
  12043. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12044. }
  12045. return this;
  12046. };
  12047. /**
  12048. * Retuns the mesh absolute position in the World.
  12049. * Returns a Vector3.
  12050. */
  12051. AbstractMesh.prototype.getAbsolutePosition = function () {
  12052. this.computeWorldMatrix();
  12053. return this._absolutePosition;
  12054. };
  12055. /**
  12056. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12057. * Returns the AbstractMesh.
  12058. */
  12059. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12060. if (!absolutePosition) {
  12061. return;
  12062. }
  12063. var absolutePositionX;
  12064. var absolutePositionY;
  12065. var absolutePositionZ;
  12066. if (absolutePosition.x === undefined) {
  12067. if (arguments.length < 3) {
  12068. return;
  12069. }
  12070. absolutePositionX = arguments[0];
  12071. absolutePositionY = arguments[1];
  12072. absolutePositionZ = arguments[2];
  12073. }
  12074. else {
  12075. absolutePositionX = absolutePosition.x;
  12076. absolutePositionY = absolutePosition.y;
  12077. absolutePositionZ = absolutePosition.z;
  12078. }
  12079. if (this.parent) {
  12080. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12081. invertParentWorldMatrix.invert();
  12082. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12083. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12084. }
  12085. else {
  12086. this.position.x = absolutePositionX;
  12087. this.position.y = absolutePositionY;
  12088. this.position.z = absolutePositionZ;
  12089. }
  12090. return this;
  12091. };
  12092. // ================================== Point of View Movement =================================
  12093. /**
  12094. * Perform relative position change from the point of view of behind the front of the mesh.
  12095. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12096. * Supports definition of mesh facing forward or backward.
  12097. * @param {number} amountRight
  12098. * @param {number} amountUp
  12099. * @param {number} amountForward
  12100. *
  12101. * Returns the AbstractMesh.
  12102. */
  12103. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12104. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12105. return this;
  12106. };
  12107. /**
  12108. * Calculate relative position change from the point of view of behind the front of the mesh.
  12109. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12110. * Supports definition of mesh facing forward or backward.
  12111. * @param {number} amountRight
  12112. * @param {number} amountUp
  12113. * @param {number} amountForward
  12114. *
  12115. * Returns a new Vector3.
  12116. */
  12117. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12118. var rotMatrix = new BABYLON.Matrix();
  12119. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12120. rotQuaternion.toRotationMatrix(rotMatrix);
  12121. var translationDelta = BABYLON.Vector3.Zero();
  12122. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12124. return translationDelta;
  12125. };
  12126. // ================================== Point of View Rotation =================================
  12127. /**
  12128. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12129. * Supports definition of mesh facing forward or backward.
  12130. * @param {number} flipBack
  12131. * @param {number} twirlClockwise
  12132. * @param {number} tiltRight
  12133. *
  12134. * Returns the AbstractMesh.
  12135. */
  12136. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12137. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12138. return this;
  12139. };
  12140. /**
  12141. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12142. * Supports definition of mesh facing forward or backward.
  12143. * @param {number} flipBack
  12144. * @param {number} twirlClockwise
  12145. * @param {number} tiltRight
  12146. *
  12147. * Returns a new Vector3.
  12148. */
  12149. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12150. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12151. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12152. };
  12153. /**
  12154. * Sets a new pivot matrix to the mesh.
  12155. * Returns the AbstractMesh.
  12156. */
  12157. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12158. this._pivotMatrix = matrix;
  12159. this._cache.pivotMatrixUpdated = true;
  12160. return this;
  12161. };
  12162. /**
  12163. * Returns the mesh pivot matrix.
  12164. * Default : Identity.
  12165. * A Matrix is returned.
  12166. */
  12167. AbstractMesh.prototype.getPivotMatrix = function () {
  12168. return this._pivotMatrix;
  12169. };
  12170. AbstractMesh.prototype._isSynchronized = function () {
  12171. if (this._isDirty) {
  12172. return false;
  12173. }
  12174. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12175. return false;
  12176. if (this._cache.pivotMatrixUpdated) {
  12177. return false;
  12178. }
  12179. if (this.infiniteDistance) {
  12180. return false;
  12181. }
  12182. if (!this._cache.position.equals(this.position))
  12183. return false;
  12184. if (this.rotationQuaternion) {
  12185. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12186. return false;
  12187. }
  12188. if (!this._cache.rotation.equals(this.rotation))
  12189. return false;
  12190. if (!this._cache.scaling.equals(this.scaling))
  12191. return false;
  12192. return true;
  12193. };
  12194. AbstractMesh.prototype._initCache = function () {
  12195. _super.prototype._initCache.call(this);
  12196. this._cache.localMatrixUpdated = false;
  12197. this._cache.position = BABYLON.Vector3.Zero();
  12198. this._cache.scaling = BABYLON.Vector3.Zero();
  12199. this._cache.rotation = BABYLON.Vector3.Zero();
  12200. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12201. this._cache.billboardMode = -1;
  12202. };
  12203. AbstractMesh.prototype.markAsDirty = function (property) {
  12204. if (property === "rotation") {
  12205. this.rotationQuaternion = null;
  12206. }
  12207. this._currentRenderId = Number.MAX_VALUE;
  12208. this._isDirty = true;
  12209. return this;
  12210. };
  12211. /**
  12212. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12213. * Returns the AbstractMesh.
  12214. */
  12215. AbstractMesh.prototype._updateBoundingInfo = function () {
  12216. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12217. this._boundingInfo.update(this.worldMatrixFromCache);
  12218. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12219. return this;
  12220. };
  12221. /**
  12222. * Update a mesh's children BoundingInfo objects only.
  12223. * Returns the AbstractMesh.
  12224. */
  12225. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12226. if (!this.subMeshes) {
  12227. return;
  12228. }
  12229. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12230. var subMesh = this.subMeshes[subIndex];
  12231. if (!subMesh.IsGlobal) {
  12232. subMesh.updateBoundingInfo(matrix);
  12233. }
  12234. }
  12235. return this;
  12236. };
  12237. /**
  12238. * Computes the mesh World matrix and returns it.
  12239. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12240. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12241. * If the parameter `force`is set to `true`, the actual computation is done.
  12242. * Returns the mesh World Matrix.
  12243. */
  12244. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12245. if (this._isWorldMatrixFrozen) {
  12246. return this._worldMatrix;
  12247. }
  12248. if (!force && this.isSynchronized(true)) {
  12249. this._currentRenderId = this.getScene().getRenderId();
  12250. return this._worldMatrix;
  12251. }
  12252. this._cache.position.copyFrom(this.position);
  12253. this._cache.scaling.copyFrom(this.scaling);
  12254. this._cache.pivotMatrixUpdated = false;
  12255. this._cache.billboardMode = this.billboardMode;
  12256. this._currentRenderId = this.getScene().getRenderId();
  12257. this._isDirty = false;
  12258. // Scaling
  12259. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12260. // Rotation
  12261. //rotate, if quaternion is set and rotation was used
  12262. if (this.rotationQuaternion) {
  12263. var len = this.rotation.length();
  12264. if (len) {
  12265. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12266. this.rotation.copyFromFloats(0, 0, 0);
  12267. }
  12268. }
  12269. if (this.rotationQuaternion) {
  12270. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12272. }
  12273. else {
  12274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12275. this._cache.rotation.copyFrom(this.rotation);
  12276. }
  12277. // Translation
  12278. if (this.infiniteDistance && !this.parent) {
  12279. var camera = this.getScene().activeCamera;
  12280. if (camera) {
  12281. var cameraWorldMatrix = camera.getWorldMatrix();
  12282. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12283. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12284. }
  12285. }
  12286. else {
  12287. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12288. }
  12289. // Composing transformations
  12290. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12291. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12292. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12293. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12294. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12295. // Need to decompose each rotation here
  12296. var currentPosition = BABYLON.Tmp.Vector3[3];
  12297. if (this.parent && this.parent.getWorldMatrix) {
  12298. if (this._meshToBoneReferal) {
  12299. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12300. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12301. }
  12302. else {
  12303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12304. }
  12305. }
  12306. else {
  12307. currentPosition.copyFrom(this.position);
  12308. }
  12309. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12310. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12311. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12312. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12313. }
  12314. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12315. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12316. }
  12317. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12318. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12319. }
  12320. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12321. }
  12322. else {
  12323. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12324. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12325. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12326. }
  12327. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12328. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12329. }
  12330. // Local world
  12331. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12332. // Parent
  12333. if (this.parent && this.parent.getWorldMatrix) {
  12334. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12335. if (this._meshToBoneReferal) {
  12336. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12337. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12338. }
  12339. else {
  12340. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12341. }
  12342. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12343. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12344. this._worldMatrix.copyFrom(this._localWorld);
  12345. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12346. }
  12347. else {
  12348. if (this._meshToBoneReferal) {
  12349. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12350. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12351. }
  12352. else {
  12353. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12354. }
  12355. }
  12356. this._markSyncedWithParent();
  12357. }
  12358. else {
  12359. this._worldMatrix.copyFrom(this._localWorld);
  12360. }
  12361. // Bounding info
  12362. this._updateBoundingInfo();
  12363. // Absolute position
  12364. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12365. // Callbacks
  12366. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12367. if (!this._poseMatrix) {
  12368. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12369. }
  12370. return this._worldMatrix;
  12371. };
  12372. /**
  12373. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12374. * @param func: callback function to add
  12375. *
  12376. * Returns the AbstractMesh.
  12377. */
  12378. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12379. this.onAfterWorldMatrixUpdateObservable.add(func);
  12380. return this;
  12381. };
  12382. /**
  12383. * Removes a registered callback function.
  12384. * Returns the AbstractMesh.
  12385. */
  12386. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12387. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12388. return this;
  12389. };
  12390. /**
  12391. * Sets the mesh position in its local space.
  12392. * Returns the AbstractMesh.
  12393. */
  12394. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12395. this.computeWorldMatrix();
  12396. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12397. return this;
  12398. };
  12399. /**
  12400. * Returns the mesh position in the local space from the current World matrix values.
  12401. * Returns a new Vector3.
  12402. */
  12403. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12404. this.computeWorldMatrix();
  12405. var invLocalWorldMatrix = this._localWorld.clone();
  12406. invLocalWorldMatrix.invert();
  12407. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12408. };
  12409. /**
  12410. * Translates the mesh along the passed Vector3 in its local space.
  12411. * Returns the AbstractMesh.
  12412. */
  12413. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12414. this.computeWorldMatrix(true);
  12415. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12416. return this;
  12417. };
  12418. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12419. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12420. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12421. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12422. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12423. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12424. /// <returns>Mesh oriented towards targetMesh</returns>
  12425. if (yawCor === void 0) { yawCor = 0; }
  12426. if (pitchCor === void 0) { pitchCor = 0; }
  12427. if (rollCor === void 0) { rollCor = 0; }
  12428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12429. var dv = AbstractMesh._lookAtVectorCache;
  12430. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12431. targetPoint.subtractToRef(pos, dv);
  12432. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12433. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12434. var pitch = Math.atan2(dv.y, len);
  12435. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12436. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12437. return this;
  12438. };
  12439. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12440. this._meshToBoneReferal = affectedMesh;
  12441. this.parent = bone;
  12442. if (bone.getWorldMatrix().determinant() < 0) {
  12443. this.scalingDeterminant *= -1;
  12444. }
  12445. return this;
  12446. };
  12447. AbstractMesh.prototype.detachFromBone = function () {
  12448. if (this.parent.getWorldMatrix().determinant() < 0) {
  12449. this.scalingDeterminant *= -1;
  12450. }
  12451. this._meshToBoneReferal = null;
  12452. this.parent = null;
  12453. return this;
  12454. };
  12455. /**
  12456. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12457. * A mesh is in the frustum if its bounding box intersects the frustum.
  12458. * Boolean returned.
  12459. */
  12460. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12461. return this._boundingInfo.isInFrustum(frustumPlanes);
  12462. };
  12463. /**
  12464. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12465. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12466. * Boolean returned.
  12467. */
  12468. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12469. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12470. ;
  12471. };
  12472. /**
  12473. * True if the mesh intersects another mesh or a SolidParticle object.
  12474. * 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)
  12475. * Returns a boolean.
  12476. */
  12477. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12478. if (!this._boundingInfo || !mesh._boundingInfo) {
  12479. return false;
  12480. }
  12481. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12482. };
  12483. /**
  12484. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12485. * Returns a boolean.
  12486. */
  12487. AbstractMesh.prototype.intersectsPoint = function (point) {
  12488. if (!this._boundingInfo) {
  12489. return false;
  12490. }
  12491. return this._boundingInfo.intersectsPoint(point);
  12492. };
  12493. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12494. return this.physicsImpostor;
  12495. };
  12496. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12497. if (!camera) {
  12498. camera = this.getScene().activeCamera;
  12499. }
  12500. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12501. };
  12502. /**
  12503. * Returns the distance from the mesh to the active camera.
  12504. * Returns a float.
  12505. */
  12506. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12507. if (!camera) {
  12508. camera = this.getScene().activeCamera;
  12509. }
  12510. return this.absolutePosition.subtract(camera.position).length();
  12511. };
  12512. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12513. if (!this.physicsImpostor) {
  12514. return;
  12515. }
  12516. this.physicsImpostor.applyImpulse(force, contactPoint);
  12517. return this;
  12518. };
  12519. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12520. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12521. return;
  12522. }
  12523. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12524. mainPivot: pivot1,
  12525. connectedPivot: pivot2,
  12526. nativeParams: options
  12527. });
  12528. return this;
  12529. };
  12530. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12531. // Collisions
  12532. /**
  12533. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12534. * Default `false`.
  12535. */
  12536. get: function () {
  12537. return this._checkCollisions;
  12538. },
  12539. set: function (collisionEnabled) {
  12540. this._checkCollisions = collisionEnabled;
  12541. if (this.getScene().workerCollisions) {
  12542. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12543. }
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12549. var globalPosition = this.getAbsolutePosition();
  12550. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12551. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12552. if (!this._collider) {
  12553. this._collider = new BABYLON.Collider();
  12554. }
  12555. this._collider.radius = this.ellipsoid;
  12556. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12557. return this;
  12558. };
  12559. // Submeshes octree
  12560. /**
  12561. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12562. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12563. * Returns an Octree of submeshes.
  12564. */
  12565. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12566. if (maxCapacity === void 0) { maxCapacity = 64; }
  12567. if (maxDepth === void 0) { maxDepth = 2; }
  12568. if (!this._submeshesOctree) {
  12569. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12570. }
  12571. this.computeWorldMatrix(true);
  12572. // Update octree
  12573. var bbox = this.getBoundingInfo().boundingBox;
  12574. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12575. return this._submeshesOctree;
  12576. };
  12577. // Collisions
  12578. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12579. this._generatePointsArray();
  12580. // Transformation
  12581. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12582. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12583. subMesh._lastColliderWorldVertices = [];
  12584. subMesh._trianglePlanes = [];
  12585. var start = subMesh.verticesStart;
  12586. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12587. for (var i = start; i < end; i++) {
  12588. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12589. }
  12590. }
  12591. // Collide
  12592. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12593. if (collider.collisionFound) {
  12594. collider.collidedMesh = this;
  12595. }
  12596. return this;
  12597. };
  12598. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12599. var subMeshes;
  12600. var len;
  12601. // Octrees
  12602. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12603. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12604. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12605. len = intersections.length;
  12606. subMeshes = intersections.data;
  12607. }
  12608. else {
  12609. subMeshes = this.subMeshes;
  12610. len = subMeshes.length;
  12611. }
  12612. for (var index = 0; index < len; index++) {
  12613. var subMesh = subMeshes[index];
  12614. // Bounding test
  12615. if (len > 1 && !subMesh._checkCollision(collider))
  12616. continue;
  12617. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12618. }
  12619. return this;
  12620. };
  12621. AbstractMesh.prototype._checkCollision = function (collider) {
  12622. // Bounding box test
  12623. if (!this._boundingInfo._checkCollision(collider))
  12624. return this;
  12625. // Transformation matrix
  12626. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12627. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12628. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12629. return this;
  12630. };
  12631. // Picking
  12632. AbstractMesh.prototype._generatePointsArray = function () {
  12633. return false;
  12634. };
  12635. /**
  12636. * Checks if the passed Ray intersects with the mesh.
  12637. * Returns an object PickingInfo.
  12638. */
  12639. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12640. var pickingInfo = new BABYLON.PickingInfo();
  12641. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12642. return pickingInfo;
  12643. }
  12644. if (!this._generatePointsArray()) {
  12645. return pickingInfo;
  12646. }
  12647. var intersectInfo = null;
  12648. // Octrees
  12649. var subMeshes;
  12650. var len;
  12651. if (this._submeshesOctree && this.useOctreeForPicking) {
  12652. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12653. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12654. len = intersections.length;
  12655. subMeshes = intersections.data;
  12656. }
  12657. else {
  12658. subMeshes = this.subMeshes;
  12659. len = subMeshes.length;
  12660. }
  12661. for (var index = 0; index < len; index++) {
  12662. var subMesh = subMeshes[index];
  12663. // Bounding test
  12664. if (len > 1 && !subMesh.canIntersects(ray))
  12665. continue;
  12666. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12667. if (currentIntersectInfo) {
  12668. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12669. intersectInfo = currentIntersectInfo;
  12670. intersectInfo.subMeshId = index;
  12671. if (fastCheck) {
  12672. break;
  12673. }
  12674. }
  12675. }
  12676. }
  12677. if (intersectInfo) {
  12678. // Get picked point
  12679. var world = this.getWorldMatrix();
  12680. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12681. var direction = ray.direction.clone();
  12682. direction = direction.scale(intersectInfo.distance);
  12683. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12684. var pickedPoint = worldOrigin.add(worldDirection);
  12685. // Return result
  12686. pickingInfo.hit = true;
  12687. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12688. pickingInfo.pickedPoint = pickedPoint;
  12689. pickingInfo.pickedMesh = this;
  12690. pickingInfo.bu = intersectInfo.bu;
  12691. pickingInfo.bv = intersectInfo.bv;
  12692. pickingInfo.faceId = intersectInfo.faceId;
  12693. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12694. return pickingInfo;
  12695. }
  12696. return pickingInfo;
  12697. };
  12698. /**
  12699. * Clones the mesh, used by the class Mesh.
  12700. * Just returns `null` for an AbstractMesh.
  12701. */
  12702. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12703. return null;
  12704. };
  12705. /**
  12706. * Disposes all the mesh submeshes.
  12707. * Returns the AbstractMesh.
  12708. */
  12709. AbstractMesh.prototype.releaseSubMeshes = function () {
  12710. if (this.subMeshes) {
  12711. while (this.subMeshes.length) {
  12712. this.subMeshes[0].dispose();
  12713. }
  12714. }
  12715. else {
  12716. this.subMeshes = new Array();
  12717. }
  12718. return this;
  12719. };
  12720. /**
  12721. * Disposes the AbstractMesh.
  12722. * Some internal references are kept for further use.
  12723. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12724. * Returns nothing.
  12725. */
  12726. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12727. var _this = this;
  12728. var index;
  12729. // Action manager
  12730. if (this.actionManager) {
  12731. this.actionManager.dispose();
  12732. this.actionManager = null;
  12733. }
  12734. // Skeleton
  12735. this.skeleton = null;
  12736. // Animations
  12737. this.getScene().stopAnimation(this);
  12738. // Physics
  12739. if (this.physicsImpostor) {
  12740. this.physicsImpostor.dispose();
  12741. }
  12742. // Intersections in progress
  12743. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12744. var other = this._intersectionsInProgress[index];
  12745. var pos = other._intersectionsInProgress.indexOf(this);
  12746. other._intersectionsInProgress.splice(pos, 1);
  12747. }
  12748. this._intersectionsInProgress = [];
  12749. // Lights
  12750. var lights = this.getScene().lights;
  12751. lights.forEach(function (light) {
  12752. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12753. if (meshIndex !== -1) {
  12754. light.includedOnlyMeshes.splice(meshIndex, 1);
  12755. }
  12756. meshIndex = light.excludedMeshes.indexOf(_this);
  12757. if (meshIndex !== -1) {
  12758. light.excludedMeshes.splice(meshIndex, 1);
  12759. }
  12760. // Shadow generators
  12761. var generator = light.getShadowGenerator();
  12762. if (generator) {
  12763. var shadowMap = generator.getShadowMap();
  12764. meshIndex = shadowMap.renderList.indexOf(_this);
  12765. if (meshIndex !== -1) {
  12766. shadowMap.renderList.splice(meshIndex, 1);
  12767. }
  12768. }
  12769. });
  12770. // Edges
  12771. if (this._edgesRenderer) {
  12772. this._edgesRenderer.dispose();
  12773. this._edgesRenderer = null;
  12774. }
  12775. // SubMeshes
  12776. if (this.getClassName() !== "InstancedMesh") {
  12777. this.releaseSubMeshes();
  12778. }
  12779. // Octree
  12780. var sceneOctree = this.getScene().selectionOctree;
  12781. if (sceneOctree) {
  12782. var index = sceneOctree.dynamicContent.indexOf(this);
  12783. if (index !== -1) {
  12784. sceneOctree.dynamicContent.splice(index, 1);
  12785. }
  12786. }
  12787. // Engine
  12788. this.getScene().getEngine().wipeCaches();
  12789. // Remove from scene
  12790. this.getScene().removeMesh(this);
  12791. if (!doNotRecurse) {
  12792. // Particles
  12793. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12794. if (this.getScene().particleSystems[index].emitter === this) {
  12795. this.getScene().particleSystems[index].dispose();
  12796. index--;
  12797. }
  12798. }
  12799. // Children
  12800. var objects = this.getDescendants(true);
  12801. for (index = 0; index < objects.length; index++) {
  12802. objects[index].dispose();
  12803. }
  12804. }
  12805. else {
  12806. var childMeshes = this.getChildMeshes(true);
  12807. for (index = 0; index < childMeshes.length; index++) {
  12808. var child = childMeshes[index];
  12809. child.parent = null;
  12810. child.computeWorldMatrix(true);
  12811. }
  12812. }
  12813. // facet data
  12814. if (this._facetDataEnabled) {
  12815. this.disableFacetData();
  12816. }
  12817. this.onAfterWorldMatrixUpdateObservable.clear();
  12818. this.onCollideObservable.clear();
  12819. this.onCollisionPositionChangeObservable.clear();
  12820. this._isDisposed = true;
  12821. _super.prototype.dispose.call(this);
  12822. };
  12823. /**
  12824. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12825. * This Vector3 is expressed in the World space.
  12826. */
  12827. AbstractMesh.prototype.getDirection = function (localAxis) {
  12828. var result = BABYLON.Vector3.Zero();
  12829. this.getDirectionToRef(localAxis, result);
  12830. return result;
  12831. };
  12832. /**
  12833. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12834. * localAxis is expressed in the mesh local space.
  12835. * result is computed in the Wordl space from the mesh World matrix.
  12836. * Returns the AbstractMesh.
  12837. */
  12838. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12839. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12840. return this;
  12841. };
  12842. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12844. if (this.getScene().getRenderId() == 0) {
  12845. this.computeWorldMatrix(true);
  12846. }
  12847. var wm = this.getWorldMatrix();
  12848. if (space == BABYLON.Space.WORLD) {
  12849. var tmat = BABYLON.Tmp.Matrix[0];
  12850. wm.invertToRef(tmat);
  12851. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12852. }
  12853. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12854. this._pivotMatrix.m[12] = -point.x;
  12855. this._pivotMatrix.m[13] = -point.y;
  12856. this._pivotMatrix.m[14] = -point.z;
  12857. this._cache.pivotMatrixUpdated = true;
  12858. return this;
  12859. };
  12860. /**
  12861. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12862. */
  12863. AbstractMesh.prototype.getPivotPoint = function () {
  12864. var point = BABYLON.Vector3.Zero();
  12865. this.getPivotPointToRef(point);
  12866. return point;
  12867. };
  12868. /**
  12869. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12870. * Returns the AbstractMesh.
  12871. */
  12872. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12873. result.x = -this._pivotMatrix.m[12];
  12874. result.y = -this._pivotMatrix.m[13];
  12875. result.z = -this._pivotMatrix.m[14];
  12876. return this;
  12877. };
  12878. /**
  12879. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12880. */
  12881. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12882. var point = BABYLON.Vector3.Zero();
  12883. this.getAbsolutePivotPointToRef(point);
  12884. return point;
  12885. };
  12886. /**
  12887. * Defines the passed mesh as the parent of the current mesh.
  12888. * Returns the AbstractMesh.
  12889. */
  12890. AbstractMesh.prototype.setParent = function (mesh) {
  12891. var child = this;
  12892. var parent = mesh;
  12893. if (mesh == null) {
  12894. var rotation = BABYLON.Tmp.Quaternion[0];
  12895. var position = BABYLON.Tmp.Vector3[0];
  12896. var scale = BABYLON.Tmp.Vector3[1];
  12897. child.getWorldMatrix().decompose(scale, rotation, position);
  12898. if (child.rotationQuaternion) {
  12899. child.rotationQuaternion.copyFrom(rotation);
  12900. }
  12901. else {
  12902. rotation.toEulerAnglesToRef(child.rotation);
  12903. }
  12904. child.position.x = position.x;
  12905. child.position.y = position.y;
  12906. child.position.z = position.z;
  12907. }
  12908. else {
  12909. var rotation = BABYLON.Tmp.Quaternion[0];
  12910. var position = BABYLON.Tmp.Vector3[0];
  12911. var scale = BABYLON.Tmp.Vector3[1];
  12912. var m1 = BABYLON.Tmp.Matrix[0];
  12913. var m2 = BABYLON.Tmp.Matrix[1];
  12914. parent.getWorldMatrix().decompose(scale, rotation, position);
  12915. rotation.toRotationMatrix(m1);
  12916. m2.setTranslation(position);
  12917. m2.multiplyToRef(m1, m1);
  12918. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12919. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12920. m.decompose(scale, rotation, position);
  12921. if (child.rotationQuaternion) {
  12922. child.rotationQuaternion.copyFrom(rotation);
  12923. }
  12924. else {
  12925. rotation.toEulerAnglesToRef(child.rotation);
  12926. }
  12927. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12928. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12929. m.decompose(scale, rotation, position);
  12930. child.position.x = position.x;
  12931. child.position.y = position.y;
  12932. child.position.z = position.z;
  12933. }
  12934. child.parent = parent;
  12935. return this;
  12936. };
  12937. /**
  12938. * Adds the passed mesh as a child to the current mesh.
  12939. * Returns the AbstractMesh.
  12940. */
  12941. AbstractMesh.prototype.addChild = function (mesh) {
  12942. mesh.setParent(this);
  12943. return this;
  12944. };
  12945. /**
  12946. * Removes the passed mesh from the current mesh children list.
  12947. * Returns the AbstractMesh.
  12948. */
  12949. AbstractMesh.prototype.removeChild = function (mesh) {
  12950. mesh.setParent(null);
  12951. return this;
  12952. };
  12953. /**
  12954. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12955. * Returns the AbstractMesh.
  12956. */
  12957. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12958. result.x = this._pivotMatrix.m[12];
  12959. result.y = this._pivotMatrix.m[13];
  12960. result.z = this._pivotMatrix.m[14];
  12961. this.getPivotPointToRef(result);
  12962. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12963. return this;
  12964. };
  12965. // Facet data
  12966. /**
  12967. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12968. * Returns the AbstractMesh.
  12969. */
  12970. AbstractMesh.prototype._initFacetData = function () {
  12971. if (!this._facetNormals) {
  12972. this._facetNormals = new Array();
  12973. }
  12974. if (!this._facetPositions) {
  12975. this._facetPositions = new Array();
  12976. }
  12977. if (!this._facetPartitioning) {
  12978. this._facetPartitioning = new Array();
  12979. }
  12980. this._facetNb = this.getIndices().length / 3;
  12981. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12982. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12983. for (var f = 0; f < this._facetNb; f++) {
  12984. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12985. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12986. }
  12987. this._facetDataEnabled = true;
  12988. return this;
  12989. };
  12990. /**
  12991. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12992. * This method can be called within the render loop.
  12993. * 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.
  12994. * Returns the AbstractMesh.
  12995. */
  12996. AbstractMesh.prototype.updateFacetData = function () {
  12997. if (!this._facetDataEnabled) {
  12998. this._initFacetData();
  12999. }
  13000. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13001. var indices = this.getIndices();
  13002. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13003. var bInfo = this.getBoundingInfo();
  13004. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13005. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13006. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13007. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13008. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13009. this._subDiv.max = this._partitioningSubdivisions;
  13010. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13011. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13012. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13013. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13014. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13015. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13016. // set the parameters for ComputeNormals()
  13017. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13018. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13019. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13020. this._facetParameters.bInfo = bInfo;
  13021. this._facetParameters.bbSize = this._bbSize;
  13022. this._facetParameters.subDiv = this._subDiv;
  13023. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13024. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13025. return this;
  13026. };
  13027. /**
  13028. * Returns the facetLocalNormals array.
  13029. * The normals are expressed in the mesh local space.
  13030. */
  13031. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13032. if (!this._facetNormals) {
  13033. this.updateFacetData();
  13034. }
  13035. return this._facetNormals;
  13036. };
  13037. /**
  13038. * Returns the facetLocalPositions array.
  13039. * The facet positions are expressed in the mesh local space.
  13040. */
  13041. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13042. if (!this._facetPositions) {
  13043. this.updateFacetData();
  13044. }
  13045. return this._facetPositions;
  13046. };
  13047. /**
  13048. * Returns the facetLocalPartioning array.
  13049. */
  13050. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13051. if (!this._facetPartitioning) {
  13052. this.updateFacetData();
  13053. }
  13054. return this._facetPartitioning;
  13055. };
  13056. /**
  13057. * Returns the i-th facet position in the world system.
  13058. * This method allocates a new Vector3 per call.
  13059. */
  13060. AbstractMesh.prototype.getFacetPosition = function (i) {
  13061. var pos = BABYLON.Vector3.Zero();
  13062. this.getFacetPositionToRef(i, pos);
  13063. return pos;
  13064. };
  13065. /**
  13066. * Sets the reference Vector3 with the i-th facet position in the world system.
  13067. * Returns the AbstractMesh.
  13068. */
  13069. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13070. var localPos = (this.getFacetLocalPositions())[i];
  13071. var world = this.getWorldMatrix();
  13072. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13073. return this;
  13074. };
  13075. /**
  13076. * Returns the i-th facet normal in the world system.
  13077. * This method allocates a new Vector3 per call.
  13078. */
  13079. AbstractMesh.prototype.getFacetNormal = function (i) {
  13080. var norm = BABYLON.Vector3.Zero();
  13081. this.getFacetNormalToRef(i, norm);
  13082. return norm;
  13083. };
  13084. /**
  13085. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13086. * Returns the AbstractMesh.
  13087. */
  13088. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13089. var localNorm = (this.getFacetLocalNormals())[i];
  13090. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13091. return this;
  13092. };
  13093. /**
  13094. * 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).
  13095. */
  13096. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13097. var bInfo = this.getBoundingInfo();
  13098. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13099. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13100. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13101. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13102. return null;
  13103. }
  13104. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13105. };
  13106. /**
  13107. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13108. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13109. * 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.
  13110. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13111. * 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.
  13112. */
  13113. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13114. if (checkFace === void 0) { checkFace = false; }
  13115. if (facing === void 0) { facing = true; }
  13116. var world = this.getWorldMatrix();
  13117. var invMat = BABYLON.Tmp.Matrix[5];
  13118. world.invertToRef(invMat);
  13119. var invVect = BABYLON.Tmp.Vector3[8];
  13120. var closest = null;
  13121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13122. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13123. if (projected) {
  13124. // tranform the local computed projected vector to world coordinates
  13125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13126. }
  13127. return closest;
  13128. };
  13129. /**
  13130. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13131. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13132. * 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.
  13133. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13134. * 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.
  13135. */
  13136. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13137. if (checkFace === void 0) { checkFace = false; }
  13138. if (facing === void 0) { facing = true; }
  13139. var closest = null;
  13140. var tmpx = 0.0;
  13141. var tmpy = 0.0;
  13142. var tmpz = 0.0;
  13143. var d = 0.0; // tmp dot facet normal * facet position
  13144. var t0 = 0.0;
  13145. var projx = 0.0;
  13146. var projy = 0.0;
  13147. var projz = 0.0;
  13148. // Get all the facets in the same partitioning block than (x, y, z)
  13149. var facetPositions = this.getFacetLocalPositions();
  13150. var facetNormals = this.getFacetLocalNormals();
  13151. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13152. if (!facetsInBlock) {
  13153. return null;
  13154. }
  13155. // Get the closest facet to (x, y, z)
  13156. var shortest = Number.MAX_VALUE; // init distance vars
  13157. var tmpDistance = shortest;
  13158. var fib; // current facet in the block
  13159. var norm; // current facet normal
  13160. var p0; // current facet barycenter position
  13161. // loop on all the facets in the current partitioning block
  13162. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13163. fib = facetsInBlock[idx];
  13164. norm = facetNormals[fib];
  13165. p0 = facetPositions[fib];
  13166. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13167. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13168. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13169. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13170. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13171. projx = x + norm.x * t0;
  13172. projy = y + norm.y * t0;
  13173. projz = z + norm.z * t0;
  13174. tmpx = projx - x;
  13175. tmpy = projy - y;
  13176. tmpz = projz - z;
  13177. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13178. if (tmpDistance < shortest) {
  13179. shortest = tmpDistance;
  13180. closest = fib;
  13181. if (projected) {
  13182. projected.x = projx;
  13183. projected.y = projy;
  13184. projected.z = projz;
  13185. }
  13186. }
  13187. }
  13188. }
  13189. return closest;
  13190. };
  13191. /**
  13192. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13193. */
  13194. AbstractMesh.prototype.getFacetDataParameters = function () {
  13195. return this._facetParameters;
  13196. };
  13197. /**
  13198. * Disables the feature FacetData and frees the related memory.
  13199. * Returns the AbstractMesh.
  13200. */
  13201. AbstractMesh.prototype.disableFacetData = function () {
  13202. if (this._facetDataEnabled) {
  13203. this._facetDataEnabled = false;
  13204. this._facetPositions = null;
  13205. this._facetNormals = null;
  13206. this._facetPartitioning = null;
  13207. this._facetParameters = null;
  13208. }
  13209. return this;
  13210. };
  13211. /**
  13212. * Creates new normals data for the mesh.
  13213. * @param updatable.
  13214. */
  13215. AbstractMesh.prototype.createNormals = function (updatable) {
  13216. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13217. var indices = this.getIndices();
  13218. var normals;
  13219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13220. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13221. }
  13222. else {
  13223. normals = [];
  13224. }
  13225. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13226. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13227. };
  13228. return AbstractMesh;
  13229. }(BABYLON.Node));
  13230. // Statics
  13231. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13232. AbstractMesh._BILLBOARDMODE_X = 1;
  13233. AbstractMesh._BILLBOARDMODE_Y = 2;
  13234. AbstractMesh._BILLBOARDMODE_Z = 4;
  13235. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13236. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13237. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13238. BABYLON.AbstractMesh = AbstractMesh;
  13239. })(BABYLON || (BABYLON = {}));
  13240. //# sourceMappingURL=babylon.abstractMesh.js.map
  13241. var BABYLON;
  13242. (function (BABYLON) {
  13243. var Light = (function (_super) {
  13244. __extends(Light, _super);
  13245. /**
  13246. * Creates a Light object in the scene.
  13247. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13248. */
  13249. function Light(name, scene) {
  13250. var _this = _super.call(this, name, scene) || this;
  13251. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13252. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13253. _this.intensity = 1.0;
  13254. _this.range = Number.MAX_VALUE;
  13255. /**
  13256. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13257. * of light.
  13258. */
  13259. _this._photometricScale = 1.0;
  13260. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13261. _this._radius = 0.00001;
  13262. _this.renderPriority = 0;
  13263. /**
  13264. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13265. * the current shadow generator.
  13266. */
  13267. _this.shadowEnabled = true;
  13268. _this._excludeWithLayerMask = 0;
  13269. _this._includeOnlyWithLayerMask = 0;
  13270. _this._lightmapMode = 0;
  13271. _this._excludedMeshesIds = new Array();
  13272. _this._includedOnlyMeshesIds = new Array();
  13273. _this.getScene().addLight(_this);
  13274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13275. _this._buildUniformLayout();
  13276. _this.includedOnlyMeshes = new Array();
  13277. _this.excludedMeshes = new Array();
  13278. _this._resyncMeshes();
  13279. return _this;
  13280. }
  13281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13282. /**
  13283. * If every light affecting the material is in this lightmapMode,
  13284. * material.lightmapTexture adds or multiplies
  13285. * (depends on material.useLightmapAsShadowmap)
  13286. * after every other light calculations.
  13287. */
  13288. get: function () {
  13289. return Light._LIGHTMAP_DEFAULT;
  13290. },
  13291. enumerable: true,
  13292. configurable: true
  13293. });
  13294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13295. /**
  13296. * material.lightmapTexture as only diffuse lighting from this light
  13297. * adds pnly specular lighting from this light
  13298. * adds dynamic shadows
  13299. */
  13300. get: function () {
  13301. return Light._LIGHTMAP_SPECULAR;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13307. /**
  13308. * material.lightmapTexture as only lighting
  13309. * no light calculation from this light
  13310. * only adds dynamic shadows from this light
  13311. */
  13312. get: function () {
  13313. return Light._LIGHTMAP_SHADOWSONLY;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13319. /**
  13320. * Each light type uses the default quantity according to its type:
  13321. * point/spot lights use luminous intensity
  13322. * directional lights use illuminance
  13323. */
  13324. get: function () {
  13325. return Light._INTENSITYMODE_AUTOMATIC;
  13326. },
  13327. enumerable: true,
  13328. configurable: true
  13329. });
  13330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13331. /**
  13332. * lumen (lm)
  13333. */
  13334. get: function () {
  13335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13336. },
  13337. enumerable: true,
  13338. configurable: true
  13339. });
  13340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13341. /**
  13342. * candela (lm/sr)
  13343. */
  13344. get: function () {
  13345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13346. },
  13347. enumerable: true,
  13348. configurable: true
  13349. });
  13350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13351. /**
  13352. * lux (lm/m^2)
  13353. */
  13354. get: function () {
  13355. return Light._INTENSITYMODE_ILLUMINANCE;
  13356. },
  13357. enumerable: true,
  13358. configurable: true
  13359. });
  13360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13361. /**
  13362. * nit (cd/m^2)
  13363. */
  13364. get: function () {
  13365. return Light._INTENSITYMODE_LUMINANCE;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13371. /**
  13372. * Light type const id of the point light.
  13373. */
  13374. get: function () {
  13375. return Light._LIGHTTYPEID_POINTLIGHT;
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13381. /**
  13382. * Light type const id of the directional light.
  13383. */
  13384. get: function () {
  13385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13391. /**
  13392. * Light type const id of the spot light.
  13393. */
  13394. get: function () {
  13395. return Light._LIGHTTYPEID_SPOTLIGHT;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13401. /**
  13402. * Light type const id of the hemispheric light.
  13403. */
  13404. get: function () {
  13405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. Object.defineProperty(Light.prototype, "intensityMode", {
  13411. /**
  13412. * Gets the photometric scale used to interpret the intensity.
  13413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13414. */
  13415. get: function () {
  13416. return this._intensityMode;
  13417. },
  13418. /**
  13419. * Sets the photometric scale used to interpret the intensity.
  13420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13421. */
  13422. set: function (value) {
  13423. this._intensityMode = value;
  13424. this._computePhotometricScale();
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. ;
  13430. ;
  13431. Object.defineProperty(Light.prototype, "radius", {
  13432. /**
  13433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13434. */
  13435. get: function () {
  13436. return this._radius;
  13437. },
  13438. /**
  13439. * sets the light radius used by PBR Materials to simulate soft area lights.
  13440. */
  13441. set: function (value) {
  13442. this._radius = value;
  13443. this._computePhotometricScale();
  13444. },
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. ;
  13449. ;
  13450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13451. get: function () {
  13452. return this._includedOnlyMeshes;
  13453. },
  13454. set: function (value) {
  13455. this._includedOnlyMeshes = value;
  13456. this._hookArrayForIncludedOnly(value);
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13462. get: function () {
  13463. return this._excludedMeshes;
  13464. },
  13465. set: function (value) {
  13466. this._excludedMeshes = value;
  13467. this._hookArrayForExcluded(value);
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13473. get: function () {
  13474. return this._excludeWithLayerMask;
  13475. },
  13476. set: function (value) {
  13477. this._excludeWithLayerMask = value;
  13478. this._resyncMeshes();
  13479. },
  13480. enumerable: true,
  13481. configurable: true
  13482. });
  13483. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13484. get: function () {
  13485. return this._includeOnlyWithLayerMask;
  13486. },
  13487. set: function (value) {
  13488. this._includeOnlyWithLayerMask = value;
  13489. this._resyncMeshes();
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. Object.defineProperty(Light.prototype, "lightmapMode", {
  13495. get: function () {
  13496. return this._lightmapMode;
  13497. },
  13498. set: function (value) {
  13499. if (this._lightmapMode === value) {
  13500. return;
  13501. }
  13502. this._lightmapMode = value;
  13503. this._markMeshesAsLightDirty();
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Light.prototype._buildUniformLayout = function () {
  13509. // Overridden
  13510. };
  13511. /**
  13512. * Returns the string "Light".
  13513. */
  13514. Light.prototype.getClassName = function () {
  13515. return "Light";
  13516. };
  13517. /**
  13518. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13519. */
  13520. Light.prototype.toString = function (fullDetails) {
  13521. var ret = "Name: " + this.name;
  13522. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13523. if (this.animations) {
  13524. for (var i = 0; i < this.animations.length; i++) {
  13525. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13526. }
  13527. }
  13528. if (fullDetails) {
  13529. }
  13530. return ret;
  13531. };
  13532. /**
  13533. * Set the enabled state of this node.
  13534. * @param {boolean} value - the new enabled state
  13535. * @see isEnabled
  13536. */
  13537. Light.prototype.setEnabled = function (value) {
  13538. _super.prototype.setEnabled.call(this, value);
  13539. this._resyncMeshes();
  13540. };
  13541. /**
  13542. * Returns the Light associated shadow generator.
  13543. */
  13544. Light.prototype.getShadowGenerator = function () {
  13545. return this._shadowGenerator;
  13546. };
  13547. /**
  13548. * Returns a Vector3, the absolute light position in the World.
  13549. */
  13550. Light.prototype.getAbsolutePosition = function () {
  13551. return BABYLON.Vector3.Zero();
  13552. };
  13553. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13554. };
  13555. Light.prototype._getWorldMatrix = function () {
  13556. return BABYLON.Matrix.Identity();
  13557. };
  13558. /**
  13559. * Boolean : True if the light will affect the passed mesh.
  13560. */
  13561. Light.prototype.canAffectMesh = function (mesh) {
  13562. if (!mesh) {
  13563. return true;
  13564. }
  13565. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13566. return false;
  13567. }
  13568. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13569. return false;
  13570. }
  13571. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13572. return false;
  13573. }
  13574. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13575. return false;
  13576. }
  13577. return true;
  13578. };
  13579. /**
  13580. * Returns the light World matrix.
  13581. */
  13582. Light.prototype.getWorldMatrix = function () {
  13583. this._currentRenderId = this.getScene().getRenderId();
  13584. var worldMatrix = this._getWorldMatrix();
  13585. if (this.parent && this.parent.getWorldMatrix) {
  13586. if (!this._parentedWorldMatrix) {
  13587. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13588. }
  13589. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13590. this._markSyncedWithParent();
  13591. return this._parentedWorldMatrix;
  13592. }
  13593. return worldMatrix;
  13594. };
  13595. /**
  13596. * Sort function to order lights for rendering.
  13597. * @param a First Light object to compare to second.
  13598. * @param b Second Light object to compare first.
  13599. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13600. */
  13601. Light.compareLightsPriority = function (a, b) {
  13602. //shadow-casting lights have priority over non-shadow-casting lights
  13603. //the renderPrioirty is a secondary sort criterion
  13604. if (a.shadowEnabled !== b.shadowEnabled) {
  13605. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13606. }
  13607. return b.renderPriority - a.renderPriority;
  13608. };
  13609. /**
  13610. * Disposes the light.
  13611. */
  13612. Light.prototype.dispose = function () {
  13613. if (this._shadowGenerator) {
  13614. this._shadowGenerator.dispose();
  13615. this._shadowGenerator = null;
  13616. }
  13617. // Animations
  13618. this.getScene().stopAnimation(this);
  13619. // Remove from meshes
  13620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13621. var mesh = _a[_i];
  13622. mesh._removeLightSource(this);
  13623. }
  13624. this._uniformBuffer.dispose();
  13625. // Remove from scene
  13626. this.getScene().removeLight(this);
  13627. _super.prototype.dispose.call(this);
  13628. };
  13629. /**
  13630. * Returns the light type ID (integer).
  13631. */
  13632. Light.prototype.getTypeID = function () {
  13633. return 0;
  13634. };
  13635. /**
  13636. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13637. */
  13638. Light.prototype.getScaledIntensity = function () {
  13639. return this._photometricScale * this.intensity;
  13640. };
  13641. /**
  13642. * Returns a new Light object, named "name", from the current one.
  13643. */
  13644. Light.prototype.clone = function (name) {
  13645. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13646. };
  13647. /**
  13648. * Serializes the current light into a Serialization object.
  13649. * Returns the serialized object.
  13650. */
  13651. Light.prototype.serialize = function () {
  13652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13653. // Type
  13654. serializationObject.type = this.getTypeID();
  13655. // Parent
  13656. if (this.parent) {
  13657. serializationObject.parentId = this.parent.id;
  13658. }
  13659. // Inclusion / exclusions
  13660. if (this.excludedMeshes.length > 0) {
  13661. serializationObject.excludedMeshesIds = [];
  13662. this.excludedMeshes.forEach(function (mesh) {
  13663. serializationObject.excludedMeshesIds.push(mesh.id);
  13664. });
  13665. }
  13666. if (this.includedOnlyMeshes.length > 0) {
  13667. serializationObject.includedOnlyMeshesIds = [];
  13668. this.includedOnlyMeshes.forEach(function (mesh) {
  13669. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13670. });
  13671. }
  13672. // Animations
  13673. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13674. serializationObject.ranges = this.serializeAnimationRanges();
  13675. return serializationObject;
  13676. };
  13677. /**
  13678. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13679. * This new light is named "name" and added to the passed scene.
  13680. */
  13681. Light.GetConstructorFromName = function (type, name, scene) {
  13682. switch (type) {
  13683. case 0:
  13684. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13685. case 1:
  13686. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13687. case 2:
  13688. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13689. case 3:
  13690. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13691. }
  13692. };
  13693. /**
  13694. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13695. */
  13696. Light.Parse = function (parsedLight, scene) {
  13697. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13698. // Inclusion / exclusions
  13699. if (parsedLight.excludedMeshesIds) {
  13700. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13701. }
  13702. if (parsedLight.includedOnlyMeshesIds) {
  13703. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13704. }
  13705. // Parent
  13706. if (parsedLight.parentId) {
  13707. light._waitingParentId = parsedLight.parentId;
  13708. }
  13709. // Animations
  13710. if (parsedLight.animations) {
  13711. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13712. var parsedAnimation = parsedLight.animations[animationIndex];
  13713. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13714. }
  13715. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13716. }
  13717. if (parsedLight.autoAnimate) {
  13718. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13719. }
  13720. return light;
  13721. };
  13722. Light.prototype._hookArrayForExcluded = function (array) {
  13723. var _this = this;
  13724. var oldPush = array.push;
  13725. array.push = function () {
  13726. var items = [];
  13727. for (var _i = 0; _i < arguments.length; _i++) {
  13728. items[_i] = arguments[_i];
  13729. }
  13730. var result = oldPush.apply(array, items);
  13731. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13732. var item = items_1[_a];
  13733. item._resyncLighSource(_this);
  13734. }
  13735. return result;
  13736. };
  13737. var oldSplice = array.splice;
  13738. array.splice = function (index, deleteCount) {
  13739. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13740. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13741. var item = deleted_1[_i];
  13742. item._resyncLighSource(_this);
  13743. }
  13744. return deleted;
  13745. };
  13746. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13747. var item = array_1[_i];
  13748. item._resyncLighSource(this);
  13749. }
  13750. };
  13751. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13752. var _this = this;
  13753. var oldPush = array.push;
  13754. array.push = function () {
  13755. var items = [];
  13756. for (var _i = 0; _i < arguments.length; _i++) {
  13757. items[_i] = arguments[_i];
  13758. }
  13759. var result = oldPush.apply(array, items);
  13760. _this._resyncMeshes();
  13761. return result;
  13762. };
  13763. var oldSplice = array.splice;
  13764. array.splice = function (index, deleteCount) {
  13765. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13766. _this._resyncMeshes();
  13767. return deleted;
  13768. };
  13769. this._resyncMeshes();
  13770. };
  13771. Light.prototype._resyncMeshes = function () {
  13772. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13773. var mesh = _a[_i];
  13774. mesh._resyncLighSource(this);
  13775. }
  13776. };
  13777. Light.prototype._markMeshesAsLightDirty = function () {
  13778. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13779. var mesh = _a[_i];
  13780. if (mesh._lightSources.indexOf(this) !== -1) {
  13781. mesh._markSubMeshesAsLightDirty();
  13782. }
  13783. }
  13784. };
  13785. /**
  13786. * Recomputes the cached photometric scale if needed.
  13787. */
  13788. Light.prototype._computePhotometricScale = function () {
  13789. this._photometricScale = this._getPhotometricScale();
  13790. this.getScene().resetCachedMaterial();
  13791. };
  13792. /**
  13793. * Returns the Photometric Scale according to the light type and intensity mode.
  13794. */
  13795. Light.prototype._getPhotometricScale = function () {
  13796. var photometricScale = 0.0;
  13797. var lightTypeID = this.getTypeID();
  13798. //get photometric mode
  13799. var photometricMode = this.intensityMode;
  13800. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13801. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13802. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13803. }
  13804. else {
  13805. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13806. }
  13807. }
  13808. //compute photometric scale
  13809. switch (lightTypeID) {
  13810. case Light.LIGHTTYPEID_POINTLIGHT:
  13811. case Light.LIGHTTYPEID_SPOTLIGHT:
  13812. switch (photometricMode) {
  13813. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13814. photometricScale = 1.0 / (4.0 * Math.PI);
  13815. break;
  13816. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13817. photometricScale = 1.0;
  13818. break;
  13819. case Light.INTENSITYMODE_LUMINANCE:
  13820. photometricScale = this.radius * this.radius;
  13821. break;
  13822. }
  13823. break;
  13824. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13825. switch (photometricMode) {
  13826. case Light.INTENSITYMODE_ILLUMINANCE:
  13827. photometricScale = 1.0;
  13828. break;
  13829. case Light.INTENSITYMODE_LUMINANCE:
  13830. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13831. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13832. var apexAngleRadians = this.radius;
  13833. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13834. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13835. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13836. photometricScale = solidAngle;
  13837. break;
  13838. }
  13839. break;
  13840. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13841. // No fall off in hemisperic light.
  13842. photometricScale = 1.0;
  13843. break;
  13844. }
  13845. return photometricScale;
  13846. };
  13847. Light.prototype._reorderLightsInScene = function () {
  13848. var scene = this.getScene();
  13849. if (this.renderPriority != 0) {
  13850. scene.requireLightSorting = true;
  13851. }
  13852. this.getScene().sortLightsByPriority();
  13853. };
  13854. return Light;
  13855. }(BABYLON.Node));
  13856. //lightmapMode Consts
  13857. Light._LIGHTMAP_DEFAULT = 0;
  13858. Light._LIGHTMAP_SPECULAR = 1;
  13859. Light._LIGHTMAP_SHADOWSONLY = 2;
  13860. // Intensity Mode Consts
  13861. Light._INTENSITYMODE_AUTOMATIC = 0;
  13862. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13863. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13864. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13865. Light._INTENSITYMODE_LUMINANCE = 4;
  13866. // Light types ids const.
  13867. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13868. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13869. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13870. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13871. __decorate([
  13872. BABYLON.serializeAsColor3()
  13873. ], Light.prototype, "diffuse", void 0);
  13874. __decorate([
  13875. BABYLON.serializeAsColor3()
  13876. ], Light.prototype, "specular", void 0);
  13877. __decorate([
  13878. BABYLON.serialize()
  13879. ], Light.prototype, "intensity", void 0);
  13880. __decorate([
  13881. BABYLON.serialize()
  13882. ], Light.prototype, "range", void 0);
  13883. __decorate([
  13884. BABYLON.serialize()
  13885. ], Light.prototype, "intensityMode", null);
  13886. __decorate([
  13887. BABYLON.serialize()
  13888. ], Light.prototype, "radius", null);
  13889. __decorate([
  13890. BABYLON.serialize()
  13891. ], Light.prototype, "_renderPriority", void 0);
  13892. __decorate([
  13893. BABYLON.expandToProperty("_reorderLightsInScene")
  13894. ], Light.prototype, "renderPriority", void 0);
  13895. __decorate([
  13896. BABYLON.serialize()
  13897. ], Light.prototype, "shadowEnabled", void 0);
  13898. __decorate([
  13899. BABYLON.serialize("excludeWithLayerMask")
  13900. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13901. __decorate([
  13902. BABYLON.serialize("includeOnlyWithLayerMask")
  13903. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13904. __decorate([
  13905. BABYLON.serialize("lightmapMode")
  13906. ], Light.prototype, "_lightmapMode", void 0);
  13907. BABYLON.Light = Light;
  13908. })(BABYLON || (BABYLON = {}));
  13909. //# sourceMappingURL=babylon.light.js.map
  13910. var BABYLON;
  13911. (function (BABYLON) {
  13912. var Camera = (function (_super) {
  13913. __extends(Camera, _super);
  13914. function Camera(name, position, scene) {
  13915. var _this = _super.call(this, name, scene) || this;
  13916. _this.upVector = BABYLON.Vector3.Up();
  13917. _this.orthoLeft = null;
  13918. _this.orthoRight = null;
  13919. _this.orthoBottom = null;
  13920. _this.orthoTop = null;
  13921. _this.fov = 0.8;
  13922. _this.minZ = 1.0;
  13923. _this.maxZ = 10000.0;
  13924. _this.inertia = 0.9;
  13925. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13926. _this.isIntermediate = false;
  13927. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13928. _this.layerMask = 0x0FFFFFFF;
  13929. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13930. // Camera rig members
  13931. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13932. _this._rigCameras = new Array();
  13933. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13934. _this.customRenderTargets = new Array();
  13935. // Cache
  13936. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13937. _this._projectionMatrix = new BABYLON.Matrix();
  13938. _this._doNotComputeProjectionMatrix = false;
  13939. _this._postProcesses = new Array();
  13940. _this._transformMatrix = BABYLON.Matrix.Zero();
  13941. _this._activeMeshes = new BABYLON.SmartArray(256);
  13942. _this._globalPosition = BABYLON.Vector3.Zero();
  13943. _this._refreshFrustumPlanes = true;
  13944. _this.getScene().addCamera(_this);
  13945. if (!_this.getScene().activeCamera) {
  13946. _this.getScene().activeCamera = _this;
  13947. }
  13948. _this.position = position;
  13949. return _this;
  13950. }
  13951. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13952. get: function () {
  13953. return Camera._PERSPECTIVE_CAMERA;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13959. get: function () {
  13960. return Camera._ORTHOGRAPHIC_CAMERA;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13966. get: function () {
  13967. return Camera._FOVMODE_VERTICAL_FIXED;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13973. get: function () {
  13974. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13980. get: function () {
  13981. return Camera._RIG_MODE_NONE;
  13982. },
  13983. enumerable: true,
  13984. configurable: true
  13985. });
  13986. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13987. get: function () {
  13988. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13989. },
  13990. enumerable: true,
  13991. configurable: true
  13992. });
  13993. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13994. get: function () {
  13995. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14001. get: function () {
  14002. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14003. },
  14004. enumerable: true,
  14005. configurable: true
  14006. });
  14007. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14008. get: function () {
  14009. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14010. },
  14011. enumerable: true,
  14012. configurable: true
  14013. });
  14014. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14015. get: function () {
  14016. return Camera._RIG_MODE_VR;
  14017. },
  14018. enumerable: true,
  14019. configurable: true
  14020. });
  14021. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14022. get: function () {
  14023. return Camera._RIG_MODE_WEBVR;
  14024. },
  14025. enumerable: true,
  14026. configurable: true
  14027. });
  14028. Camera.prototype.getClassName = function () {
  14029. return "Camera";
  14030. };
  14031. /**
  14032. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14033. */
  14034. Camera.prototype.toString = function (fullDetails) {
  14035. var ret = "Name: " + this.name;
  14036. ret += ", type: " + this.getClassName();
  14037. if (this.animations) {
  14038. for (var i = 0; i < this.animations.length; i++) {
  14039. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14040. }
  14041. }
  14042. if (fullDetails) {
  14043. }
  14044. return ret;
  14045. };
  14046. Object.defineProperty(Camera.prototype, "globalPosition", {
  14047. get: function () {
  14048. return this._globalPosition;
  14049. },
  14050. enumerable: true,
  14051. configurable: true
  14052. });
  14053. Camera.prototype.getActiveMeshes = function () {
  14054. return this._activeMeshes;
  14055. };
  14056. Camera.prototype.isActiveMesh = function (mesh) {
  14057. return (this._activeMeshes.indexOf(mesh) !== -1);
  14058. };
  14059. //Cache
  14060. Camera.prototype._initCache = function () {
  14061. _super.prototype._initCache.call(this);
  14062. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14063. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14064. this._cache.mode = undefined;
  14065. this._cache.minZ = undefined;
  14066. this._cache.maxZ = undefined;
  14067. this._cache.fov = undefined;
  14068. this._cache.fovMode = undefined;
  14069. this._cache.aspectRatio = undefined;
  14070. this._cache.orthoLeft = undefined;
  14071. this._cache.orthoRight = undefined;
  14072. this._cache.orthoBottom = undefined;
  14073. this._cache.orthoTop = undefined;
  14074. this._cache.renderWidth = undefined;
  14075. this._cache.renderHeight = undefined;
  14076. };
  14077. Camera.prototype._updateCache = function (ignoreParentClass) {
  14078. if (!ignoreParentClass) {
  14079. _super.prototype._updateCache.call(this);
  14080. }
  14081. var engine = this.getEngine();
  14082. this._cache.position.copyFrom(this.position);
  14083. this._cache.upVector.copyFrom(this.upVector);
  14084. this._cache.mode = this.mode;
  14085. this._cache.minZ = this.minZ;
  14086. this._cache.maxZ = this.maxZ;
  14087. this._cache.fov = this.fov;
  14088. this._cache.fovMode = this.fovMode;
  14089. this._cache.aspectRatio = engine.getAspectRatio(this);
  14090. this._cache.orthoLeft = this.orthoLeft;
  14091. this._cache.orthoRight = this.orthoRight;
  14092. this._cache.orthoBottom = this.orthoBottom;
  14093. this._cache.orthoTop = this.orthoTop;
  14094. this._cache.renderWidth = engine.getRenderWidth();
  14095. this._cache.renderHeight = engine.getRenderHeight();
  14096. };
  14097. Camera.prototype._updateFromScene = function () {
  14098. this.updateCache();
  14099. this.update();
  14100. };
  14101. // Synchronized
  14102. Camera.prototype._isSynchronized = function () {
  14103. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14104. };
  14105. Camera.prototype._isSynchronizedViewMatrix = function () {
  14106. if (!_super.prototype._isSynchronized.call(this))
  14107. return false;
  14108. return this._cache.position.equals(this.position)
  14109. && this._cache.upVector.equals(this.upVector)
  14110. && this.isSynchronizedWithParent();
  14111. };
  14112. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14113. var check = this._cache.mode === this.mode
  14114. && this._cache.minZ === this.minZ
  14115. && this._cache.maxZ === this.maxZ;
  14116. if (!check) {
  14117. return false;
  14118. }
  14119. var engine = this.getEngine();
  14120. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14121. check = this._cache.fov === this.fov
  14122. && this._cache.fovMode === this.fovMode
  14123. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14124. }
  14125. else {
  14126. check = this._cache.orthoLeft === this.orthoLeft
  14127. && this._cache.orthoRight === this.orthoRight
  14128. && this._cache.orthoBottom === this.orthoBottom
  14129. && this._cache.orthoTop === this.orthoTop
  14130. && this._cache.renderWidth === engine.getRenderWidth()
  14131. && this._cache.renderHeight === engine.getRenderHeight();
  14132. }
  14133. return check;
  14134. };
  14135. // Controls
  14136. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14137. };
  14138. Camera.prototype.detachControl = function (element) {
  14139. };
  14140. Camera.prototype.update = function () {
  14141. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14142. this._updateRigCameras();
  14143. }
  14144. this._checkInputs();
  14145. };
  14146. Camera.prototype._checkInputs = function () {
  14147. };
  14148. Object.defineProperty(Camera.prototype, "rigCameras", {
  14149. get: function () {
  14150. return this._rigCameras;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14156. get: function () {
  14157. return this._rigPostProcess;
  14158. },
  14159. enumerable: true,
  14160. configurable: true
  14161. });
  14162. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14163. // invalidate framebuffer
  14164. if (this._postProcesses.length > 0) {
  14165. this._postProcesses[0].markTextureDirty();
  14166. }
  14167. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14168. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14169. var cam = this._rigCameras[i];
  14170. var rigPostProcess = cam._rigPostProcess;
  14171. // for VR rig, there does not have to be a post process
  14172. if (rigPostProcess) {
  14173. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14174. if (isPass) {
  14175. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14176. cam.isIntermediate = this._postProcesses.length === 0;
  14177. }
  14178. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14179. rigPostProcess.markTextureDirty();
  14180. }
  14181. else {
  14182. cam._postProcesses = this._postProcesses.slice(0);
  14183. }
  14184. }
  14185. };
  14186. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14187. if (insertAt === void 0) { insertAt = null; }
  14188. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14189. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14190. return 0;
  14191. }
  14192. if (insertAt == null || insertAt < 0) {
  14193. this._postProcesses.push(postProcess);
  14194. }
  14195. else {
  14196. this._postProcesses.splice(insertAt, 0, postProcess);
  14197. }
  14198. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14199. return this._postProcesses.indexOf(postProcess);
  14200. };
  14201. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14202. if (atIndices === void 0) { atIndices = null; }
  14203. var result = [];
  14204. var i;
  14205. var index;
  14206. if (!atIndices) {
  14207. var idx = this._postProcesses.indexOf(postProcess);
  14208. if (idx !== -1) {
  14209. this._postProcesses.splice(idx, 1);
  14210. }
  14211. }
  14212. else {
  14213. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14214. // iterate descending, so can just splice as we go
  14215. for (i = atIndices.length - 1; i >= 0; i--) {
  14216. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14217. result.push(i);
  14218. continue;
  14219. }
  14220. index = atIndices[i];
  14221. this._postProcesses.splice(index, 1);
  14222. }
  14223. }
  14224. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14225. return result;
  14226. };
  14227. Camera.prototype.getWorldMatrix = function () {
  14228. if (!this._worldMatrix) {
  14229. this._worldMatrix = BABYLON.Matrix.Identity();
  14230. }
  14231. var viewMatrix = this.getViewMatrix();
  14232. viewMatrix.invertToRef(this._worldMatrix);
  14233. return this._worldMatrix;
  14234. };
  14235. Camera.prototype._getViewMatrix = function () {
  14236. return BABYLON.Matrix.Identity();
  14237. };
  14238. Camera.prototype.getViewMatrix = function (force) {
  14239. this._computedViewMatrix = this._computeViewMatrix(force);
  14240. if (!force && this._isSynchronizedViewMatrix()) {
  14241. return this._computedViewMatrix;
  14242. }
  14243. this._refreshFrustumPlanes = true;
  14244. if (!this.parent || !this.parent.getWorldMatrix) {
  14245. this._globalPosition.copyFrom(this.position);
  14246. }
  14247. else {
  14248. if (!this._worldMatrix) {
  14249. this._worldMatrix = BABYLON.Matrix.Identity();
  14250. }
  14251. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14252. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14253. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14254. this._computedViewMatrix.invert();
  14255. this._markSyncedWithParent();
  14256. }
  14257. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14258. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14259. }
  14260. this._currentRenderId = this.getScene().getRenderId();
  14261. return this._computedViewMatrix;
  14262. };
  14263. Camera.prototype._computeViewMatrix = function (force) {
  14264. if (!force && this._isSynchronizedViewMatrix()) {
  14265. return this._computedViewMatrix;
  14266. }
  14267. this._computedViewMatrix = this._getViewMatrix();
  14268. this._currentRenderId = this.getScene().getRenderId();
  14269. return this._computedViewMatrix;
  14270. };
  14271. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14272. this._doNotComputeProjectionMatrix = true;
  14273. if (projection !== undefined) {
  14274. this._projectionMatrix = projection;
  14275. }
  14276. };
  14277. ;
  14278. Camera.prototype.unfreezeProjectionMatrix = function () {
  14279. this._doNotComputeProjectionMatrix = false;
  14280. };
  14281. ;
  14282. Camera.prototype.getProjectionMatrix = function (force) {
  14283. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14284. return this._projectionMatrix;
  14285. }
  14286. this._refreshFrustumPlanes = true;
  14287. var engine = this.getEngine();
  14288. var scene = this.getScene();
  14289. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14290. if (this.minZ <= 0) {
  14291. this.minZ = 0.1;
  14292. }
  14293. if (scene.useRightHandedSystem) {
  14294. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14295. }
  14296. else {
  14297. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14298. }
  14299. return this._projectionMatrix;
  14300. }
  14301. var halfWidth = engine.getRenderWidth() / 2.0;
  14302. var halfHeight = engine.getRenderHeight() / 2.0;
  14303. if (scene.useRightHandedSystem) {
  14304. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14305. }
  14306. else {
  14307. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14308. }
  14309. return this._projectionMatrix;
  14310. };
  14311. Camera.prototype.getTranformationMatrix = function () {
  14312. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14313. return this._transformMatrix;
  14314. };
  14315. Camera.prototype.updateFrustumPlanes = function () {
  14316. if (!this._refreshFrustumPlanes) {
  14317. return;
  14318. }
  14319. this.getTranformationMatrix();
  14320. if (!this._frustumPlanes) {
  14321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14322. }
  14323. else {
  14324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14325. }
  14326. this._refreshFrustumPlanes = false;
  14327. };
  14328. Camera.prototype.isInFrustum = function (target) {
  14329. this.updateFrustumPlanes();
  14330. return target.isInFrustum(this._frustumPlanes);
  14331. };
  14332. Camera.prototype.isCompletelyInFrustum = function (target) {
  14333. this.updateFrustumPlanes();
  14334. return target.isCompletelyInFrustum(this._frustumPlanes);
  14335. };
  14336. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14337. if (length === void 0) { length = 100; }
  14338. if (!transform) {
  14339. transform = this.getWorldMatrix();
  14340. }
  14341. if (!origin) {
  14342. origin = this.position;
  14343. }
  14344. var forward = new BABYLON.Vector3(0, 0, 1);
  14345. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14346. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14347. return new BABYLON.Ray(origin, direction, length);
  14348. };
  14349. Camera.prototype.dispose = function () {
  14350. // Animations
  14351. this.getScene().stopAnimation(this);
  14352. // Remove from scene
  14353. this.getScene().removeCamera(this);
  14354. while (this._rigCameras.length > 0) {
  14355. this._rigCameras.pop().dispose();
  14356. }
  14357. // Postprocesses
  14358. var i = this._postProcesses.length;
  14359. while (--i >= 0) {
  14360. this._postProcesses[i].dispose(this);
  14361. }
  14362. _super.prototype.dispose.call(this);
  14363. };
  14364. Object.defineProperty(Camera.prototype, "leftCamera", {
  14365. // ---- Camera rigs section ----
  14366. get: function () {
  14367. if (this._rigCameras.length < 1) {
  14368. return undefined;
  14369. }
  14370. return this._rigCameras[0];
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Camera.prototype, "rightCamera", {
  14376. get: function () {
  14377. if (this._rigCameras.length < 2) {
  14378. return undefined;
  14379. }
  14380. return this._rigCameras[1];
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Camera.prototype.getLeftTarget = function () {
  14386. if (this._rigCameras.length < 1) {
  14387. return undefined;
  14388. }
  14389. return this._rigCameras[0].getTarget();
  14390. };
  14391. Camera.prototype.getRightTarget = function () {
  14392. if (this._rigCameras.length < 2) {
  14393. return undefined;
  14394. }
  14395. return this._rigCameras[1].getTarget();
  14396. };
  14397. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14398. while (this._rigCameras.length > 0) {
  14399. this._rigCameras.pop().dispose();
  14400. }
  14401. this.cameraRigMode = mode;
  14402. this._cameraRigParams = {};
  14403. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14404. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14405. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14406. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14407. // create the rig cameras, unless none
  14408. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14409. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14410. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14411. }
  14412. switch (this.cameraRigMode) {
  14413. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14414. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14415. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14416. break;
  14417. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14418. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14419. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14420. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14421. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14422. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14423. break;
  14424. case Camera.RIG_MODE_VR:
  14425. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14426. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14427. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14428. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14429. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14430. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14431. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14432. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14433. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14434. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14435. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14436. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14437. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14438. if (metrics.compensateDistortion) {
  14439. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14440. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14441. }
  14442. break;
  14443. case Camera.RIG_MODE_WEBVR:
  14444. if (rigParams.vrDisplay) {
  14445. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14446. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14447. //Left eye
  14448. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14449. this._rigCameras[0].setCameraRigParameter("left", true);
  14450. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14451. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14452. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14453. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14454. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14455. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14456. this._rigCameras[0].parent = this;
  14457. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14458. //Right eye
  14459. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14460. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14461. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14462. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14463. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14464. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14465. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14466. this._rigCameras[1].parent = this;
  14467. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14468. }
  14469. break;
  14470. }
  14471. this._cascadePostProcessesToRigCams();
  14472. this.
  14473. update();
  14474. };
  14475. Camera.prototype._getVRProjectionMatrix = function () {
  14476. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14477. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14478. return this._projectionMatrix;
  14479. };
  14480. Camera.prototype._updateCameraRotationMatrix = function () {
  14481. //Here for WebVR
  14482. };
  14483. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14484. //Here for WebVR
  14485. };
  14486. /**
  14487. * This function MUST be overwritten by the different WebVR cameras available.
  14488. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14489. */
  14490. Camera.prototype._getWebVRProjectionMatrix = function () {
  14491. return BABYLON.Matrix.Identity();
  14492. };
  14493. /**
  14494. * This function MUST be overwritten by the different WebVR cameras available.
  14495. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14496. */
  14497. Camera.prototype._getWebVRViewMatrix = function () {
  14498. return BABYLON.Matrix.Identity();
  14499. };
  14500. Camera.prototype.setCameraRigParameter = function (name, value) {
  14501. if (!this._cameraRigParams) {
  14502. this._cameraRigParams = {};
  14503. }
  14504. this._cameraRigParams[name] = value;
  14505. //provisionnally:
  14506. if (name === "interaxialDistance") {
  14507. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14508. }
  14509. };
  14510. /**
  14511. * needs to be overridden by children so sub has required properties to be copied
  14512. */
  14513. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14514. return null;
  14515. };
  14516. /**
  14517. * May need to be overridden by children
  14518. */
  14519. Camera.prototype._updateRigCameras = function () {
  14520. for (var i = 0; i < this._rigCameras.length; i++) {
  14521. this._rigCameras[i].minZ = this.minZ;
  14522. this._rigCameras[i].maxZ = this.maxZ;
  14523. this._rigCameras[i].fov = this.fov;
  14524. }
  14525. // only update viewport when ANAGLYPH
  14526. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14527. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14528. }
  14529. };
  14530. Camera.prototype._setupInputs = function () {
  14531. };
  14532. Camera.prototype.serialize = function () {
  14533. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14534. // Type
  14535. serializationObject.type = this.getClassName();
  14536. // Parent
  14537. if (this.parent) {
  14538. serializationObject.parentId = this.parent.id;
  14539. }
  14540. if (this.inputs) {
  14541. this.inputs.serialize(serializationObject);
  14542. }
  14543. // Animations
  14544. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14545. serializationObject.ranges = this.serializeAnimationRanges();
  14546. return serializationObject;
  14547. };
  14548. Camera.prototype.clone = function (name) {
  14549. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14550. };
  14551. Camera.prototype.getDirection = function (localAxis) {
  14552. var result = BABYLON.Vector3.Zero();
  14553. this.getDirectionToRef(localAxis, result);
  14554. return result;
  14555. };
  14556. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14557. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14558. };
  14559. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14560. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14561. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14562. switch (type) {
  14563. case "ArcRotateCamera":
  14564. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14565. case "DeviceOrientationCamera":
  14566. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14567. case "FollowCamera":
  14568. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14569. case "ArcFollowCamera":
  14570. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14571. case "GamepadCamera":
  14572. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14573. case "TouchCamera":
  14574. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14575. case "VirtualJoysticksCamera":
  14576. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14577. case "WebVRFreeCamera":
  14578. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14579. case "WebVRGamepadCamera":
  14580. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14581. case "VRDeviceOrientationFreeCamera":
  14582. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14583. case "VRDeviceOrientationGamepadCamera":
  14584. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14585. case "AnaglyphArcRotateCamera":
  14586. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14587. case "AnaglyphFreeCamera":
  14588. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14589. case "AnaglyphGamepadCamera":
  14590. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14591. case "AnaglyphUniversalCamera":
  14592. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14593. case "StereoscopicArcRotateCamera":
  14594. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14595. case "StereoscopicFreeCamera":
  14596. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14597. case "StereoscopicGamepadCamera":
  14598. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14599. case "StereoscopicUniversalCamera":
  14600. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14601. case "FreeCamera":
  14602. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14603. default:
  14604. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14605. }
  14606. };
  14607. Camera.Parse = function (parsedCamera, scene) {
  14608. var type = parsedCamera.type;
  14609. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14610. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14611. // Parent
  14612. if (parsedCamera.parentId) {
  14613. camera._waitingParentId = parsedCamera.parentId;
  14614. }
  14615. //If camera has an input manager, let it parse inputs settings
  14616. if (camera.inputs) {
  14617. camera.inputs.parse(parsedCamera);
  14618. camera._setupInputs();
  14619. }
  14620. if (camera.setPosition) {
  14621. camera.position.copyFromFloats(0, 0, 0);
  14622. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14623. }
  14624. // Target
  14625. if (parsedCamera.target) {
  14626. if (camera.setTarget) {
  14627. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14628. }
  14629. }
  14630. // Apply 3d rig, when found
  14631. if (parsedCamera.cameraRigMode) {
  14632. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14633. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14634. }
  14635. // Animations
  14636. if (parsedCamera.animations) {
  14637. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14638. var parsedAnimation = parsedCamera.animations[animationIndex];
  14639. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14640. }
  14641. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14642. }
  14643. if (parsedCamera.autoAnimate) {
  14644. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14645. }
  14646. return camera;
  14647. };
  14648. return Camera;
  14649. }(BABYLON.Node));
  14650. // Statics
  14651. Camera._PERSPECTIVE_CAMERA = 0;
  14652. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14653. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14654. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14655. Camera._RIG_MODE_NONE = 0;
  14656. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14657. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14658. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14659. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14660. Camera._RIG_MODE_VR = 20;
  14661. Camera._RIG_MODE_WEBVR = 21;
  14662. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14663. __decorate([
  14664. BABYLON.serializeAsVector3()
  14665. ], Camera.prototype, "position", void 0);
  14666. __decorate([
  14667. BABYLON.serializeAsVector3()
  14668. ], Camera.prototype, "upVector", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], Camera.prototype, "orthoLeft", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], Camera.prototype, "orthoRight", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], Camera.prototype, "orthoBottom", void 0);
  14678. __decorate([
  14679. BABYLON.serialize()
  14680. ], Camera.prototype, "orthoTop", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], Camera.prototype, "fov", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], Camera.prototype, "minZ", void 0);
  14687. __decorate([
  14688. BABYLON.serialize()
  14689. ], Camera.prototype, "maxZ", void 0);
  14690. __decorate([
  14691. BABYLON.serialize()
  14692. ], Camera.prototype, "inertia", void 0);
  14693. __decorate([
  14694. BABYLON.serialize()
  14695. ], Camera.prototype, "mode", void 0);
  14696. __decorate([
  14697. BABYLON.serialize()
  14698. ], Camera.prototype, "layerMask", void 0);
  14699. __decorate([
  14700. BABYLON.serialize()
  14701. ], Camera.prototype, "fovMode", void 0);
  14702. __decorate([
  14703. BABYLON.serialize()
  14704. ], Camera.prototype, "cameraRigMode", void 0);
  14705. __decorate([
  14706. BABYLON.serialize()
  14707. ], Camera.prototype, "interaxialDistance", void 0);
  14708. __decorate([
  14709. BABYLON.serialize()
  14710. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14711. BABYLON.Camera = Camera;
  14712. })(BABYLON || (BABYLON = {}));
  14713. //# sourceMappingURL=babylon.camera.js.map
  14714. var BABYLON;
  14715. (function (BABYLON) {
  14716. var RenderingManager = (function () {
  14717. function RenderingManager(scene) {
  14718. this._renderingGroups = new Array();
  14719. this._autoClearDepthStencil = {};
  14720. this._customOpaqueSortCompareFn = {};
  14721. this._customAlphaTestSortCompareFn = {};
  14722. this._customTransparentSortCompareFn = {};
  14723. this._renderinGroupInfo = null;
  14724. this._scene = scene;
  14725. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14726. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14727. }
  14728. }
  14729. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14730. if (depth === void 0) { depth = true; }
  14731. if (stencil === void 0) { stencil = true; }
  14732. if (this._depthStencilBufferAlreadyCleaned) {
  14733. return;
  14734. }
  14735. this._scene.getEngine().clear(null, false, depth, stencil);
  14736. this._depthStencilBufferAlreadyCleaned = true;
  14737. };
  14738. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14739. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14740. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14741. var info = null;
  14742. if (observable) {
  14743. if (!this._renderinGroupInfo) {
  14744. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14745. }
  14746. info = this._renderinGroupInfo;
  14747. info.scene = this._scene;
  14748. info.camera = this._scene.activeCamera;
  14749. }
  14750. // Dispatch sprites
  14751. if (renderSprites) {
  14752. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14753. var manager = this._scene.spriteManagers[index];
  14754. this.dispatchSprites(manager);
  14755. }
  14756. }
  14757. // Render
  14758. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14759. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14760. var renderingGroup = this._renderingGroups[index];
  14761. if (!renderingGroup && !observable)
  14762. continue;
  14763. this._currentIndex = index;
  14764. var renderingGroupMask = 0;
  14765. // Fire PRECLEAR stage
  14766. if (observable) {
  14767. renderingGroupMask = Math.pow(2, index);
  14768. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14769. info.renderingGroupId = index;
  14770. observable.notifyObservers(info, renderingGroupMask);
  14771. }
  14772. // Clear depth/stencil if needed
  14773. if (RenderingManager.AUTOCLEAR) {
  14774. var autoClear = this._autoClearDepthStencil[index];
  14775. if (autoClear && autoClear.autoClear) {
  14776. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14777. }
  14778. }
  14779. if (observable) {
  14780. // Fire PREOPAQUE stage
  14781. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14782. observable.notifyObservers(info, renderingGroupMask);
  14783. // Fire PRETRANSPARENT stage
  14784. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14785. observable.notifyObservers(info, renderingGroupMask);
  14786. }
  14787. if (renderingGroup)
  14788. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14789. // Fire POSTTRANSPARENT stage
  14790. if (observable) {
  14791. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14792. observable.notifyObservers(info, renderingGroupMask);
  14793. }
  14794. }
  14795. };
  14796. RenderingManager.prototype.reset = function () {
  14797. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14798. var renderingGroup = this._renderingGroups[index];
  14799. if (renderingGroup) {
  14800. renderingGroup.prepare();
  14801. }
  14802. }
  14803. };
  14804. RenderingManager.prototype.dispose = function () {
  14805. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14806. var renderingGroup = this._renderingGroups[index];
  14807. if (renderingGroup) {
  14808. renderingGroup.dispose();
  14809. }
  14810. }
  14811. this._renderingGroups.length = 0;
  14812. };
  14813. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14814. if (!this._renderingGroups[renderingGroupId]) {
  14815. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14816. }
  14817. };
  14818. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14819. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14820. this._prepareRenderingGroup(renderingGroupId);
  14821. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14822. };
  14823. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14824. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14825. this._prepareRenderingGroup(renderingGroupId);
  14826. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14827. };
  14828. RenderingManager.prototype.dispatch = function (subMesh) {
  14829. var mesh = subMesh.getMesh();
  14830. var renderingGroupId = mesh.renderingGroupId || 0;
  14831. this._prepareRenderingGroup(renderingGroupId);
  14832. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14833. };
  14834. /**
  14835. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14836. * This allowed control for front to back rendering or reversly depending of the special needs.
  14837. *
  14838. * @param renderingGroupId The rendering group id corresponding to its index
  14839. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14840. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14841. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14842. */
  14843. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14844. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14845. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14846. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14847. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14848. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14849. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14850. if (this._renderingGroups[renderingGroupId]) {
  14851. var group = this._renderingGroups[renderingGroupId];
  14852. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14853. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14854. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14855. }
  14856. };
  14857. /**
  14858. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14859. *
  14860. * @param renderingGroupId The rendering group id corresponding to its index
  14861. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14862. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14863. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14864. */
  14865. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14866. if (depth === void 0) { depth = true; }
  14867. if (stencil === void 0) { stencil = true; }
  14868. this._autoClearDepthStencil[renderingGroupId] = {
  14869. autoClear: autoClearDepthStencil,
  14870. depth: depth,
  14871. stencil: stencil
  14872. };
  14873. };
  14874. return RenderingManager;
  14875. }());
  14876. /**
  14877. * The max id used for rendering groups (not included)
  14878. */
  14879. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14880. /**
  14881. * The min id used for rendering groups (included)
  14882. */
  14883. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14884. /**
  14885. * Used to globally prevent autoclearing scenes.
  14886. */
  14887. RenderingManager.AUTOCLEAR = true;
  14888. BABYLON.RenderingManager = RenderingManager;
  14889. })(BABYLON || (BABYLON = {}));
  14890. //# sourceMappingURL=babylon.renderingManager.js.map
  14891. var BABYLON;
  14892. (function (BABYLON) {
  14893. var RenderingGroup = (function () {
  14894. /**
  14895. * Creates a new rendering group.
  14896. * @param index The rendering group index
  14897. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14898. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14899. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14900. */
  14901. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14902. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14903. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14904. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14905. this.index = index;
  14906. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14907. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14908. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14909. this._particleSystems = new BABYLON.SmartArray(256);
  14910. this._spriteManagers = new BABYLON.SmartArray(256);
  14911. this._edgesRenderers = new BABYLON.SmartArray(16);
  14912. this._scene = scene;
  14913. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14914. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14915. this.transparentSortCompareFn = transparentSortCompareFn;
  14916. }
  14917. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14918. /**
  14919. * Set the opaque sort comparison function.
  14920. * If null the sub meshes will be render in the order they were created
  14921. */
  14922. set: function (value) {
  14923. this._opaqueSortCompareFn = value;
  14924. if (value) {
  14925. this._renderOpaque = this.renderOpaqueSorted;
  14926. }
  14927. else {
  14928. this._renderOpaque = RenderingGroup.renderUnsorted;
  14929. }
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14935. /**
  14936. * Set the alpha test sort comparison function.
  14937. * If null the sub meshes will be render in the order they were created
  14938. */
  14939. set: function (value) {
  14940. this._alphaTestSortCompareFn = value;
  14941. if (value) {
  14942. this._renderAlphaTest = this.renderAlphaTestSorted;
  14943. }
  14944. else {
  14945. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14946. }
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14952. /**
  14953. * Set the transparent sort comparison function.
  14954. * If null the sub meshes will be render in the order they were created
  14955. */
  14956. set: function (value) {
  14957. if (value) {
  14958. this._transparentSortCompareFn = value;
  14959. }
  14960. else {
  14961. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14962. }
  14963. this._renderTransparent = this.renderTransparentSorted;
  14964. },
  14965. enumerable: true,
  14966. configurable: true
  14967. });
  14968. /**
  14969. * Render all the sub meshes contained in the group.
  14970. * @param customRenderFunction Used to override the default render behaviour of the group.
  14971. * @returns true if rendered some submeshes.
  14972. */
  14973. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14974. if (customRenderFunction) {
  14975. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14976. return;
  14977. }
  14978. var engine = this._scene.getEngine();
  14979. // Opaque
  14980. if (this._opaqueSubMeshes.length !== 0) {
  14981. this._renderOpaque(this._opaqueSubMeshes);
  14982. }
  14983. // Alpha test
  14984. if (this._alphaTestSubMeshes.length !== 0) {
  14985. engine.setAlphaTesting(true);
  14986. this._renderAlphaTest(this._alphaTestSubMeshes);
  14987. engine.setAlphaTesting(false);
  14988. }
  14989. var stencilState = engine.getStencilBuffer();
  14990. engine.setStencilBuffer(false);
  14991. // Sprites
  14992. if (renderSprites) {
  14993. this._renderSprites();
  14994. }
  14995. // Particles
  14996. if (renderParticles) {
  14997. this._renderParticles(activeMeshes);
  14998. }
  14999. if (this.onBeforeTransparentRendering) {
  15000. this.onBeforeTransparentRendering();
  15001. }
  15002. // Transparent
  15003. if (this._transparentSubMeshes.length !== 0) {
  15004. this._renderTransparent(this._transparentSubMeshes);
  15005. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15006. }
  15007. engine.setStencilBuffer(stencilState);
  15008. // Edges
  15009. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15010. this._edgesRenderers.data[edgesRendererIndex].render();
  15011. }
  15012. };
  15013. /**
  15014. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15015. * @param subMeshes The submeshes to render
  15016. */
  15017. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15018. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15019. };
  15020. /**
  15021. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15022. * @param subMeshes The submeshes to render
  15023. */
  15024. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15025. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15026. };
  15027. /**
  15028. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15029. * @param subMeshes The submeshes to render
  15030. */
  15031. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15032. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15033. };
  15034. /**
  15035. * Renders the submeshes in a specified order.
  15036. * @param subMeshes The submeshes to sort before render
  15037. * @param sortCompareFn The comparison function use to sort
  15038. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15039. * @param transparent Specifies to activate blending if true
  15040. */
  15041. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15042. var subIndex = 0;
  15043. var subMesh;
  15044. for (; subIndex < subMeshes.length; subIndex++) {
  15045. subMesh = subMeshes.data[subIndex];
  15046. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15047. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15048. }
  15049. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15050. sortedArray.sort(sortCompareFn);
  15051. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15052. subMesh = sortedArray[subIndex];
  15053. subMesh.render(transparent);
  15054. }
  15055. };
  15056. /**
  15057. * Renders the submeshes in the order they were dispatched (no sort applied).
  15058. * @param subMeshes The submeshes to render
  15059. */
  15060. RenderingGroup.renderUnsorted = function (subMeshes) {
  15061. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15062. var submesh = subMeshes.data[subIndex];
  15063. submesh.render(false);
  15064. }
  15065. };
  15066. /**
  15067. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15068. * are rendered back to front if in the same alpha index.
  15069. *
  15070. * @param a The first submesh
  15071. * @param b The second submesh
  15072. * @returns The result of the comparison
  15073. */
  15074. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15075. // Alpha index first
  15076. if (a._alphaIndex > b._alphaIndex) {
  15077. return 1;
  15078. }
  15079. if (a._alphaIndex < b._alphaIndex) {
  15080. return -1;
  15081. }
  15082. // Then distance to camera
  15083. return RenderingGroup.backToFrontSortCompare(a, b);
  15084. };
  15085. /**
  15086. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15087. * are rendered back to front.
  15088. *
  15089. * @param a The first submesh
  15090. * @param b The second submesh
  15091. * @returns The result of the comparison
  15092. */
  15093. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15094. // Then distance to camera
  15095. if (a._distanceToCamera < b._distanceToCamera) {
  15096. return 1;
  15097. }
  15098. if (a._distanceToCamera > b._distanceToCamera) {
  15099. return -1;
  15100. }
  15101. return 0;
  15102. };
  15103. /**
  15104. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15105. * are rendered front to back (prevent overdraw).
  15106. *
  15107. * @param a The first submesh
  15108. * @param b The second submesh
  15109. * @returns The result of the comparison
  15110. */
  15111. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15112. // Then distance to camera
  15113. if (a._distanceToCamera < b._distanceToCamera) {
  15114. return -1;
  15115. }
  15116. if (a._distanceToCamera > b._distanceToCamera) {
  15117. return 1;
  15118. }
  15119. return 0;
  15120. };
  15121. /**
  15122. * Resets the different lists of submeshes to prepare a new frame.
  15123. */
  15124. RenderingGroup.prototype.prepare = function () {
  15125. this._opaqueSubMeshes.reset();
  15126. this._transparentSubMeshes.reset();
  15127. this._alphaTestSubMeshes.reset();
  15128. this._particleSystems.reset();
  15129. this._spriteManagers.reset();
  15130. this._edgesRenderers.reset();
  15131. };
  15132. RenderingGroup.prototype.dispose = function () {
  15133. this._opaqueSubMeshes.dispose();
  15134. this._transparentSubMeshes.dispose();
  15135. this._alphaTestSubMeshes.dispose();
  15136. this._particleSystems.dispose();
  15137. this._spriteManagers.dispose();
  15138. this._edgesRenderers.dispose();
  15139. };
  15140. /**
  15141. * Inserts the submesh in its correct queue depending on its material.
  15142. * @param subMesh The submesh to dispatch
  15143. */
  15144. RenderingGroup.prototype.dispatch = function (subMesh) {
  15145. var material = subMesh.getMaterial();
  15146. var mesh = subMesh.getMesh();
  15147. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15148. this._transparentSubMeshes.push(subMesh);
  15149. }
  15150. else if (material.needAlphaTesting()) {
  15151. this._alphaTestSubMeshes.push(subMesh);
  15152. }
  15153. else {
  15154. this._opaqueSubMeshes.push(subMesh); // Opaque
  15155. }
  15156. if (mesh._edgesRenderer) {
  15157. this._edgesRenderers.push(mesh._edgesRenderer);
  15158. }
  15159. };
  15160. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15161. this._spriteManagers.push(spriteManager);
  15162. };
  15163. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15164. this._particleSystems.push(particleSystem);
  15165. };
  15166. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15167. if (this._particleSystems.length === 0) {
  15168. return;
  15169. }
  15170. // Particles
  15171. var activeCamera = this._scene.activeCamera;
  15172. this._scene._particlesDuration.beginMonitoring();
  15173. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15174. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15175. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15176. continue;
  15177. }
  15178. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15179. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15180. }
  15181. }
  15182. this._scene._particlesDuration.endMonitoring(false);
  15183. };
  15184. RenderingGroup.prototype._renderSprites = function () {
  15185. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15186. return;
  15187. }
  15188. // Sprites
  15189. var activeCamera = this._scene.activeCamera;
  15190. this._scene._spritesDuration.beginMonitoring();
  15191. for (var id = 0; id < this._spriteManagers.length; id++) {
  15192. var spriteManager = this._spriteManagers.data[id];
  15193. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15194. spriteManager.render();
  15195. }
  15196. }
  15197. this._scene._spritesDuration.endMonitoring(false);
  15198. };
  15199. return RenderingGroup;
  15200. }());
  15201. BABYLON.RenderingGroup = RenderingGroup;
  15202. })(BABYLON || (BABYLON = {}));
  15203. //# sourceMappingURL=babylon.renderingGroup.js.map
  15204. var BABYLON;
  15205. (function (BABYLON) {
  15206. var ClickInfo = (function () {
  15207. function ClickInfo() {
  15208. this._singleClick = false;
  15209. this._doubleClick = false;
  15210. this._hasSwiped = false;
  15211. this._ignore = false;
  15212. }
  15213. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15214. get: function () {
  15215. return this._singleClick;
  15216. },
  15217. set: function (b) {
  15218. this._singleClick = b;
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15224. get: function () {
  15225. return this._doubleClick;
  15226. },
  15227. set: function (b) {
  15228. this._doubleClick = b;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15234. get: function () {
  15235. return this._hasSwiped;
  15236. },
  15237. set: function (b) {
  15238. this._hasSwiped = b;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15244. get: function () {
  15245. return this._ignore;
  15246. },
  15247. set: function (b) {
  15248. this._ignore = b;
  15249. },
  15250. enumerable: true,
  15251. configurable: true
  15252. });
  15253. return ClickInfo;
  15254. }());
  15255. var PointerEventTypes = (function () {
  15256. function PointerEventTypes() {
  15257. }
  15258. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15259. get: function () {
  15260. return PointerEventTypes._POINTERDOWN;
  15261. },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15266. get: function () {
  15267. return PointerEventTypes._POINTERUP;
  15268. },
  15269. enumerable: true,
  15270. configurable: true
  15271. });
  15272. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15273. get: function () {
  15274. return PointerEventTypes._POINTERMOVE;
  15275. },
  15276. enumerable: true,
  15277. configurable: true
  15278. });
  15279. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15280. get: function () {
  15281. return PointerEventTypes._POINTERWHEEL;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15287. get: function () {
  15288. return PointerEventTypes._POINTERPICK;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15294. get: function () {
  15295. return PointerEventTypes._POINTERTAP;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15301. get: function () {
  15302. return PointerEventTypes._POINTERDOUBLETAP;
  15303. },
  15304. enumerable: true,
  15305. configurable: true
  15306. });
  15307. return PointerEventTypes;
  15308. }());
  15309. PointerEventTypes._POINTERDOWN = 0x01;
  15310. PointerEventTypes._POINTERUP = 0x02;
  15311. PointerEventTypes._POINTERMOVE = 0x04;
  15312. PointerEventTypes._POINTERWHEEL = 0x08;
  15313. PointerEventTypes._POINTERPICK = 0x10;
  15314. PointerEventTypes._POINTERTAP = 0x20;
  15315. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15316. BABYLON.PointerEventTypes = PointerEventTypes;
  15317. var PointerInfoBase = (function () {
  15318. function PointerInfoBase(type, event) {
  15319. this.type = type;
  15320. this.event = event;
  15321. }
  15322. return PointerInfoBase;
  15323. }());
  15324. BABYLON.PointerInfoBase = PointerInfoBase;
  15325. /**
  15326. * This class is used to store pointer related info for the onPrePointerObservable event.
  15327. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15328. */
  15329. var PointerInfoPre = (function (_super) {
  15330. __extends(PointerInfoPre, _super);
  15331. function PointerInfoPre(type, event, localX, localY) {
  15332. var _this = _super.call(this, type, event) || this;
  15333. _this.skipOnPointerObservable = false;
  15334. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15335. return _this;
  15336. }
  15337. return PointerInfoPre;
  15338. }(PointerInfoBase));
  15339. BABYLON.PointerInfoPre = PointerInfoPre;
  15340. /**
  15341. * This type contains all the data related to a pointer event in Babylon.js.
  15342. * 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.
  15343. */
  15344. var PointerInfo = (function (_super) {
  15345. __extends(PointerInfo, _super);
  15346. function PointerInfo(type, event, pickInfo) {
  15347. var _this = _super.call(this, type, event) || this;
  15348. _this.pickInfo = pickInfo;
  15349. return _this;
  15350. }
  15351. return PointerInfo;
  15352. }(PointerInfoBase));
  15353. BABYLON.PointerInfo = PointerInfo;
  15354. /**
  15355. * This class is used by the onRenderingGroupObservable
  15356. */
  15357. var RenderingGroupInfo = (function () {
  15358. function RenderingGroupInfo() {
  15359. }
  15360. return RenderingGroupInfo;
  15361. }());
  15362. /**
  15363. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15364. * This stage will be fired no matter what
  15365. */
  15366. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15367. /**
  15368. * Called before opaque object are rendered.
  15369. * This stage will be fired only if there's 3D Opaque content to render
  15370. */
  15371. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15372. /**
  15373. * Called after the opaque objects are rendered and before the transparent ones
  15374. * This stage will be fired only if there's 3D transparent content to render
  15375. */
  15376. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15377. /**
  15378. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15379. * This stage will be fired no matter what
  15380. */
  15381. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15382. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15383. /**
  15384. * Represents a scene to be rendered by the engine.
  15385. * @see http://doc.babylonjs.com/page.php?p=21911
  15386. */
  15387. var Scene = (function () {
  15388. /**
  15389. * @constructor
  15390. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15391. */
  15392. function Scene(engine) {
  15393. // Members
  15394. this.autoClear = true;
  15395. this.autoClearDepthAndStencil = true;
  15396. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15397. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15398. this.forceWireframe = false;
  15399. this._forcePointsCloud = false;
  15400. this.forceShowBoundingBoxes = false;
  15401. this.animationsEnabled = true;
  15402. this.constantlyUpdateMeshUnderPointer = false;
  15403. this.hoverCursor = "pointer";
  15404. // Metadata
  15405. this.metadata = null;
  15406. // Events
  15407. /**
  15408. * An event triggered when the scene is disposed.
  15409. * @type {BABYLON.Observable}
  15410. */
  15411. this.onDisposeObservable = new BABYLON.Observable();
  15412. /**
  15413. * An event triggered before rendering the scene
  15414. * @type {BABYLON.Observable}
  15415. */
  15416. this.onBeforeRenderObservable = new BABYLON.Observable();
  15417. /**
  15418. * An event triggered after rendering the scene
  15419. * @type {BABYLON.Observable}
  15420. */
  15421. this.onAfterRenderObservable = new BABYLON.Observable();
  15422. /**
  15423. * An event triggered when the scene is ready
  15424. * @type {BABYLON.Observable}
  15425. */
  15426. this.onReadyObservable = new BABYLON.Observable();
  15427. /**
  15428. * An event triggered before rendering a camera
  15429. * @type {BABYLON.Observable}
  15430. */
  15431. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15432. /**
  15433. * An event triggered after rendering a camera
  15434. * @type {BABYLON.Observable}
  15435. */
  15436. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15437. /**
  15438. * An event triggered when a camera is created
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15442. /**
  15443. * An event triggered when a camera is removed
  15444. * @type {BABYLON.Observable}
  15445. */
  15446. this.onCameraRemovedObservable = new BABYLON.Observable();
  15447. /**
  15448. * An event triggered when a light is created
  15449. * @type {BABYLON.Observable}
  15450. */
  15451. this.onNewLightAddedObservable = new BABYLON.Observable();
  15452. /**
  15453. * An event triggered when a light is removed
  15454. * @type {BABYLON.Observable}
  15455. */
  15456. this.onLightRemovedObservable = new BABYLON.Observable();
  15457. /**
  15458. * An event triggered when a geometry is created
  15459. * @type {BABYLON.Observable}
  15460. */
  15461. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15462. /**
  15463. * An event triggered when a geometry is removed
  15464. * @type {BABYLON.Observable}
  15465. */
  15466. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15467. /**
  15468. * An event triggered when a mesh is created
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15472. /**
  15473. * An event triggered when a mesh is removed
  15474. * @type {BABYLON.Observable}
  15475. */
  15476. this.onMeshRemovedObservable = new BABYLON.Observable();
  15477. /**
  15478. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15479. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15480. * 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)
  15481. */
  15482. this.onRenderingGroupObservable = new BABYLON.Observable();
  15483. // Animations
  15484. this.animations = [];
  15485. /**
  15486. * 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).
  15487. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15488. */
  15489. this.onPrePointerObservable = new BABYLON.Observable();
  15490. /**
  15491. * Observable event triggered each time an input event is received from the rendering canvas
  15492. */
  15493. this.onPointerObservable = new BABYLON.Observable();
  15494. this._meshPickProceed = false;
  15495. this._previousHasSwiped = false;
  15496. this._currentPickResult = null;
  15497. this._previousPickResult = null;
  15498. this._isButtonPressed = false;
  15499. this._doubleClickOccured = false;
  15500. 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
  15501. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15502. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15503. this._startingPointerTime = 0;
  15504. this._previousStartingPointerTime = 0;
  15505. // Coordinate system
  15506. /**
  15507. * use right-handed coordinate system on this scene.
  15508. * @type {boolean}
  15509. */
  15510. this._useRightHandedSystem = false;
  15511. // Fog
  15512. /**
  15513. * is fog enabled on this scene.
  15514. * @type {boolean}
  15515. */
  15516. this._fogEnabled = true;
  15517. this._fogMode = Scene.FOGMODE_NONE;
  15518. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15519. this.fogDensity = 0.1;
  15520. this.fogStart = 0;
  15521. this.fogEnd = 1000.0;
  15522. // Lights
  15523. /**
  15524. * is shadow enabled on this scene.
  15525. * @type {boolean}
  15526. */
  15527. this._shadowsEnabled = true;
  15528. /**
  15529. * is light enabled on this scene.
  15530. * @type {boolean}
  15531. */
  15532. this._lightsEnabled = true;
  15533. /**
  15534. * All of the lights added to this scene.
  15535. * @see BABYLON.Light
  15536. * @type {BABYLON.Light[]}
  15537. */
  15538. this.lights = new Array();
  15539. // Cameras
  15540. /**
  15541. * All of the cameras added to this scene.
  15542. * @see BABYLON.Camera
  15543. * @type {BABYLON.Camera[]}
  15544. */
  15545. this.cameras = new Array();
  15546. this.activeCameras = new Array();
  15547. // Meshes
  15548. /**
  15549. * All of the (abstract) meshes added to this scene.
  15550. * @see BABYLON.AbstractMesh
  15551. * @type {BABYLON.AbstractMesh[]}
  15552. */
  15553. this.meshes = new Array();
  15554. // Geometries
  15555. this._geometries = new Array();
  15556. this.materials = new Array();
  15557. this.multiMaterials = new Array();
  15558. // Textures
  15559. this._texturesEnabled = true;
  15560. this.textures = new Array();
  15561. // Particles
  15562. this.particlesEnabled = true;
  15563. this.particleSystems = new Array();
  15564. // Sprites
  15565. this.spritesEnabled = true;
  15566. this.spriteManagers = new Array();
  15567. // Layers
  15568. this.layers = new Array();
  15569. this.highlightLayers = new Array();
  15570. // Skeletons
  15571. this._skeletonsEnabled = true;
  15572. this.skeletons = new Array();
  15573. // Morph targets
  15574. this.morphTargetManagers = new Array();
  15575. // Lens flares
  15576. this.lensFlaresEnabled = true;
  15577. this.lensFlareSystems = new Array();
  15578. // Collisions
  15579. this.collisionsEnabled = true;
  15580. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15581. // Postprocesses
  15582. this.postProcessesEnabled = true;
  15583. // Customs render targets
  15584. this.renderTargetsEnabled = true;
  15585. this.dumpNextRenderTargets = false;
  15586. this.customRenderTargets = new Array();
  15587. // Imported meshes
  15588. this.importedMeshesFiles = new Array();
  15589. // Probes
  15590. this.probesEnabled = true;
  15591. this.reflectionProbes = new Array();
  15592. this._actionManagers = new Array();
  15593. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15594. // Procedural textures
  15595. this.proceduralTexturesEnabled = true;
  15596. this._proceduralTextures = new Array();
  15597. this.soundTracks = new Array();
  15598. this._audioEnabled = true;
  15599. this._headphone = false;
  15600. // Performance counters
  15601. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15602. this._totalLightsCounter = new BABYLON.PerfCounter();
  15603. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15604. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15605. this._totalVertices = new BABYLON.PerfCounter();
  15606. this._activeIndices = new BABYLON.PerfCounter();
  15607. this._activeParticles = new BABYLON.PerfCounter();
  15608. this._lastFrameDuration = new BABYLON.PerfCounter();
  15609. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15610. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15611. this._particlesDuration = new BABYLON.PerfCounter();
  15612. this._renderDuration = new BABYLON.PerfCounter();
  15613. this._spritesDuration = new BABYLON.PerfCounter();
  15614. this._activeBones = new BABYLON.PerfCounter();
  15615. this._animationTime = 0;
  15616. this.animationTimeScale = 1;
  15617. this._renderId = 0;
  15618. this._executeWhenReadyTimeoutId = -1;
  15619. this._intermediateRendering = false;
  15620. this._viewUpdateFlag = -1;
  15621. this._projectionUpdateFlag = -1;
  15622. this._toBeDisposed = new BABYLON.SmartArray(256);
  15623. this._pendingData = []; //ANY
  15624. this._activeMeshes = new BABYLON.SmartArray(256);
  15625. this._processedMaterials = new BABYLON.SmartArray(256);
  15626. this._renderTargets = new BABYLON.SmartArray(256);
  15627. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15628. this._activeSkeletons = new BABYLON.SmartArray(32);
  15629. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15630. this._activeAnimatables = new Array();
  15631. this._transformMatrix = BABYLON.Matrix.Zero();
  15632. this.requireLightSorting = false;
  15633. this._uniqueIdCounter = 0;
  15634. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15635. this._engine.scenes.push(this);
  15636. this._uid = null;
  15637. this._renderingManager = new BABYLON.RenderingManager(this);
  15638. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15639. if (BABYLON.OutlineRenderer) {
  15640. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15641. }
  15642. this.attachControl();
  15643. if (BABYLON.SoundTrack) {
  15644. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15645. }
  15646. //simplification queue
  15647. if (BABYLON.SimplificationQueue) {
  15648. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15649. }
  15650. //collision coordinator initialization. For now legacy per default.
  15651. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15652. // Uniform Buffer
  15653. this._createUbo();
  15654. // Default Image processing definition.
  15655. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15656. }
  15657. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15658. get: function () {
  15659. return Scene._FOGMODE_NONE;
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15665. get: function () {
  15666. return Scene._FOGMODE_EXP;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15672. get: function () {
  15673. return Scene._FOGMODE_EXP2;
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15679. get: function () {
  15680. return Scene._FOGMODE_LINEAR;
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15686. /**
  15687. * Texture used in all pbr material as the reflection texture.
  15688. * As in the majority of the scene they are the same (exception for multi room and so on),
  15689. * this is easier to reference from here than from all the materials.
  15690. */
  15691. get: function () {
  15692. return this._environmentTexture;
  15693. },
  15694. /**
  15695. * Texture used in all pbr material as the reflection texture.
  15696. * As in the majority of the scene they are the same (exception for multi room and so on),
  15697. * this is easier to set here than in all the materials.
  15698. */
  15699. set: function (value) {
  15700. this._environmentTexture = value;
  15701. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15702. },
  15703. enumerable: true,
  15704. configurable: true
  15705. });
  15706. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15707. /**
  15708. * Default image processing configuration used either in the rendering
  15709. * Forward main pass or through the imageProcessingPostProcess if present.
  15710. * As in the majority of the scene they are the same (exception for multi camera),
  15711. * this is easier to reference from here than from all the materials and post process.
  15712. *
  15713. * No setter as we it is a shared configuration, you can set the values instead.
  15714. */
  15715. get: function () {
  15716. return this._imageProcessingConfiguration;
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15722. get: function () {
  15723. return this._forcePointsCloud;
  15724. },
  15725. set: function (value) {
  15726. if (this._forcePointsCloud === value) {
  15727. return;
  15728. }
  15729. this._forcePointsCloud = value;
  15730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Scene.prototype, "onDispose", {
  15736. set: function (callback) {
  15737. if (this._onDisposeObserver) {
  15738. this.onDisposeObservable.remove(this._onDisposeObserver);
  15739. }
  15740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(Scene.prototype, "beforeRender", {
  15746. set: function (callback) {
  15747. if (this._onBeforeRenderObserver) {
  15748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15749. }
  15750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Scene.prototype, "afterRender", {
  15756. set: function (callback) {
  15757. if (this._onAfterRenderObserver) {
  15758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15759. }
  15760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15766. set: function (callback) {
  15767. if (this._onBeforeCameraRenderObserver) {
  15768. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15769. }
  15770. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15776. set: function (callback) {
  15777. if (this._onAfterCameraRenderObserver) {
  15778. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15779. }
  15780. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15786. get: function () {
  15787. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15793. get: function () {
  15794. return this._useRightHandedSystem;
  15795. },
  15796. set: function (value) {
  15797. if (this._useRightHandedSystem === value) {
  15798. return;
  15799. }
  15800. this._useRightHandedSystem = value;
  15801. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15807. get: function () {
  15808. return this._fogEnabled;
  15809. },
  15810. set: function (value) {
  15811. if (this._fogEnabled === value) {
  15812. return;
  15813. }
  15814. this._fogEnabled = value;
  15815. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Scene.prototype, "fogMode", {
  15821. get: function () {
  15822. return this._fogMode;
  15823. },
  15824. set: function (value) {
  15825. if (this._fogMode === value) {
  15826. return;
  15827. }
  15828. this._fogMode = value;
  15829. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15835. get: function () {
  15836. return this._shadowsEnabled;
  15837. },
  15838. set: function (value) {
  15839. if (this._shadowsEnabled === value) {
  15840. return;
  15841. }
  15842. this._shadowsEnabled = value;
  15843. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15849. get: function () {
  15850. return this._lightsEnabled;
  15851. },
  15852. set: function (value) {
  15853. if (this._lightsEnabled === value) {
  15854. return;
  15855. }
  15856. this._lightsEnabled = value;
  15857. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15863. get: function () {
  15864. if (!this._defaultMaterial) {
  15865. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15866. }
  15867. return this._defaultMaterial;
  15868. },
  15869. set: function (value) {
  15870. this._defaultMaterial = value;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15876. get: function () {
  15877. return this._texturesEnabled;
  15878. },
  15879. set: function (value) {
  15880. if (this._texturesEnabled === value) {
  15881. return;
  15882. }
  15883. this._texturesEnabled = value;
  15884. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15885. },
  15886. enumerable: true,
  15887. configurable: true
  15888. });
  15889. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15890. get: function () {
  15891. return this._skeletonsEnabled;
  15892. },
  15893. set: function (value) {
  15894. if (this._skeletonsEnabled === value) {
  15895. return;
  15896. }
  15897. this._skeletonsEnabled = value;
  15898. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15904. get: function () {
  15905. if (!this._postProcessRenderPipelineManager) {
  15906. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15907. }
  15908. return this._postProcessRenderPipelineManager;
  15909. },
  15910. enumerable: true,
  15911. configurable: true
  15912. });
  15913. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15914. get: function () {
  15915. return this._frustumPlanes;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(Scene.prototype, "debugLayer", {
  15921. // Properties
  15922. get: function () {
  15923. if (!this._debugLayer) {
  15924. this._debugLayer = new BABYLON.DebugLayer(this);
  15925. }
  15926. return this._debugLayer;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15932. get: function () {
  15933. return this._workerCollisions;
  15934. },
  15935. set: function (enabled) {
  15936. if (!BABYLON.CollisionCoordinatorLegacy) {
  15937. return;
  15938. }
  15939. enabled = (enabled && !!Worker);
  15940. this._workerCollisions = enabled;
  15941. if (this.collisionCoordinator) {
  15942. this.collisionCoordinator.destroy();
  15943. }
  15944. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15945. this.collisionCoordinator.init(this);
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15951. get: function () {
  15952. return this._selectionOctree;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15958. /**
  15959. * The mesh that is currently under the pointer.
  15960. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15961. */
  15962. get: function () {
  15963. return this._pointerOverMesh;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(Scene.prototype, "pointerX", {
  15969. /**
  15970. * Current on-screen X position of the pointer
  15971. * @return {number} X position of the pointer
  15972. */
  15973. get: function () {
  15974. return this._pointerX;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(Scene.prototype, "pointerY", {
  15980. /**
  15981. * Current on-screen Y position of the pointer
  15982. * @return {number} Y position of the pointer
  15983. */
  15984. get: function () {
  15985. return this._pointerY;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Scene.prototype.getCachedMaterial = function () {
  15991. return this._cachedMaterial;
  15992. };
  15993. Scene.prototype.getCachedEffect = function () {
  15994. return this._cachedEffect;
  15995. };
  15996. Scene.prototype.getCachedVisibility = function () {
  15997. return this._cachedVisibility;
  15998. };
  15999. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16000. if (visibility === void 0) { visibility = 0; }
  16001. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16002. };
  16003. Scene.prototype.getBoundingBoxRenderer = function () {
  16004. if (!this._boundingBoxRenderer) {
  16005. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16006. }
  16007. return this._boundingBoxRenderer;
  16008. };
  16009. Scene.prototype.getOutlineRenderer = function () {
  16010. return this._outlineRenderer;
  16011. };
  16012. Scene.prototype.getEngine = function () {
  16013. return this._engine;
  16014. };
  16015. Scene.prototype.getTotalVertices = function () {
  16016. return this._totalVertices.current;
  16017. };
  16018. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16019. get: function () {
  16020. return this._totalVertices;
  16021. },
  16022. enumerable: true,
  16023. configurable: true
  16024. });
  16025. Scene.prototype.getActiveIndices = function () {
  16026. return this._activeIndices.current;
  16027. };
  16028. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16029. get: function () {
  16030. return this._activeIndices;
  16031. },
  16032. enumerable: true,
  16033. configurable: true
  16034. });
  16035. Scene.prototype.getActiveParticles = function () {
  16036. return this._activeParticles.current;
  16037. };
  16038. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16039. get: function () {
  16040. return this._activeParticles;
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. Scene.prototype.getActiveBones = function () {
  16046. return this._activeBones.current;
  16047. };
  16048. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16049. get: function () {
  16050. return this._activeBones;
  16051. },
  16052. enumerable: true,
  16053. configurable: true
  16054. });
  16055. // Stats
  16056. Scene.prototype.getLastFrameDuration = function () {
  16057. return this._lastFrameDuration.current;
  16058. };
  16059. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16060. get: function () {
  16061. return this._lastFrameDuration;
  16062. },
  16063. enumerable: true,
  16064. configurable: true
  16065. });
  16066. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16067. return this._evaluateActiveMeshesDuration.current;
  16068. };
  16069. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16070. get: function () {
  16071. return this._evaluateActiveMeshesDuration;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Scene.prototype.getActiveMeshes = function () {
  16077. return this._activeMeshes;
  16078. };
  16079. Scene.prototype.getRenderTargetsDuration = function () {
  16080. return this._renderTargetsDuration.current;
  16081. };
  16082. Scene.prototype.getRenderDuration = function () {
  16083. return this._renderDuration.current;
  16084. };
  16085. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16086. get: function () {
  16087. return this._renderDuration;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Scene.prototype.getParticlesDuration = function () {
  16093. return this._particlesDuration.current;
  16094. };
  16095. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16096. get: function () {
  16097. return this._particlesDuration;
  16098. },
  16099. enumerable: true,
  16100. configurable: true
  16101. });
  16102. Scene.prototype.getSpritesDuration = function () {
  16103. return this._spritesDuration.current;
  16104. };
  16105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16106. get: function () {
  16107. return this._spritesDuration;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Scene.prototype.getAnimationRatio = function () {
  16113. return this._animationRatio;
  16114. };
  16115. Scene.prototype.getRenderId = function () {
  16116. return this._renderId;
  16117. };
  16118. Scene.prototype.incrementRenderId = function () {
  16119. this._renderId++;
  16120. };
  16121. Scene.prototype._updatePointerPosition = function (evt) {
  16122. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16123. this._pointerX = evt.clientX - canvasRect.left;
  16124. this._pointerY = evt.clientY - canvasRect.top;
  16125. this._unTranslatedPointerX = this._pointerX;
  16126. this._unTranslatedPointerY = this._pointerY;
  16127. if (this.cameraToUseForPointers) {
  16128. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16129. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16130. }
  16131. };
  16132. Scene.prototype._createUbo = function () {
  16133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16134. this._sceneUbo.addUniform("viewProjection", 16);
  16135. this._sceneUbo.addUniform("view", 16);
  16136. };
  16137. // Pointers handling
  16138. /**
  16139. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16140. * @param attachUp defines if you want to attach events to pointerup
  16141. * @param attachDown defines if you want to attach events to pointerdown
  16142. * @param attachMove defines if you want to attach events to pointermove
  16143. */
  16144. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16145. var _this = this;
  16146. if (attachUp === void 0) { attachUp = true; }
  16147. if (attachDown === void 0) { attachDown = true; }
  16148. if (attachMove === void 0) { attachMove = true; }
  16149. this._initActionManager = function (act, clickInfo) {
  16150. if (!_this._meshPickProceed) {
  16151. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16152. _this._currentPickResult = pickResult;
  16153. if (pickResult) {
  16154. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16155. }
  16156. _this._meshPickProceed = true;
  16157. }
  16158. return act;
  16159. };
  16160. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16161. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16162. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16163. btn !== _this._previousButtonPressed) {
  16164. _this._doubleClickOccured = false;
  16165. clickInfo.singleClick = true;
  16166. clickInfo.ignore = false;
  16167. cb(clickInfo, _this._currentPickResult);
  16168. }
  16169. };
  16170. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16171. var clickInfo = new ClickInfo();
  16172. _this._currentPickResult = null;
  16173. var act;
  16174. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16175. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16176. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16177. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16178. act = _this._initActionManager(act, clickInfo);
  16179. if (act)
  16180. checkPicking = act.hasPickTriggers;
  16181. }
  16182. if (checkPicking) {
  16183. var btn = evt.button;
  16184. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16185. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16186. if (!clickInfo.hasSwiped) {
  16187. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16188. if (!checkSingleClickImmediately) {
  16189. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16190. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16191. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16192. act = _this._initActionManager(act, clickInfo);
  16193. if (act)
  16194. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16195. }
  16196. }
  16197. if (checkSingleClickImmediately) {
  16198. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16199. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16200. btn !== _this._previousButtonPressed) {
  16201. clickInfo.singleClick = true;
  16202. cb(clickInfo, _this._currentPickResult);
  16203. }
  16204. }
  16205. else {
  16206. // wait that no double click has been raised during the double click delay
  16207. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16208. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16209. }
  16210. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16211. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16212. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16213. act = _this._initActionManager(act, clickInfo);
  16214. if (act)
  16215. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16216. }
  16217. if (checkDoubleClick) {
  16218. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16219. if (btn === _this._previousButtonPressed &&
  16220. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16221. !_this._doubleClickOccured) {
  16222. // pointer has not moved for 2 clicks, it's a double click
  16223. if (!clickInfo.hasSwiped &&
  16224. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16225. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16226. _this._previousStartingPointerTime = 0;
  16227. _this._doubleClickOccured = true;
  16228. clickInfo.doubleClick = true;
  16229. clickInfo.ignore = false;
  16230. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16231. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16232. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16233. cb(clickInfo, _this._currentPickResult);
  16234. }
  16235. else {
  16236. _this._doubleClickOccured = false;
  16237. _this._previousStartingPointerTime = _this._startingPointerTime;
  16238. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16239. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16240. _this._previousButtonPressed = btn;
  16241. _this._previousHasSwiped = clickInfo.hasSwiped;
  16242. if (Scene.ExclusiveDoubleClickMode) {
  16243. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16244. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16245. }
  16246. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16247. cb(clickInfo, _this._previousPickResult);
  16248. }
  16249. else {
  16250. cb(clickInfo, _this._currentPickResult);
  16251. }
  16252. }
  16253. }
  16254. else {
  16255. _this._doubleClickOccured = false;
  16256. _this._previousStartingPointerTime = _this._startingPointerTime;
  16257. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16258. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16259. _this._previousButtonPressed = btn;
  16260. _this._previousHasSwiped = clickInfo.hasSwiped;
  16261. }
  16262. }
  16263. }
  16264. }
  16265. clickInfo.ignore = true;
  16266. cb(clickInfo, _this._currentPickResult);
  16267. };
  16268. var spritePredicate = function (sprite) {
  16269. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16270. };
  16271. this._onPointerMove = function (evt) {
  16272. _this._updatePointerPosition(evt);
  16273. // PreObservable support
  16274. if (_this.onPrePointerObservable.hasObservers()) {
  16275. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16276. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16277. _this.onPrePointerObservable.notifyObservers(pi, type);
  16278. if (pi.skipOnPointerObservable) {
  16279. return;
  16280. }
  16281. }
  16282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16283. return;
  16284. }
  16285. var canvas = _this._engine.getRenderingCanvas();
  16286. if (!_this.pointerMovePredicate) {
  16287. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16288. }
  16289. // Meshes
  16290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16291. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16292. _this.setPointerOverSprite(null);
  16293. _this.setPointerOverMesh(pickResult.pickedMesh);
  16294. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16295. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16296. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16297. }
  16298. else {
  16299. canvas.style.cursor = _this.hoverCursor;
  16300. }
  16301. }
  16302. else {
  16303. canvas.style.cursor = "";
  16304. }
  16305. }
  16306. else {
  16307. _this.setPointerOverMesh(null);
  16308. // Sprites
  16309. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16310. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16311. _this.setPointerOverSprite(pickResult.pickedSprite);
  16312. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16313. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16314. }
  16315. else {
  16316. canvas.style.cursor = _this.hoverCursor;
  16317. }
  16318. }
  16319. else {
  16320. _this.setPointerOverSprite(null);
  16321. // Restore pointer
  16322. canvas.style.cursor = "";
  16323. }
  16324. }
  16325. if (_this.onPointerMove) {
  16326. _this.onPointerMove(evt, pickResult);
  16327. }
  16328. if (_this.onPointerObservable.hasObservers()) {
  16329. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16330. var pi = new PointerInfo(type, evt, pickResult);
  16331. _this.onPointerObservable.notifyObservers(pi, type);
  16332. }
  16333. };
  16334. this._onPointerDown = function (evt) {
  16335. _this._isButtonPressed = true;
  16336. _this._pickedDownMesh = null;
  16337. _this._meshPickProceed = false;
  16338. _this._updatePointerPosition(evt);
  16339. // PreObservable support
  16340. if (_this.onPrePointerObservable.hasObservers()) {
  16341. var type = PointerEventTypes.POINTERDOWN;
  16342. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16343. _this.onPrePointerObservable.notifyObservers(pi, type);
  16344. if (pi.skipOnPointerObservable) {
  16345. return;
  16346. }
  16347. }
  16348. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16349. return;
  16350. }
  16351. _this._startingPointerPosition.x = _this._pointerX;
  16352. _this._startingPointerPosition.y = _this._pointerY;
  16353. _this._startingPointerTime = new Date().getTime();
  16354. if (!_this.pointerDownPredicate) {
  16355. _this.pointerDownPredicate = function (mesh) {
  16356. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16357. };
  16358. }
  16359. // Meshes
  16360. _this._pickedDownMesh = null;
  16361. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16362. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16363. _this._pickedDownMesh = pickResult.pickedMesh;
  16364. var actionManager = pickResult.pickedMesh.actionManager;
  16365. if (actionManager) {
  16366. if (actionManager.hasPickTriggers) {
  16367. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16368. switch (evt.button) {
  16369. case 0:
  16370. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16371. break;
  16372. case 1:
  16373. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16374. break;
  16375. case 2:
  16376. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16377. break;
  16378. }
  16379. }
  16380. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16381. window.setTimeout((function () {
  16382. var _this = this;
  16383. 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);
  16384. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16385. if (this._isButtonPressed &&
  16386. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16387. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16388. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16389. this._startingPointerTime = 0;
  16390. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16391. }
  16392. }
  16393. }).bind(_this), Scene.LongPressDelay);
  16394. }
  16395. }
  16396. }
  16397. if (_this.onPointerDown) {
  16398. _this.onPointerDown(evt, pickResult);
  16399. }
  16400. if (_this.onPointerObservable.hasObservers()) {
  16401. var type = PointerEventTypes.POINTERDOWN;
  16402. var pi = new PointerInfo(type, evt, pickResult);
  16403. _this.onPointerObservable.notifyObservers(pi, type);
  16404. }
  16405. // Sprites
  16406. _this._pickedDownSprite = null;
  16407. if (_this.spriteManagers.length > 0) {
  16408. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16409. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16410. if (pickResult.pickedSprite.actionManager) {
  16411. _this._pickedDownSprite = pickResult.pickedSprite;
  16412. switch (evt.button) {
  16413. case 0:
  16414. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16415. break;
  16416. case 1:
  16417. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16418. break;
  16419. case 2:
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16421. break;
  16422. }
  16423. if (pickResult.pickedSprite.actionManager) {
  16424. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16425. }
  16426. }
  16427. }
  16428. }
  16429. };
  16430. this._onPointerUp = function (evt) {
  16431. _this._isButtonPressed = false;
  16432. _this._pickedUpMesh = null;
  16433. _this._meshPickProceed = false;
  16434. _this._updatePointerPosition(evt);
  16435. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16436. // PreObservable support
  16437. if (this.onPrePointerObservable.hasObservers()) {
  16438. if (!clickInfo.ignore) {
  16439. if (!clickInfo.hasSwiped) {
  16440. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16441. var type = PointerEventTypes.POINTERTAP;
  16442. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16443. this.onPrePointerObservable.notifyObservers(pi, type);
  16444. if (pi.skipOnPointerObservable) {
  16445. return;
  16446. }
  16447. }
  16448. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16449. var type = PointerEventTypes.POINTERDOUBLETAP;
  16450. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16451. this.onPrePointerObservable.notifyObservers(pi, type);
  16452. if (pi.skipOnPointerObservable) {
  16453. return;
  16454. }
  16455. }
  16456. }
  16457. }
  16458. else {
  16459. var type = PointerEventTypes.POINTERUP;
  16460. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16461. this.onPrePointerObservable.notifyObservers(pi, type);
  16462. if (pi.skipOnPointerObservable) {
  16463. return;
  16464. }
  16465. }
  16466. }
  16467. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16468. return;
  16469. }
  16470. if (!this.pointerUpPredicate) {
  16471. this.pointerUpPredicate = function (mesh) {
  16472. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16473. };
  16474. }
  16475. // Meshes
  16476. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16477. this._initActionManager(null, clickInfo);
  16478. }
  16479. if (!pickResult) {
  16480. pickResult = this._currentPickResult;
  16481. }
  16482. if (pickResult && pickResult && pickResult.pickedMesh) {
  16483. this._pickedUpMesh = pickResult.pickedMesh;
  16484. if (this._pickedDownMesh === this._pickedUpMesh) {
  16485. if (this.onPointerPick) {
  16486. this.onPointerPick(evt, pickResult);
  16487. }
  16488. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16489. var type = PointerEventTypes.POINTERPICK;
  16490. var pi = new PointerInfo(type, evt, pickResult);
  16491. this.onPointerObservable.notifyObservers(pi, type);
  16492. }
  16493. }
  16494. if (pickResult.pickedMesh.actionManager) {
  16495. if (clickInfo.ignore) {
  16496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16497. }
  16498. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16500. }
  16501. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16502. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16503. }
  16504. }
  16505. }
  16506. if (this._pickedDownMesh &&
  16507. this._pickedDownMesh.actionManager &&
  16508. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16509. this._pickedDownMesh !== this._pickedUpMesh) {
  16510. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16511. }
  16512. if (this.onPointerUp) {
  16513. this.onPointerUp(evt, pickResult);
  16514. }
  16515. if (this.onPointerObservable.hasObservers()) {
  16516. if (!clickInfo.ignore) {
  16517. if (!clickInfo.hasSwiped) {
  16518. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16519. var type = PointerEventTypes.POINTERTAP;
  16520. var pi = new PointerInfo(type, evt, pickResult);
  16521. this.onPointerObservable.notifyObservers(pi, type);
  16522. }
  16523. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16524. var type = PointerEventTypes.POINTERDOUBLETAP;
  16525. var pi = new PointerInfo(type, evt, pickResult);
  16526. this.onPointerObservable.notifyObservers(pi, type);
  16527. }
  16528. }
  16529. }
  16530. else {
  16531. var type = PointerEventTypes.POINTERUP;
  16532. var pi = new PointerInfo(type, evt, pickResult);
  16533. this.onPointerObservable.notifyObservers(pi, type);
  16534. }
  16535. }
  16536. // Sprites
  16537. if (this.spriteManagers.length > 0) {
  16538. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16539. if (pickResult.hit && pickResult.pickedSprite) {
  16540. if (pickResult.pickedSprite.actionManager) {
  16541. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16542. if (pickResult.pickedSprite.actionManager) {
  16543. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16544. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16545. }
  16546. }
  16547. }
  16548. }
  16549. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16550. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16551. }
  16552. }
  16553. this._previousPickResult = this._currentPickResult;
  16554. }).bind(_this));
  16555. };
  16556. this._onKeyDown = function (evt) {
  16557. if (_this.actionManager) {
  16558. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16559. }
  16560. };
  16561. this._onKeyUp = function (evt) {
  16562. if (_this.actionManager) {
  16563. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16564. }
  16565. };
  16566. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16567. var canvas = this._engine.getRenderingCanvas();
  16568. if (attachMove) {
  16569. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16570. // Wheel
  16571. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16572. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16573. }
  16574. if (attachDown) {
  16575. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16576. }
  16577. if (attachUp) {
  16578. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16579. }
  16580. canvas.tabIndex = 1;
  16581. canvas.addEventListener("keydown", this._onKeyDown, false);
  16582. canvas.addEventListener("keyup", this._onKeyUp, false);
  16583. };
  16584. Scene.prototype.detachControl = function () {
  16585. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16586. var canvas = this._engine.getRenderingCanvas();
  16587. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16588. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16589. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16590. // Wheel
  16591. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16592. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16593. canvas.removeEventListener("keydown", this._onKeyDown);
  16594. canvas.removeEventListener("keyup", this._onKeyUp);
  16595. };
  16596. // Ready
  16597. Scene.prototype.isReady = function () {
  16598. if (this._pendingData.length > 0) {
  16599. return false;
  16600. }
  16601. var index;
  16602. // Geometries
  16603. for (index = 0; index < this._geometries.length; index++) {
  16604. var geometry = this._geometries[index];
  16605. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16606. return false;
  16607. }
  16608. }
  16609. // Meshes
  16610. for (index = 0; index < this.meshes.length; index++) {
  16611. var mesh = this.meshes[index];
  16612. if (!mesh.isEnabled()) {
  16613. continue;
  16614. }
  16615. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16616. continue;
  16617. }
  16618. if (!mesh.isReady()) {
  16619. return false;
  16620. }
  16621. var mat = mesh.material;
  16622. if (mat) {
  16623. if (!mat.isReady(mesh)) {
  16624. return false;
  16625. }
  16626. }
  16627. }
  16628. return true;
  16629. };
  16630. Scene.prototype.resetCachedMaterial = function () {
  16631. this._cachedMaterial = null;
  16632. this._cachedEffect = null;
  16633. this._cachedVisibility = null;
  16634. };
  16635. Scene.prototype.registerBeforeRender = function (func) {
  16636. this.onBeforeRenderObservable.add(func);
  16637. };
  16638. Scene.prototype.unregisterBeforeRender = function (func) {
  16639. this.onBeforeRenderObservable.removeCallback(func);
  16640. };
  16641. Scene.prototype.registerAfterRender = function (func) {
  16642. this.onAfterRenderObservable.add(func);
  16643. };
  16644. Scene.prototype.unregisterAfterRender = function (func) {
  16645. this.onAfterRenderObservable.removeCallback(func);
  16646. };
  16647. Scene.prototype._addPendingData = function (data) {
  16648. this._pendingData.push(data);
  16649. };
  16650. Scene.prototype._removePendingData = function (data) {
  16651. var index = this._pendingData.indexOf(data);
  16652. if (index !== -1) {
  16653. this._pendingData.splice(index, 1);
  16654. }
  16655. };
  16656. Scene.prototype.getWaitingItemsCount = function () {
  16657. return this._pendingData.length;
  16658. };
  16659. /**
  16660. * Registers a function to be executed when the scene is ready.
  16661. * @param {Function} func - the function to be executed.
  16662. */
  16663. Scene.prototype.executeWhenReady = function (func) {
  16664. var _this = this;
  16665. this.onReadyObservable.add(func);
  16666. if (this._executeWhenReadyTimeoutId !== -1) {
  16667. return;
  16668. }
  16669. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16670. _this._checkIsReady();
  16671. }, 150);
  16672. };
  16673. Scene.prototype._checkIsReady = function () {
  16674. var _this = this;
  16675. if (this.isReady()) {
  16676. this.onReadyObservable.notifyObservers(this);
  16677. this.onReadyObservable.clear();
  16678. this._executeWhenReadyTimeoutId = -1;
  16679. return;
  16680. }
  16681. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16682. _this._checkIsReady();
  16683. }, 150);
  16684. };
  16685. // Animations
  16686. /**
  16687. * Will start the animation sequence of a given target
  16688. * @param target - the target
  16689. * @param {number} from - from which frame should animation start
  16690. * @param {number} to - till which frame should animation run.
  16691. * @param {boolean} [loop] - should the animation loop
  16692. * @param {number} [speedRatio] - the speed in which to run the animation
  16693. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16694. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16695. * @return {BABYLON.Animatable} the animatable object created for this animation
  16696. * @see BABYLON.Animatable
  16697. * @see http://doc.babylonjs.com/page.php?p=22081
  16698. */
  16699. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16700. if (speedRatio === void 0) { speedRatio = 1.0; }
  16701. if (from > to && speedRatio > 0) {
  16702. speedRatio *= -1;
  16703. }
  16704. this.stopAnimation(target);
  16705. if (!animatable) {
  16706. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16707. }
  16708. // Local animations
  16709. if (target.animations) {
  16710. animatable.appendAnimations(target, target.animations);
  16711. }
  16712. // Children animations
  16713. if (target.getAnimatables) {
  16714. var animatables = target.getAnimatables();
  16715. for (var index = 0; index < animatables.length; index++) {
  16716. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16717. }
  16718. }
  16719. animatable.reset();
  16720. return animatable;
  16721. };
  16722. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16723. if (speedRatio === undefined) {
  16724. speedRatio = 1.0;
  16725. }
  16726. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16727. return animatable;
  16728. };
  16729. Scene.prototype.getAnimatableByTarget = function (target) {
  16730. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16731. if (this._activeAnimatables[index].target === target) {
  16732. return this._activeAnimatables[index];
  16733. }
  16734. }
  16735. return null;
  16736. };
  16737. Object.defineProperty(Scene.prototype, "Animatables", {
  16738. get: function () {
  16739. return this._activeAnimatables;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. /**
  16745. * Will stop the animation of the given target
  16746. * @param target - the target
  16747. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16748. * @see beginAnimation
  16749. */
  16750. Scene.prototype.stopAnimation = function (target, animationName) {
  16751. var animatable = this.getAnimatableByTarget(target);
  16752. if (animatable) {
  16753. animatable.stop(animationName);
  16754. }
  16755. };
  16756. Scene.prototype._animate = function () {
  16757. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16758. return;
  16759. }
  16760. // Getting time
  16761. var now = BABYLON.Tools.Now;
  16762. if (!this._animationTimeLast) {
  16763. if (this._pendingData.length > 0) {
  16764. return;
  16765. }
  16766. this._animationTimeLast = now;
  16767. }
  16768. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16769. this._animationTime += deltaTime;
  16770. this._animationTimeLast = now;
  16771. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16772. this._activeAnimatables[index]._animate(this._animationTime);
  16773. }
  16774. };
  16775. // Matrix
  16776. Scene.prototype.getViewMatrix = function () {
  16777. return this._viewMatrix;
  16778. };
  16779. Scene.prototype.getProjectionMatrix = function () {
  16780. return this._projectionMatrix;
  16781. };
  16782. Scene.prototype.getTransformMatrix = function () {
  16783. return this._transformMatrix;
  16784. };
  16785. Scene.prototype.setTransformMatrix = function (view, projection) {
  16786. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16787. return;
  16788. }
  16789. this._viewUpdateFlag = view.updateFlag;
  16790. this._projectionUpdateFlag = projection.updateFlag;
  16791. this._viewMatrix = view;
  16792. this._projectionMatrix = projection;
  16793. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16794. // Update frustum
  16795. if (!this._frustumPlanes) {
  16796. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16797. }
  16798. else {
  16799. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16800. }
  16801. if (this._sceneUbo.useUbo) {
  16802. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16803. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16804. this._sceneUbo.update();
  16805. }
  16806. };
  16807. Scene.prototype.getSceneUniformBuffer = function () {
  16808. return this._sceneUbo;
  16809. };
  16810. // Methods
  16811. Scene.prototype.getUniqueId = function () {
  16812. var result = this._uniqueIdCounter;
  16813. this._uniqueIdCounter++;
  16814. return result;
  16815. };
  16816. Scene.prototype.addMesh = function (newMesh) {
  16817. newMesh.uniqueId = this.getUniqueId();
  16818. var position = this.meshes.push(newMesh);
  16819. //notify the collision coordinator
  16820. if (this.collisionCoordinator) {
  16821. this.collisionCoordinator.onMeshAdded(newMesh);
  16822. }
  16823. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16824. };
  16825. Scene.prototype.removeMesh = function (toRemove) {
  16826. var index = this.meshes.indexOf(toRemove);
  16827. if (index !== -1) {
  16828. // Remove from the scene if mesh found
  16829. this.meshes.splice(index, 1);
  16830. }
  16831. //notify the collision coordinator
  16832. if (this.collisionCoordinator) {
  16833. this.collisionCoordinator.onMeshRemoved(toRemove);
  16834. }
  16835. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16836. return index;
  16837. };
  16838. Scene.prototype.removeSkeleton = function (toRemove) {
  16839. var index = this.skeletons.indexOf(toRemove);
  16840. if (index !== -1) {
  16841. // Remove from the scene if found
  16842. this.skeletons.splice(index, 1);
  16843. }
  16844. return index;
  16845. };
  16846. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16847. var index = this.morphTargetManagers.indexOf(toRemove);
  16848. if (index !== -1) {
  16849. // Remove from the scene if found
  16850. this.morphTargetManagers.splice(index, 1);
  16851. }
  16852. return index;
  16853. };
  16854. Scene.prototype.removeLight = function (toRemove) {
  16855. var index = this.lights.indexOf(toRemove);
  16856. if (index !== -1) {
  16857. // Remove from the scene if mesh found
  16858. this.lights.splice(index, 1);
  16859. this.sortLightsByPriority();
  16860. }
  16861. this.onLightRemovedObservable.notifyObservers(toRemove);
  16862. return index;
  16863. };
  16864. Scene.prototype.removeCamera = function (toRemove) {
  16865. var index = this.cameras.indexOf(toRemove);
  16866. if (index !== -1) {
  16867. // Remove from the scene if mesh found
  16868. this.cameras.splice(index, 1);
  16869. }
  16870. // Remove from activeCameras
  16871. var index2 = this.activeCameras.indexOf(toRemove);
  16872. if (index2 !== -1) {
  16873. // Remove from the scene if mesh found
  16874. this.activeCameras.splice(index2, 1);
  16875. }
  16876. // Reset the activeCamera
  16877. if (this.activeCamera === toRemove) {
  16878. if (this.cameras.length > 0) {
  16879. this.activeCamera = this.cameras[0];
  16880. }
  16881. else {
  16882. this.activeCamera = null;
  16883. }
  16884. }
  16885. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16886. return index;
  16887. };
  16888. Scene.prototype.addLight = function (newLight) {
  16889. newLight.uniqueId = this.getUniqueId();
  16890. this.lights.push(newLight);
  16891. this.sortLightsByPriority();
  16892. this.onNewLightAddedObservable.notifyObservers(newLight);
  16893. };
  16894. Scene.prototype.sortLightsByPriority = function () {
  16895. if (this.requireLightSorting) {
  16896. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16897. }
  16898. };
  16899. Scene.prototype.addCamera = function (newCamera) {
  16900. newCamera.uniqueId = this.getUniqueId();
  16901. var position = this.cameras.push(newCamera);
  16902. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16903. };
  16904. /**
  16905. * Switch active camera
  16906. * @param {Camera} newCamera - new active camera
  16907. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16908. */
  16909. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16910. if (attachControl === void 0) { attachControl = true; }
  16911. var canvas = this._engine.getRenderingCanvas();
  16912. this.activeCamera.detachControl(canvas);
  16913. this.activeCamera = newCamera;
  16914. if (attachControl) {
  16915. newCamera.attachControl(canvas);
  16916. }
  16917. };
  16918. /**
  16919. * sets the active camera of the scene using its ID
  16920. * @param {string} id - the camera's ID
  16921. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16922. * @see activeCamera
  16923. */
  16924. Scene.prototype.setActiveCameraByID = function (id) {
  16925. var camera = this.getCameraByID(id);
  16926. if (camera) {
  16927. this.activeCamera = camera;
  16928. return camera;
  16929. }
  16930. return null;
  16931. };
  16932. /**
  16933. * sets the active camera of the scene using its name
  16934. * @param {string} name - the camera's name
  16935. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16936. * @see activeCamera
  16937. */
  16938. Scene.prototype.setActiveCameraByName = function (name) {
  16939. var camera = this.getCameraByName(name);
  16940. if (camera) {
  16941. this.activeCamera = camera;
  16942. return camera;
  16943. }
  16944. return null;
  16945. };
  16946. /**
  16947. * get a material using its id
  16948. * @param {string} the material's ID
  16949. * @return {BABYLON.Material|null} the material or null if none found.
  16950. */
  16951. Scene.prototype.getMaterialByID = function (id) {
  16952. for (var index = 0; index < this.materials.length; index++) {
  16953. if (this.materials[index].id === id) {
  16954. return this.materials[index];
  16955. }
  16956. }
  16957. return null;
  16958. };
  16959. /**
  16960. * get a material using its name
  16961. * @param {string} the material's name
  16962. * @return {BABYLON.Material|null} the material or null if none found.
  16963. */
  16964. Scene.prototype.getMaterialByName = function (name) {
  16965. for (var index = 0; index < this.materials.length; index++) {
  16966. if (this.materials[index].name === name) {
  16967. return this.materials[index];
  16968. }
  16969. }
  16970. return null;
  16971. };
  16972. Scene.prototype.getLensFlareSystemByName = function (name) {
  16973. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16974. if (this.lensFlareSystems[index].name === name) {
  16975. return this.lensFlareSystems[index];
  16976. }
  16977. }
  16978. return null;
  16979. };
  16980. Scene.prototype.getLensFlareSystemByID = function (id) {
  16981. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16982. if (this.lensFlareSystems[index].id === id) {
  16983. return this.lensFlareSystems[index];
  16984. }
  16985. }
  16986. return null;
  16987. };
  16988. Scene.prototype.getCameraByID = function (id) {
  16989. for (var index = 0; index < this.cameras.length; index++) {
  16990. if (this.cameras[index].id === id) {
  16991. return this.cameras[index];
  16992. }
  16993. }
  16994. return null;
  16995. };
  16996. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16997. for (var index = 0; index < this.cameras.length; index++) {
  16998. if (this.cameras[index].uniqueId === uniqueId) {
  16999. return this.cameras[index];
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * get a camera using its name
  17006. * @param {string} the camera's name
  17007. * @return {BABYLON.Camera|null} the camera or null if none found.
  17008. */
  17009. Scene.prototype.getCameraByName = function (name) {
  17010. for (var index = 0; index < this.cameras.length; index++) {
  17011. if (this.cameras[index].name === name) {
  17012. return this.cameras[index];
  17013. }
  17014. }
  17015. return null;
  17016. };
  17017. /**
  17018. * get a bone using its id
  17019. * @param {string} the bone's id
  17020. * @return {BABYLON.Bone|null} the bone or null if not found
  17021. */
  17022. Scene.prototype.getBoneByID = function (id) {
  17023. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17024. var skeleton = this.skeletons[skeletonIndex];
  17025. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17026. if (skeleton.bones[boneIndex].id === id) {
  17027. return skeleton.bones[boneIndex];
  17028. }
  17029. }
  17030. }
  17031. return null;
  17032. };
  17033. /**
  17034. * get a bone using its id
  17035. * @param {string} the bone's name
  17036. * @return {BABYLON.Bone|null} the bone or null if not found
  17037. */
  17038. Scene.prototype.getBoneByName = function (name) {
  17039. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17040. var skeleton = this.skeletons[skeletonIndex];
  17041. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17042. if (skeleton.bones[boneIndex].name === name) {
  17043. return skeleton.bones[boneIndex];
  17044. }
  17045. }
  17046. }
  17047. return null;
  17048. };
  17049. /**
  17050. * get a light node using its name
  17051. * @param {string} the light's name
  17052. * @return {BABYLON.Light|null} the light or null if none found.
  17053. */
  17054. Scene.prototype.getLightByName = function (name) {
  17055. for (var index = 0; index < this.lights.length; index++) {
  17056. if (this.lights[index].name === name) {
  17057. return this.lights[index];
  17058. }
  17059. }
  17060. return null;
  17061. };
  17062. /**
  17063. * get a light node using its ID
  17064. * @param {string} the light's id
  17065. * @return {BABYLON.Light|null} the light or null if none found.
  17066. */
  17067. Scene.prototype.getLightByID = function (id) {
  17068. for (var index = 0; index < this.lights.length; index++) {
  17069. if (this.lights[index].id === id) {
  17070. return this.lights[index];
  17071. }
  17072. }
  17073. return null;
  17074. };
  17075. /**
  17076. * get a light node using its scene-generated unique ID
  17077. * @param {number} the light's unique id
  17078. * @return {BABYLON.Light|null} the light or null if none found.
  17079. */
  17080. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17081. for (var index = 0; index < this.lights.length; index++) {
  17082. if (this.lights[index].uniqueId === uniqueId) {
  17083. return this.lights[index];
  17084. }
  17085. }
  17086. return null;
  17087. };
  17088. /**
  17089. * get a particle system by id
  17090. * @param id {number} the particle system id
  17091. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17092. */
  17093. Scene.prototype.getParticleSystemByID = function (id) {
  17094. for (var index = 0; index < this.particleSystems.length; index++) {
  17095. if (this.particleSystems[index].id === id) {
  17096. return this.particleSystems[index];
  17097. }
  17098. }
  17099. return null;
  17100. };
  17101. /**
  17102. * get a geometry using its ID
  17103. * @param {string} the geometry's id
  17104. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17105. */
  17106. Scene.prototype.getGeometryByID = function (id) {
  17107. for (var index = 0; index < this._geometries.length; index++) {
  17108. if (this._geometries[index].id === id) {
  17109. return this._geometries[index];
  17110. }
  17111. }
  17112. return null;
  17113. };
  17114. /**
  17115. * add a new geometry to this scene.
  17116. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17117. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17118. * @return {boolean} was the geometry added or not
  17119. */
  17120. Scene.prototype.pushGeometry = function (geometry, force) {
  17121. if (!force && this.getGeometryByID(geometry.id)) {
  17122. return false;
  17123. }
  17124. this._geometries.push(geometry);
  17125. //notify the collision coordinator
  17126. if (this.collisionCoordinator) {
  17127. this.collisionCoordinator.onGeometryAdded(geometry);
  17128. }
  17129. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17130. return true;
  17131. };
  17132. /**
  17133. * Removes an existing geometry
  17134. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17135. * @return {boolean} was the geometry removed or not
  17136. */
  17137. Scene.prototype.removeGeometry = function (geometry) {
  17138. var index = this._geometries.indexOf(geometry);
  17139. if (index > -1) {
  17140. this._geometries.splice(index, 1);
  17141. //notify the collision coordinator
  17142. if (this.collisionCoordinator) {
  17143. this.collisionCoordinator.onGeometryDeleted(geometry);
  17144. }
  17145. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17146. return true;
  17147. }
  17148. return false;
  17149. };
  17150. Scene.prototype.getGeometries = function () {
  17151. return this._geometries;
  17152. };
  17153. /**
  17154. * Get the first added mesh found of a given ID
  17155. * @param {string} id - the id to search for
  17156. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17157. */
  17158. Scene.prototype.getMeshByID = function (id) {
  17159. for (var index = 0; index < this.meshes.length; index++) {
  17160. if (this.meshes[index].id === id) {
  17161. return this.meshes[index];
  17162. }
  17163. }
  17164. return null;
  17165. };
  17166. Scene.prototype.getMeshesByID = function (id) {
  17167. return this.meshes.filter(function (m) {
  17168. return m.id === id;
  17169. });
  17170. };
  17171. /**
  17172. * Get a mesh with its auto-generated unique id
  17173. * @param {number} uniqueId - the unique id to search for
  17174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17175. */
  17176. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17177. for (var index = 0; index < this.meshes.length; index++) {
  17178. if (this.meshes[index].uniqueId === uniqueId) {
  17179. return this.meshes[index];
  17180. }
  17181. }
  17182. return null;
  17183. };
  17184. /**
  17185. * Get a the last added mesh found of a given ID
  17186. * @param {string} id - the id to search for
  17187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17188. */
  17189. Scene.prototype.getLastMeshByID = function (id) {
  17190. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17191. if (this.meshes[index].id === id) {
  17192. return this.meshes[index];
  17193. }
  17194. }
  17195. return null;
  17196. };
  17197. /**
  17198. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17199. * @param {string} id - the id to search for
  17200. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17201. */
  17202. Scene.prototype.getLastEntryByID = function (id) {
  17203. var index;
  17204. for (index = this.meshes.length - 1; index >= 0; index--) {
  17205. if (this.meshes[index].id === id) {
  17206. return this.meshes[index];
  17207. }
  17208. }
  17209. for (index = this.cameras.length - 1; index >= 0; index--) {
  17210. if (this.cameras[index].id === id) {
  17211. return this.cameras[index];
  17212. }
  17213. }
  17214. for (index = this.lights.length - 1; index >= 0; index--) {
  17215. if (this.lights[index].id === id) {
  17216. return this.lights[index];
  17217. }
  17218. }
  17219. return null;
  17220. };
  17221. Scene.prototype.getNodeByID = function (id) {
  17222. var mesh = this.getMeshByID(id);
  17223. if (mesh) {
  17224. return mesh;
  17225. }
  17226. var light = this.getLightByID(id);
  17227. if (light) {
  17228. return light;
  17229. }
  17230. var camera = this.getCameraByID(id);
  17231. if (camera) {
  17232. return camera;
  17233. }
  17234. var bone = this.getBoneByID(id);
  17235. return bone;
  17236. };
  17237. Scene.prototype.getNodeByName = function (name) {
  17238. var mesh = this.getMeshByName(name);
  17239. if (mesh) {
  17240. return mesh;
  17241. }
  17242. var light = this.getLightByName(name);
  17243. if (light) {
  17244. return light;
  17245. }
  17246. var camera = this.getCameraByName(name);
  17247. if (camera) {
  17248. return camera;
  17249. }
  17250. var bone = this.getBoneByName(name);
  17251. return bone;
  17252. };
  17253. Scene.prototype.getMeshByName = function (name) {
  17254. for (var index = 0; index < this.meshes.length; index++) {
  17255. if (this.meshes[index].name === name) {
  17256. return this.meshes[index];
  17257. }
  17258. }
  17259. return null;
  17260. };
  17261. Scene.prototype.getSoundByName = function (name) {
  17262. var index;
  17263. if (BABYLON.AudioEngine) {
  17264. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17265. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17266. return this.mainSoundTrack.soundCollection[index];
  17267. }
  17268. }
  17269. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17270. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17271. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17272. return this.soundTracks[sdIndex].soundCollection[index];
  17273. }
  17274. }
  17275. }
  17276. }
  17277. return null;
  17278. };
  17279. Scene.prototype.getLastSkeletonByID = function (id) {
  17280. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17281. if (this.skeletons[index].id === id) {
  17282. return this.skeletons[index];
  17283. }
  17284. }
  17285. return null;
  17286. };
  17287. Scene.prototype.getSkeletonById = function (id) {
  17288. for (var index = 0; index < this.skeletons.length; index++) {
  17289. if (this.skeletons[index].id === id) {
  17290. return this.skeletons[index];
  17291. }
  17292. }
  17293. return null;
  17294. };
  17295. Scene.prototype.getSkeletonByName = function (name) {
  17296. for (var index = 0; index < this.skeletons.length; index++) {
  17297. if (this.skeletons[index].name === name) {
  17298. return this.skeletons[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. Scene.prototype.getMorphTargetManagerById = function (id) {
  17304. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17305. if (this.morphTargetManagers[index].uniqueId === id) {
  17306. return this.morphTargetManagers[index];
  17307. }
  17308. }
  17309. return null;
  17310. };
  17311. Scene.prototype.isActiveMesh = function (mesh) {
  17312. return (this._activeMeshes.indexOf(mesh) !== -1);
  17313. };
  17314. /**
  17315. * Return a the first highlight layer of the scene with a given name.
  17316. * @param name The name of the highlight layer to look for.
  17317. * @return The highlight layer if found otherwise null.
  17318. */
  17319. Scene.prototype.getHighlightLayerByName = function (name) {
  17320. for (var index = 0; index < this.highlightLayers.length; index++) {
  17321. if (this.highlightLayers[index].name === name) {
  17322. return this.highlightLayers[index];
  17323. }
  17324. }
  17325. return null;
  17326. };
  17327. Object.defineProperty(Scene.prototype, "uid", {
  17328. /**
  17329. * Return a unique id as a string which can serve as an identifier for the scene
  17330. */
  17331. get: function () {
  17332. if (!this._uid) {
  17333. this._uid = BABYLON.Tools.RandomId();
  17334. }
  17335. return this._uid;
  17336. },
  17337. enumerable: true,
  17338. configurable: true
  17339. });
  17340. /**
  17341. * Add an externaly attached data from its key.
  17342. * This method call will fail and return false, if such key already exists.
  17343. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17344. * @param key the unique key that identifies the data
  17345. * @param data the data object to associate to the key for this Engine instance
  17346. * @return true if no such key were already present and the data was added successfully, false otherwise
  17347. */
  17348. Scene.prototype.addExternalData = function (key, data) {
  17349. if (!this._externalData) {
  17350. this._externalData = new BABYLON.StringDictionary();
  17351. }
  17352. return this._externalData.add(key, data);
  17353. };
  17354. /**
  17355. * Get an externaly attached data from its key
  17356. * @param key the unique key that identifies the data
  17357. * @return the associated data, if present (can be null), or undefined if not present
  17358. */
  17359. Scene.prototype.getExternalData = function (key) {
  17360. if (!this._externalData) {
  17361. return null;
  17362. }
  17363. return this._externalData.get(key);
  17364. };
  17365. /**
  17366. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17367. * @param key the unique key that identifies the data
  17368. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17369. * @return the associated data, can be null if the factory returned null.
  17370. */
  17371. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17372. if (!this._externalData) {
  17373. this._externalData = new BABYLON.StringDictionary();
  17374. }
  17375. return this._externalData.getOrAddWithFactory(key, factory);
  17376. };
  17377. /**
  17378. * Remove an externaly attached data from the Engine instance
  17379. * @param key the unique key that identifies the data
  17380. * @return true if the data was successfully removed, false if it doesn't exist
  17381. */
  17382. Scene.prototype.removeExternalData = function (key) {
  17383. return this._externalData.remove(key);
  17384. };
  17385. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17386. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17387. var material = subMesh.getMaterial();
  17388. if (mesh.showSubMeshesBoundingBox) {
  17389. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17390. }
  17391. if (material) {
  17392. // Render targets
  17393. if (material.getRenderTargetTextures) {
  17394. if (this._processedMaterials.indexOf(material) === -1) {
  17395. this._processedMaterials.push(material);
  17396. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17397. }
  17398. }
  17399. // Dispatch
  17400. this._activeIndices.addCount(subMesh.indexCount, false);
  17401. this._renderingManager.dispatch(subMesh);
  17402. }
  17403. }
  17404. };
  17405. Scene.prototype._isInIntermediateRendering = function () {
  17406. return this._intermediateRendering;
  17407. };
  17408. Scene.prototype._evaluateActiveMeshes = function () {
  17409. this.activeCamera._activeMeshes.reset();
  17410. this._activeMeshes.reset();
  17411. this._renderingManager.reset();
  17412. this._processedMaterials.reset();
  17413. this._activeParticleSystems.reset();
  17414. this._activeSkeletons.reset();
  17415. this._softwareSkinnedMeshes.reset();
  17416. if (this._boundingBoxRenderer) {
  17417. this._boundingBoxRenderer.reset();
  17418. }
  17419. // Meshes
  17420. var meshes;
  17421. var len;
  17422. if (this._selectionOctree) {
  17423. var selection = this._selectionOctree.select(this._frustumPlanes);
  17424. meshes = selection.data;
  17425. len = selection.length;
  17426. }
  17427. else {
  17428. len = this.meshes.length;
  17429. meshes = this.meshes;
  17430. }
  17431. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17432. var mesh = meshes[meshIndex];
  17433. if (mesh.isBlocked) {
  17434. continue;
  17435. }
  17436. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17437. if (!mesh.isReady() || !mesh.isEnabled()) {
  17438. continue;
  17439. }
  17440. mesh.computeWorldMatrix();
  17441. // Intersections
  17442. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17443. this._meshesForIntersections.pushNoDuplicate(mesh);
  17444. }
  17445. // Switch to current LOD
  17446. var meshLOD = mesh.getLOD(this.activeCamera);
  17447. if (!meshLOD) {
  17448. continue;
  17449. }
  17450. mesh._preActivate();
  17451. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17452. this._activeMeshes.push(mesh);
  17453. this.activeCamera._activeMeshes.push(mesh);
  17454. mesh._activate(this._renderId);
  17455. this._activeMesh(mesh, meshLOD);
  17456. }
  17457. }
  17458. // Particle systems
  17459. this._particlesDuration.beginMonitoring();
  17460. var beforeParticlesDate = BABYLON.Tools.Now;
  17461. if (this.particlesEnabled) {
  17462. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17463. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17464. var particleSystem = this.particleSystems[particleIndex];
  17465. if (!particleSystem.isStarted()) {
  17466. continue;
  17467. }
  17468. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17469. this._activeParticleSystems.push(particleSystem);
  17470. particleSystem.animate();
  17471. this._renderingManager.dispatchParticles(particleSystem);
  17472. }
  17473. }
  17474. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17475. }
  17476. this._particlesDuration.endMonitoring(false);
  17477. };
  17478. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17479. if (mesh.skeleton && this.skeletonsEnabled) {
  17480. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17481. mesh.skeleton.prepare();
  17482. }
  17483. if (!mesh.computeBonesUsingShaders) {
  17484. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17485. }
  17486. }
  17487. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17488. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17489. }
  17490. if (mesh && mesh.subMeshes) {
  17491. // Submeshes Octrees
  17492. var len;
  17493. var subMeshes;
  17494. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17495. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17496. len = intersections.length;
  17497. subMeshes = intersections.data;
  17498. }
  17499. else {
  17500. subMeshes = mesh.subMeshes;
  17501. len = subMeshes.length;
  17502. }
  17503. for (var subIndex = 0; subIndex < len; subIndex++) {
  17504. var subMesh = subMeshes[subIndex];
  17505. this._evaluateSubMesh(subMesh, mesh);
  17506. }
  17507. }
  17508. };
  17509. Scene.prototype.updateTransformMatrix = function (force) {
  17510. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17511. };
  17512. Scene.prototype._renderForCamera = function (camera) {
  17513. var engine = this._engine;
  17514. var startTime = BABYLON.Tools.Now;
  17515. this.activeCamera = camera;
  17516. if (!this.activeCamera)
  17517. throw new Error("Active camera not set");
  17518. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17519. // Viewport
  17520. engine.setViewport(this.activeCamera.viewport);
  17521. // Camera
  17522. this.resetCachedMaterial();
  17523. this._renderId++;
  17524. this.updateTransformMatrix();
  17525. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17526. // Meshes
  17527. this._evaluateActiveMeshesDuration.beginMonitoring();
  17528. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17529. this._evaluateActiveMeshes();
  17530. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17531. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17532. // Software skinning
  17533. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17534. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17535. mesh.applySkeleton(mesh.skeleton);
  17536. }
  17537. // Render targets
  17538. this._renderTargetsDuration.beginMonitoring();
  17539. var needsRestoreFrameBuffer = false;
  17540. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17541. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17542. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17543. }
  17544. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17545. this._intermediateRendering = true;
  17546. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17547. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17548. var renderTarget = this._renderTargets.data[renderIndex];
  17549. if (renderTarget._shouldRender()) {
  17550. this._renderId++;
  17551. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17552. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17553. }
  17554. }
  17555. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17556. this._intermediateRendering = false;
  17557. this._renderId++;
  17558. needsRestoreFrameBuffer = true; // Restore back buffer
  17559. }
  17560. // Render HighlightLayer Texture
  17561. var stencilState = this._engine.getStencilBuffer();
  17562. var renderhighlights = false;
  17563. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17564. this._intermediateRendering = true;
  17565. for (var i = 0; i < this.highlightLayers.length; i++) {
  17566. var highlightLayer = this.highlightLayers[i];
  17567. if (highlightLayer.shouldRender() &&
  17568. (!highlightLayer.camera ||
  17569. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17570. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17571. renderhighlights = true;
  17572. var renderTarget = highlightLayer._mainTexture;
  17573. if (renderTarget._shouldRender()) {
  17574. this._renderId++;
  17575. renderTarget.render(false, false);
  17576. needsRestoreFrameBuffer = true;
  17577. }
  17578. }
  17579. }
  17580. this._intermediateRendering = false;
  17581. this._renderId++;
  17582. }
  17583. if (needsRestoreFrameBuffer) {
  17584. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17585. }
  17586. this._renderTargetsDuration.endMonitoring(false);
  17587. // Prepare Frame
  17588. this.postProcessManager._prepareFrame();
  17589. this._renderDuration.beginMonitoring();
  17590. // Backgrounds
  17591. var layerIndex;
  17592. var layer;
  17593. if (this.layers.length) {
  17594. engine.setDepthBuffer(false);
  17595. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17596. layer = this.layers[layerIndex];
  17597. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17598. layer.render();
  17599. }
  17600. }
  17601. engine.setDepthBuffer(true);
  17602. }
  17603. // Render
  17604. BABYLON.Tools.StartPerformanceCounter("Main render");
  17605. // Activate HighlightLayer stencil
  17606. if (renderhighlights) {
  17607. this._engine.setStencilBuffer(true);
  17608. }
  17609. this._renderingManager.render(null, null, true, true);
  17610. // Restore HighlightLayer stencil
  17611. if (renderhighlights) {
  17612. this._engine.setStencilBuffer(stencilState);
  17613. }
  17614. BABYLON.Tools.EndPerformanceCounter("Main render");
  17615. // Bounding boxes
  17616. if (this._boundingBoxRenderer) {
  17617. this._boundingBoxRenderer.render();
  17618. }
  17619. // Lens flares
  17620. if (this.lensFlaresEnabled) {
  17621. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17622. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17623. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17624. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17625. lensFlareSystem.render();
  17626. }
  17627. }
  17628. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17629. }
  17630. // Foregrounds
  17631. if (this.layers.length) {
  17632. engine.setDepthBuffer(false);
  17633. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17634. layer = this.layers[layerIndex];
  17635. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17636. layer.render();
  17637. }
  17638. }
  17639. engine.setDepthBuffer(true);
  17640. }
  17641. // Highlight Layer
  17642. if (renderhighlights) {
  17643. engine.setDepthBuffer(false);
  17644. for (var i = 0; i < this.highlightLayers.length; i++) {
  17645. if (this.highlightLayers[i].shouldRender()) {
  17646. this.highlightLayers[i].render();
  17647. }
  17648. }
  17649. engine.setDepthBuffer(true);
  17650. }
  17651. this._renderDuration.endMonitoring(false);
  17652. // Finalize frame
  17653. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17654. // Update camera
  17655. this.activeCamera._updateFromScene();
  17656. // Reset some special arrays
  17657. this._renderTargets.reset();
  17658. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17659. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17660. };
  17661. Scene.prototype._processSubCameras = function (camera) {
  17662. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17663. this._renderForCamera(camera);
  17664. return;
  17665. }
  17666. // rig cameras
  17667. for (var index = 0; index < camera._rigCameras.length; index++) {
  17668. this._renderForCamera(camera._rigCameras[index]);
  17669. }
  17670. this.activeCamera = camera;
  17671. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17672. // Update camera
  17673. this.activeCamera._updateFromScene();
  17674. };
  17675. Scene.prototype._checkIntersections = function () {
  17676. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17677. var sourceMesh = this._meshesForIntersections.data[index];
  17678. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17679. var action = sourceMesh.actionManager.actions[actionIndex];
  17680. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17681. var parameters = action.getTriggerParameter();
  17682. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17683. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17684. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17685. if (areIntersecting && currentIntersectionInProgress === -1) {
  17686. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17687. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17688. sourceMesh._intersectionsInProgress.push(otherMesh);
  17689. }
  17690. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17691. sourceMesh._intersectionsInProgress.push(otherMesh);
  17692. }
  17693. }
  17694. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17695. //They intersected, and now they don't.
  17696. //is this trigger an exit trigger? execute an event.
  17697. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17699. }
  17700. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17701. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17702. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17703. }
  17704. }
  17705. }
  17706. }
  17707. }
  17708. };
  17709. Scene.prototype.render = function () {
  17710. if (this.isDisposed) {
  17711. return;
  17712. }
  17713. this._lastFrameDuration.beginMonitoring();
  17714. this._particlesDuration.fetchNewFrame();
  17715. this._spritesDuration.fetchNewFrame();
  17716. this._activeParticles.fetchNewFrame();
  17717. this._renderDuration.fetchNewFrame();
  17718. this._renderTargetsDuration.fetchNewFrame();
  17719. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17720. this._totalVertices.fetchNewFrame();
  17721. this._activeIndices.fetchNewFrame();
  17722. this._activeBones.fetchNewFrame();
  17723. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17724. this._meshesForIntersections.reset();
  17725. this.resetCachedMaterial();
  17726. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17727. // Actions
  17728. if (this.actionManager) {
  17729. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17730. }
  17731. //Simplification Queue
  17732. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17733. this.simplificationQueue.executeNext();
  17734. }
  17735. // Animations
  17736. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17737. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17738. this._animate();
  17739. // Physics
  17740. if (this._physicsEngine) {
  17741. BABYLON.Tools.StartPerformanceCounter("Physics");
  17742. this._physicsEngine._step(deltaTime / 1000.0);
  17743. BABYLON.Tools.EndPerformanceCounter("Physics");
  17744. }
  17745. // Before render
  17746. this.onBeforeRenderObservable.notifyObservers(this);
  17747. // Customs render targets
  17748. this._renderTargetsDuration.beginMonitoring();
  17749. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17750. var engine = this.getEngine();
  17751. var currentActiveCamera = this.activeCamera;
  17752. if (this.renderTargetsEnabled) {
  17753. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17754. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17755. var renderTarget = this.customRenderTargets[customIndex];
  17756. if (renderTarget._shouldRender()) {
  17757. this._renderId++;
  17758. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17759. if (!this.activeCamera)
  17760. throw new Error("Active camera not set");
  17761. // Viewport
  17762. engine.setViewport(this.activeCamera.viewport);
  17763. // Camera
  17764. this.updateTransformMatrix();
  17765. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17766. }
  17767. }
  17768. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17769. this._renderId++;
  17770. }
  17771. // Restore back buffer
  17772. if (this.customRenderTargets.length > 0) {
  17773. engine.restoreDefaultFramebuffer();
  17774. }
  17775. this._renderTargetsDuration.endMonitoring();
  17776. this.activeCamera = currentActiveCamera;
  17777. // Procedural textures
  17778. if (this.proceduralTexturesEnabled) {
  17779. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17780. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17781. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17782. if (proceduralTexture._shouldRender()) {
  17783. proceduralTexture.render();
  17784. }
  17785. }
  17786. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17787. }
  17788. // Clear
  17789. if (this.autoClearDepthAndStencil || this.autoClear) {
  17790. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17791. }
  17792. // Shadows
  17793. if (this.shadowsEnabled) {
  17794. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17795. var light = this.lights[lightIndex];
  17796. var shadowGenerator = light.getShadowGenerator();
  17797. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17798. var shadowMap = shadowGenerator.getShadowMap();
  17799. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17800. this._renderTargets.push(shadowMap);
  17801. }
  17802. }
  17803. }
  17804. }
  17805. // Depth renderer
  17806. if (this._depthRenderer) {
  17807. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17808. }
  17809. // Geometry renderer
  17810. if (this._geometryBufferRenderer) {
  17811. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17812. }
  17813. // RenderPipeline
  17814. if (this._postProcessRenderPipelineManager) {
  17815. this._postProcessRenderPipelineManager.update();
  17816. }
  17817. // Multi-cameras?
  17818. if (this.activeCameras.length > 0) {
  17819. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17820. if (cameraIndex > 0) {
  17821. this._engine.clear(null, false, true, true);
  17822. }
  17823. this._processSubCameras(this.activeCameras[cameraIndex]);
  17824. }
  17825. }
  17826. else {
  17827. if (!this.activeCamera) {
  17828. throw new Error("No camera defined");
  17829. }
  17830. this._processSubCameras(this.activeCamera);
  17831. }
  17832. // Intersection checks
  17833. this._checkIntersections();
  17834. // Update the audio listener attached to the camera
  17835. if (BABYLON.AudioEngine) {
  17836. this._updateAudioParameters();
  17837. }
  17838. // After render
  17839. if (this.afterRender) {
  17840. this.afterRender();
  17841. }
  17842. this.onAfterRenderObservable.notifyObservers(this);
  17843. // Cleaning
  17844. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17845. this._toBeDisposed.data[index].dispose();
  17846. this._toBeDisposed[index] = null;
  17847. }
  17848. this._toBeDisposed.reset();
  17849. if (this.dumpNextRenderTargets) {
  17850. this.dumpNextRenderTargets = false;
  17851. }
  17852. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17853. this._lastFrameDuration.endMonitoring();
  17854. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17855. this._totalLightsCounter.addCount(this.lights.length, true);
  17856. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17857. this._totalTexturesCounter.addCount(this.textures.length, true);
  17858. this._activeBones.addCount(0, true);
  17859. this._activeIndices.addCount(0, true);
  17860. this._activeParticles.addCount(0, true);
  17861. };
  17862. Scene.prototype._updateAudioParameters = function () {
  17863. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17864. return;
  17865. }
  17866. var listeningCamera;
  17867. var audioEngine = BABYLON.Engine.audioEngine;
  17868. if (this.activeCameras.length > 0) {
  17869. listeningCamera = this.activeCameras[0];
  17870. }
  17871. else {
  17872. listeningCamera = this.activeCamera;
  17873. }
  17874. if (listeningCamera && audioEngine.canUseWebAudio) {
  17875. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17876. // for VR cameras
  17877. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17878. listeningCamera = listeningCamera.rigCameras[0];
  17879. }
  17880. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17881. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17882. cameraDirection.normalize();
  17883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17884. var i;
  17885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17886. var sound = this.mainSoundTrack.soundCollection[i];
  17887. if (sound.useCustomAttenuation) {
  17888. sound.updateDistanceFromListener();
  17889. }
  17890. }
  17891. for (i = 0; i < this.soundTracks.length; i++) {
  17892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17893. sound = this.soundTracks[i].soundCollection[j];
  17894. if (sound.useCustomAttenuation) {
  17895. sound.updateDistanceFromListener();
  17896. }
  17897. }
  17898. }
  17899. }
  17900. };
  17901. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17902. // Audio
  17903. get: function () {
  17904. return this._audioEnabled;
  17905. },
  17906. set: function (value) {
  17907. this._audioEnabled = value;
  17908. if (BABYLON.AudioEngine) {
  17909. if (this._audioEnabled) {
  17910. this._enableAudio();
  17911. }
  17912. else {
  17913. this._disableAudio();
  17914. }
  17915. }
  17916. },
  17917. enumerable: true,
  17918. configurable: true
  17919. });
  17920. Scene.prototype._disableAudio = function () {
  17921. var i;
  17922. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17923. this.mainSoundTrack.soundCollection[i].pause();
  17924. }
  17925. for (i = 0; i < this.soundTracks.length; i++) {
  17926. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17927. this.soundTracks[i].soundCollection[j].pause();
  17928. }
  17929. }
  17930. };
  17931. Scene.prototype._enableAudio = function () {
  17932. var i;
  17933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17934. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17935. this.mainSoundTrack.soundCollection[i].play();
  17936. }
  17937. }
  17938. for (i = 0; i < this.soundTracks.length; i++) {
  17939. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17940. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17941. this.soundTracks[i].soundCollection[j].play();
  17942. }
  17943. }
  17944. }
  17945. };
  17946. Object.defineProperty(Scene.prototype, "headphone", {
  17947. get: function () {
  17948. return this._headphone;
  17949. },
  17950. set: function (value) {
  17951. this._headphone = value;
  17952. if (BABYLON.AudioEngine) {
  17953. if (this._headphone) {
  17954. this._switchAudioModeForHeadphones();
  17955. }
  17956. else {
  17957. this._switchAudioModeForNormalSpeakers();
  17958. }
  17959. }
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Scene.prototype._switchAudioModeForHeadphones = function () {
  17965. this.mainSoundTrack.switchPanningModelToHRTF();
  17966. for (var i = 0; i < this.soundTracks.length; i++) {
  17967. this.soundTracks[i].switchPanningModelToHRTF();
  17968. }
  17969. };
  17970. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17971. this.mainSoundTrack.switchPanningModelToEqualPower();
  17972. for (var i = 0; i < this.soundTracks.length; i++) {
  17973. this.soundTracks[i].switchPanningModelToEqualPower();
  17974. }
  17975. };
  17976. Scene.prototype.enableDepthRenderer = function () {
  17977. if (this._depthRenderer) {
  17978. return this._depthRenderer;
  17979. }
  17980. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17981. return this._depthRenderer;
  17982. };
  17983. Scene.prototype.disableDepthRenderer = function () {
  17984. if (!this._depthRenderer) {
  17985. return;
  17986. }
  17987. this._depthRenderer.dispose();
  17988. this._depthRenderer = null;
  17989. };
  17990. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17991. if (ratio === void 0) { ratio = 1; }
  17992. if (this._geometryBufferRenderer) {
  17993. return this._geometryBufferRenderer;
  17994. }
  17995. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17996. if (!this._geometryBufferRenderer.isSupported) {
  17997. this._geometryBufferRenderer = null;
  17998. }
  17999. return this._geometryBufferRenderer;
  18000. };
  18001. Scene.prototype.disableGeometryBufferRenderer = function () {
  18002. if (!this._geometryBufferRenderer) {
  18003. return;
  18004. }
  18005. this._geometryBufferRenderer.dispose();
  18006. this._geometryBufferRenderer = null;
  18007. };
  18008. Scene.prototype.freezeMaterials = function () {
  18009. for (var i = 0; i < this.materials.length; i++) {
  18010. this.materials[i].freeze();
  18011. }
  18012. };
  18013. Scene.prototype.unfreezeMaterials = function () {
  18014. for (var i = 0; i < this.materials.length; i++) {
  18015. this.materials[i].unfreeze();
  18016. }
  18017. };
  18018. Scene.prototype.dispose = function () {
  18019. this.beforeRender = null;
  18020. this.afterRender = null;
  18021. this.skeletons = [];
  18022. this.morphTargetManagers = [];
  18023. this.importedMeshesFiles = new Array();
  18024. if (this._depthRenderer) {
  18025. this._depthRenderer.dispose();
  18026. }
  18027. // Smart arrays
  18028. if (this.activeCamera) {
  18029. this.activeCamera._activeMeshes.dispose();
  18030. this.activeCamera = null;
  18031. }
  18032. this._activeMeshes.dispose();
  18033. this._renderingManager.dispose();
  18034. this._processedMaterials.dispose();
  18035. this._activeParticleSystems.dispose();
  18036. this._activeSkeletons.dispose();
  18037. this._softwareSkinnedMeshes.dispose();
  18038. if (this._boundingBoxRenderer) {
  18039. this._boundingBoxRenderer.dispose();
  18040. }
  18041. this._meshesForIntersections.dispose();
  18042. this._toBeDisposed.dispose();
  18043. // Debug layer
  18044. if (this._debugLayer) {
  18045. this._debugLayer.hide();
  18046. }
  18047. // Events
  18048. this.onDisposeObservable.notifyObservers(this);
  18049. this.onDisposeObservable.clear();
  18050. this.onBeforeRenderObservable.clear();
  18051. this.onAfterRenderObservable.clear();
  18052. this.detachControl();
  18053. // Release sounds & sounds tracks
  18054. if (BABYLON.AudioEngine) {
  18055. this.disposeSounds();
  18056. }
  18057. // Detach cameras
  18058. var canvas = this._engine.getRenderingCanvas();
  18059. var index;
  18060. for (index = 0; index < this.cameras.length; index++) {
  18061. this.cameras[index].detachControl(canvas);
  18062. }
  18063. // Release lights
  18064. while (this.lights.length) {
  18065. this.lights[0].dispose();
  18066. }
  18067. // Release meshes
  18068. while (this.meshes.length) {
  18069. this.meshes[0].dispose(true);
  18070. }
  18071. // Release cameras
  18072. while (this.cameras.length) {
  18073. this.cameras[0].dispose();
  18074. }
  18075. // Release materials
  18076. while (this.materials.length) {
  18077. this.materials[0].dispose();
  18078. }
  18079. // Release particles
  18080. while (this.particleSystems.length) {
  18081. this.particleSystems[0].dispose();
  18082. }
  18083. // Release sprites
  18084. while (this.spriteManagers.length) {
  18085. this.spriteManagers[0].dispose();
  18086. }
  18087. // Release layers
  18088. while (this.layers.length) {
  18089. this.layers[0].dispose();
  18090. }
  18091. while (this.highlightLayers.length) {
  18092. this.highlightLayers[0].dispose();
  18093. }
  18094. // Release textures
  18095. while (this.textures.length) {
  18096. this.textures[0].dispose();
  18097. }
  18098. // Release UBO
  18099. this._sceneUbo.dispose();
  18100. // Post-processes
  18101. this.postProcessManager.dispose();
  18102. // Physics
  18103. if (this._physicsEngine) {
  18104. this.disablePhysicsEngine();
  18105. }
  18106. // Remove from engine
  18107. index = this._engine.scenes.indexOf(this);
  18108. if (index > -1) {
  18109. this._engine.scenes.splice(index, 1);
  18110. }
  18111. this._engine.wipeCaches();
  18112. this._engine = null;
  18113. };
  18114. Object.defineProperty(Scene.prototype, "isDisposed", {
  18115. get: function () {
  18116. return !this._engine;
  18117. },
  18118. enumerable: true,
  18119. configurable: true
  18120. });
  18121. // Release sounds & sounds tracks
  18122. Scene.prototype.disposeSounds = function () {
  18123. this.mainSoundTrack.dispose();
  18124. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18125. this.soundTracks[scIndex].dispose();
  18126. }
  18127. };
  18128. // Octrees
  18129. Scene.prototype.getWorldExtends = function () {
  18130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18132. for (var index = 0; index < this.meshes.length; index++) {
  18133. var mesh = this.meshes[index];
  18134. mesh.computeWorldMatrix(true);
  18135. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18136. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18137. BABYLON.Tools.CheckExtends(minBox, min, max);
  18138. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18139. }
  18140. return {
  18141. min: min,
  18142. max: max
  18143. };
  18144. };
  18145. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18146. if (maxCapacity === void 0) { maxCapacity = 64; }
  18147. if (maxDepth === void 0) { maxDepth = 2; }
  18148. if (!this._selectionOctree) {
  18149. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18150. }
  18151. var worldExtends = this.getWorldExtends();
  18152. // Update octree
  18153. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18154. return this._selectionOctree;
  18155. };
  18156. // Picking
  18157. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18158. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18159. var engine = this._engine;
  18160. if (!camera) {
  18161. if (!this.activeCamera)
  18162. throw new Error("Active camera not set");
  18163. camera = this.activeCamera;
  18164. }
  18165. var cameraViewport = camera.viewport;
  18166. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18167. // Moving coordinates to local viewport world
  18168. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18169. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18170. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18171. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18172. };
  18173. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18174. if (!BABYLON.PickingInfo) {
  18175. return null;
  18176. }
  18177. var engine = this._engine;
  18178. if (!camera) {
  18179. if (!this.activeCamera)
  18180. throw new Error("Active camera not set");
  18181. camera = this.activeCamera;
  18182. }
  18183. var cameraViewport = camera.viewport;
  18184. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18185. var identity = BABYLON.Matrix.Identity();
  18186. // Moving coordinates to local viewport world
  18187. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18188. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18189. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18190. };
  18191. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18192. if (!BABYLON.PickingInfo) {
  18193. return null;
  18194. }
  18195. var pickingInfo = null;
  18196. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18197. var mesh = this.meshes[meshIndex];
  18198. if (predicate) {
  18199. if (!predicate(mesh)) {
  18200. continue;
  18201. }
  18202. }
  18203. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18204. continue;
  18205. }
  18206. var world = mesh.getWorldMatrix();
  18207. var ray = rayFunction(world);
  18208. var result = mesh.intersects(ray, fastCheck);
  18209. if (!result || !result.hit)
  18210. continue;
  18211. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18212. continue;
  18213. pickingInfo = result;
  18214. if (fastCheck) {
  18215. break;
  18216. }
  18217. }
  18218. return pickingInfo || new BABYLON.PickingInfo();
  18219. };
  18220. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18221. if (!BABYLON.PickingInfo) {
  18222. return null;
  18223. }
  18224. var pickingInfos = new Array();
  18225. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18226. var mesh = this.meshes[meshIndex];
  18227. if (predicate) {
  18228. if (!predicate(mesh)) {
  18229. continue;
  18230. }
  18231. }
  18232. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18233. continue;
  18234. }
  18235. var world = mesh.getWorldMatrix();
  18236. var ray = rayFunction(world);
  18237. var result = mesh.intersects(ray, false);
  18238. if (!result || !result.hit)
  18239. continue;
  18240. pickingInfos.push(result);
  18241. }
  18242. return pickingInfos;
  18243. };
  18244. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18245. if (!BABYLON.PickingInfo) {
  18246. return null;
  18247. }
  18248. var pickingInfo = null;
  18249. camera = camera || this.activeCamera;
  18250. if (this.spriteManagers.length > 0) {
  18251. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18252. var spriteManager = this.spriteManagers[spriteIndex];
  18253. if (!spriteManager.isPickable) {
  18254. continue;
  18255. }
  18256. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18257. if (!result || !result.hit)
  18258. continue;
  18259. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18260. continue;
  18261. pickingInfo = result;
  18262. if (fastCheck) {
  18263. break;
  18264. }
  18265. }
  18266. }
  18267. return pickingInfo || new BABYLON.PickingInfo();
  18268. };
  18269. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18270. /// <param name="x">X position on screen</param>
  18271. /// <param name="y">Y position on screen</param>
  18272. /// <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>
  18273. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18274. /// <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>
  18275. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18276. var _this = this;
  18277. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18278. };
  18279. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18280. /// <param name="x">X position on screen</param>
  18281. /// <param name="y">Y position on screen</param>
  18282. /// <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>
  18283. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18284. /// <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>
  18285. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18286. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18287. };
  18288. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18289. var _this = this;
  18290. return this._internalPick(function (world) {
  18291. if (!_this._pickWithRayInverseMatrix) {
  18292. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18293. }
  18294. world.invertToRef(_this._pickWithRayInverseMatrix);
  18295. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18296. }, predicate, fastCheck);
  18297. };
  18298. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18299. /// <param name="x">X position on screen</param>
  18300. /// <param name="y">Y position on screen</param>
  18301. /// <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>
  18302. /// <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>
  18303. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18304. var _this = this;
  18305. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18306. };
  18307. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18308. /// <param name="ray">Ray to use</param>
  18309. /// <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>
  18310. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18311. var _this = this;
  18312. return this._internalMultiPick(function (world) {
  18313. if (!_this._pickWithRayInverseMatrix) {
  18314. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18315. }
  18316. world.invertToRef(_this._pickWithRayInverseMatrix);
  18317. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18318. }, predicate);
  18319. };
  18320. Scene.prototype.setPointerOverMesh = function (mesh) {
  18321. if (this._pointerOverMesh === mesh) {
  18322. return;
  18323. }
  18324. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18325. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18326. }
  18327. this._pointerOverMesh = mesh;
  18328. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18329. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18330. }
  18331. };
  18332. Scene.prototype.getPointerOverMesh = function () {
  18333. return this._pointerOverMesh;
  18334. };
  18335. Scene.prototype.setPointerOverSprite = function (sprite) {
  18336. if (this._pointerOverSprite === sprite) {
  18337. return;
  18338. }
  18339. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18340. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18341. }
  18342. this._pointerOverSprite = sprite;
  18343. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18344. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18345. }
  18346. };
  18347. Scene.prototype.getPointerOverSprite = function () {
  18348. return this._pointerOverSprite;
  18349. };
  18350. // Physics
  18351. Scene.prototype.getPhysicsEngine = function () {
  18352. return this._physicsEngine;
  18353. };
  18354. /**
  18355. * Enables physics to the current scene
  18356. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18357. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18358. * @return {boolean} was the physics engine initialized
  18359. */
  18360. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18361. if (this._physicsEngine) {
  18362. return true;
  18363. }
  18364. try {
  18365. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18366. return true;
  18367. }
  18368. catch (e) {
  18369. BABYLON.Tools.Error(e.message);
  18370. return false;
  18371. }
  18372. };
  18373. Scene.prototype.disablePhysicsEngine = function () {
  18374. if (!this._physicsEngine) {
  18375. return;
  18376. }
  18377. this._physicsEngine.dispose();
  18378. this._physicsEngine = undefined;
  18379. };
  18380. Scene.prototype.isPhysicsEnabled = function () {
  18381. return this._physicsEngine !== undefined;
  18382. };
  18383. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18384. var mesh = compound.parts[0].mesh;
  18385. mesh.physicsImpostor.dispose();
  18386. mesh.physicsImpostor = null;
  18387. };
  18388. // Misc.
  18389. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18390. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18391. // Light
  18392. if (this.lights.length === 0) {
  18393. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18394. }
  18395. // Camera
  18396. if (!this.activeCamera) {
  18397. var worldExtends = this.getWorldExtends();
  18398. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18399. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18400. var camera;
  18401. var radius = worldSize.length() * 1.5;
  18402. if (createArcRotateCamera) {
  18403. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18404. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18405. arcRotateCamera.wheelPrecision = 100 / radius;
  18406. camera = arcRotateCamera;
  18407. }
  18408. else {
  18409. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18410. freeCamera.setTarget(worldCenter);
  18411. camera = freeCamera;
  18412. }
  18413. camera.minZ = radius * 0.01;
  18414. camera.maxZ = radius * 100;
  18415. camera.speed = radius * 0.2;
  18416. this.activeCamera = camera;
  18417. }
  18418. };
  18419. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18420. if (pbr === void 0) { pbr = false; }
  18421. if (environmentTexture) {
  18422. this.environmentTexture = environmentTexture;
  18423. }
  18424. if (!this.environmentTexture) {
  18425. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18426. return;
  18427. }
  18428. if (!this.environmentTexture) {
  18429. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18430. return;
  18431. }
  18432. // Skybox
  18433. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18434. if (pbr) {
  18435. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18436. hdrSkyboxMaterial.backFaceCulling = false;
  18437. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18438. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18439. hdrSkyboxMaterial.microSurface = 1.0;
  18440. hdrSkyboxMaterial.disableLighting = true;
  18441. hdrSkybox.infiniteDistance = true;
  18442. hdrSkybox.material = hdrSkyboxMaterial;
  18443. }
  18444. else {
  18445. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18446. skyboxMaterial.backFaceCulling = false;
  18447. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18448. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18449. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18450. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18451. skyboxMaterial.disableLighting = true;
  18452. hdrSkybox.infiniteDistance = true;
  18453. hdrSkybox.material = skyboxMaterial;
  18454. }
  18455. return hdrSkybox;
  18456. };
  18457. // Tags
  18458. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18459. if (tagsQuery === undefined) {
  18460. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18461. return list;
  18462. }
  18463. var listByTags = [];
  18464. forEach = forEach || (function (item) { return; });
  18465. for (var i in list) {
  18466. var item = list[i];
  18467. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18468. listByTags.push(item);
  18469. forEach(item);
  18470. }
  18471. }
  18472. return listByTags;
  18473. };
  18474. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18475. return this._getByTags(this.meshes, tagsQuery, forEach);
  18476. };
  18477. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18478. return this._getByTags(this.cameras, tagsQuery, forEach);
  18479. };
  18480. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18481. return this._getByTags(this.lights, tagsQuery, forEach);
  18482. };
  18483. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18484. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18485. };
  18486. /**
  18487. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18488. * This allowed control for front to back rendering or reversly depending of the special needs.
  18489. *
  18490. * @param renderingGroupId The rendering group id corresponding to its index
  18491. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18492. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18493. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18494. */
  18495. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18496. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18497. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18498. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18499. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18500. };
  18501. /**
  18502. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18503. *
  18504. * @param renderingGroupId The rendering group id corresponding to its index
  18505. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18506. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18507. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18508. */
  18509. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18510. if (depth === void 0) { depth = true; }
  18511. if (stencil === void 0) { stencil = true; }
  18512. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18513. };
  18514. /**
  18515. * Will flag all materials as dirty to trigger new shader compilation
  18516. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18517. */
  18518. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18519. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18520. var material = _a[_i];
  18521. if (predicate && !predicate(material)) {
  18522. continue;
  18523. }
  18524. material.markAsDirty(flag);
  18525. }
  18526. };
  18527. return Scene;
  18528. }());
  18529. // Statics
  18530. Scene._FOGMODE_NONE = 0;
  18531. Scene._FOGMODE_EXP = 1;
  18532. Scene._FOGMODE_EXP2 = 2;
  18533. Scene._FOGMODE_LINEAR = 3;
  18534. Scene.MinDeltaTime = 1.0;
  18535. Scene.MaxDeltaTime = 1000.0;
  18536. Scene.DragMovementThreshold = 10; // in pixels
  18537. Scene.LongPressDelay = 500; // in milliseconds
  18538. Scene.DoubleClickDelay = 300; // in milliseconds
  18539. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18540. BABYLON.Scene = Scene;
  18541. })(BABYLON || (BABYLON = {}));
  18542. //# sourceMappingURL=babylon.scene.js.map
  18543. var BABYLON;
  18544. (function (BABYLON) {
  18545. var Buffer = (function () {
  18546. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18547. if (engine instanceof BABYLON.Mesh) {
  18548. this._engine = engine.getScene().getEngine();
  18549. }
  18550. else {
  18551. this._engine = engine;
  18552. }
  18553. this._updatable = updatable;
  18554. this._data = data;
  18555. this._strideSize = stride;
  18556. if (!postponeInternalCreation) {
  18557. this.create();
  18558. }
  18559. this._instanced = instanced;
  18560. this._instanceDivisor = instanced ? 1 : 0;
  18561. }
  18562. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18563. // a lot of these parameters are ignored as they are overriden by the buffer
  18564. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18565. };
  18566. // Properties
  18567. Buffer.prototype.isUpdatable = function () {
  18568. return this._updatable;
  18569. };
  18570. Buffer.prototype.getData = function () {
  18571. return this._data;
  18572. };
  18573. Buffer.prototype.getBuffer = function () {
  18574. return this._buffer;
  18575. };
  18576. Buffer.prototype.getStrideSize = function () {
  18577. return this._strideSize;
  18578. };
  18579. Buffer.prototype.getIsInstanced = function () {
  18580. return this._instanced;
  18581. };
  18582. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18583. get: function () {
  18584. return this._instanceDivisor;
  18585. },
  18586. set: function (value) {
  18587. this._instanceDivisor = value;
  18588. if (value == 0) {
  18589. this._instanced = false;
  18590. }
  18591. else {
  18592. this._instanced = true;
  18593. }
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. // Methods
  18599. Buffer.prototype.create = function (data) {
  18600. if (!data && this._buffer) {
  18601. return; // nothing to do
  18602. }
  18603. data = data || this._data;
  18604. if (!this._buffer) {
  18605. if (this._updatable) {
  18606. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18607. this._data = data;
  18608. }
  18609. else {
  18610. this._buffer = this._engine.createVertexBuffer(data);
  18611. }
  18612. }
  18613. else if (this._updatable) {
  18614. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18615. this._data = data;
  18616. }
  18617. };
  18618. Buffer.prototype.update = function (data) {
  18619. this.create(data);
  18620. };
  18621. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18622. if (!this._buffer) {
  18623. return;
  18624. }
  18625. if (this._updatable) {
  18626. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18627. this._data = null;
  18628. }
  18629. };
  18630. Buffer.prototype.dispose = function () {
  18631. if (!this._buffer) {
  18632. return;
  18633. }
  18634. if (this._engine._releaseBuffer(this._buffer)) {
  18635. this._buffer = null;
  18636. }
  18637. };
  18638. return Buffer;
  18639. }());
  18640. BABYLON.Buffer = Buffer;
  18641. })(BABYLON || (BABYLON = {}));
  18642. //# sourceMappingURL=babylon.buffer.js.map
  18643. var BABYLON;
  18644. (function (BABYLON) {
  18645. var VertexBuffer = (function () {
  18646. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18647. if (!stride) {
  18648. // Deduce stride from kind
  18649. switch (kind) {
  18650. case VertexBuffer.PositionKind:
  18651. stride = 3;
  18652. break;
  18653. case VertexBuffer.NormalKind:
  18654. stride = 3;
  18655. break;
  18656. case VertexBuffer.UVKind:
  18657. case VertexBuffer.UV2Kind:
  18658. case VertexBuffer.UV3Kind:
  18659. case VertexBuffer.UV4Kind:
  18660. case VertexBuffer.UV5Kind:
  18661. case VertexBuffer.UV6Kind:
  18662. stride = 2;
  18663. break;
  18664. case VertexBuffer.TangentKind:
  18665. case VertexBuffer.ColorKind:
  18666. stride = 4;
  18667. break;
  18668. case VertexBuffer.MatricesIndicesKind:
  18669. case VertexBuffer.MatricesIndicesExtraKind:
  18670. stride = 4;
  18671. break;
  18672. case VertexBuffer.MatricesWeightsKind:
  18673. case VertexBuffer.MatricesWeightsExtraKind:
  18674. stride = 4;
  18675. break;
  18676. }
  18677. }
  18678. if (data instanceof BABYLON.Buffer) {
  18679. if (!stride) {
  18680. stride = data.getStrideSize();
  18681. }
  18682. this._buffer = data;
  18683. this._ownsBuffer = false;
  18684. }
  18685. else {
  18686. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18687. this._ownsBuffer = true;
  18688. }
  18689. this._stride = stride;
  18690. this._offset = offset ? offset : 0;
  18691. this._size = size ? size : stride;
  18692. this._kind = kind;
  18693. }
  18694. /**
  18695. * Returns the kind of the VertexBuffer (string).
  18696. */
  18697. VertexBuffer.prototype.getKind = function () {
  18698. return this._kind;
  18699. };
  18700. // Properties
  18701. /**
  18702. * Boolean : is the VertexBuffer updatable ?
  18703. */
  18704. VertexBuffer.prototype.isUpdatable = function () {
  18705. return this._buffer.isUpdatable();
  18706. };
  18707. /**
  18708. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18709. */
  18710. VertexBuffer.prototype.getData = function () {
  18711. return this._buffer.getData();
  18712. };
  18713. /**
  18714. * Returns the WebGLBuffer associated to the VertexBuffer.
  18715. */
  18716. VertexBuffer.prototype.getBuffer = function () {
  18717. return this._buffer.getBuffer();
  18718. };
  18719. /**
  18720. * Returns the stride of the VertexBuffer (integer).
  18721. */
  18722. VertexBuffer.prototype.getStrideSize = function () {
  18723. return this._stride;
  18724. };
  18725. /**
  18726. * Returns the offset (integer).
  18727. */
  18728. VertexBuffer.prototype.getOffset = function () {
  18729. return this._offset;
  18730. };
  18731. /**
  18732. * Returns the VertexBuffer total size (integer).
  18733. */
  18734. VertexBuffer.prototype.getSize = function () {
  18735. return this._size;
  18736. };
  18737. /**
  18738. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18739. */
  18740. VertexBuffer.prototype.getIsInstanced = function () {
  18741. return this._buffer.getIsInstanced();
  18742. };
  18743. /**
  18744. * Returns the instancing divisor, zero for non-instanced (integer).
  18745. */
  18746. VertexBuffer.prototype.getInstanceDivisor = function () {
  18747. return this._buffer.instanceDivisor;
  18748. };
  18749. // Methods
  18750. /**
  18751. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18752. * Returns the created WebGLBuffer.
  18753. */
  18754. VertexBuffer.prototype.create = function (data) {
  18755. return this._buffer.create(data);
  18756. };
  18757. /**
  18758. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18759. * Returns the updated WebGLBuffer.
  18760. */
  18761. VertexBuffer.prototype.update = function (data) {
  18762. return this._buffer.update(data);
  18763. };
  18764. /**
  18765. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18766. * Returns the directly updated WebGLBuffer.
  18767. */
  18768. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18769. return this._buffer.updateDirectly(data, offset);
  18770. };
  18771. /**
  18772. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18773. */
  18774. VertexBuffer.prototype.dispose = function () {
  18775. if (this._ownsBuffer) {
  18776. this._buffer.dispose();
  18777. }
  18778. };
  18779. Object.defineProperty(VertexBuffer, "PositionKind", {
  18780. get: function () {
  18781. return VertexBuffer._PositionKind;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(VertexBuffer, "NormalKind", {
  18787. get: function () {
  18788. return VertexBuffer._NormalKind;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(VertexBuffer, "TangentKind", {
  18794. get: function () {
  18795. return VertexBuffer._TangentKind;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. Object.defineProperty(VertexBuffer, "UVKind", {
  18801. get: function () {
  18802. return VertexBuffer._UVKind;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18808. get: function () {
  18809. return VertexBuffer._UV2Kind;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18815. get: function () {
  18816. return VertexBuffer._UV3Kind;
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18822. get: function () {
  18823. return VertexBuffer._UV4Kind;
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18829. get: function () {
  18830. return VertexBuffer._UV5Kind;
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18836. get: function () {
  18837. return VertexBuffer._UV6Kind;
  18838. },
  18839. enumerable: true,
  18840. configurable: true
  18841. });
  18842. Object.defineProperty(VertexBuffer, "ColorKind", {
  18843. get: function () {
  18844. return VertexBuffer._ColorKind;
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18850. get: function () {
  18851. return VertexBuffer._MatricesIndicesKind;
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18857. get: function () {
  18858. return VertexBuffer._MatricesWeightsKind;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18864. get: function () {
  18865. return VertexBuffer._MatricesIndicesExtraKind;
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18871. get: function () {
  18872. return VertexBuffer._MatricesWeightsExtraKind;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. return VertexBuffer;
  18878. }());
  18879. // Enums
  18880. VertexBuffer._PositionKind = "position";
  18881. VertexBuffer._NormalKind = "normal";
  18882. VertexBuffer._TangentKind = "tangent";
  18883. VertexBuffer._UVKind = "uv";
  18884. VertexBuffer._UV2Kind = "uv2";
  18885. VertexBuffer._UV3Kind = "uv3";
  18886. VertexBuffer._UV4Kind = "uv4";
  18887. VertexBuffer._UV5Kind = "uv5";
  18888. VertexBuffer._UV6Kind = "uv6";
  18889. VertexBuffer._ColorKind = "color";
  18890. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18891. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18892. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18893. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18894. BABYLON.VertexBuffer = VertexBuffer;
  18895. })(BABYLON || (BABYLON = {}));
  18896. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18897. var BABYLON;
  18898. (function (BABYLON) {
  18899. var BaseTexture = (function () {
  18900. function BaseTexture(scene) {
  18901. this._hasAlpha = false;
  18902. this.getAlphaFromRGB = false;
  18903. this.level = 1;
  18904. this.coordinatesIndex = 0;
  18905. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18906. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18907. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18908. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18909. this.isCube = false;
  18910. this.isRenderTarget = false;
  18911. this.animations = new Array();
  18912. /**
  18913. * An event triggered when the texture is disposed.
  18914. * @type {BABYLON.Observable}
  18915. */
  18916. this.onDisposeObservable = new BABYLON.Observable();
  18917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18918. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18919. this._scene.textures.push(this);
  18920. this._uid = null;
  18921. }
  18922. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18923. get: function () {
  18924. return this._hasAlpha;
  18925. },
  18926. set: function (value) {
  18927. if (this._hasAlpha === value) {
  18928. return;
  18929. }
  18930. this._hasAlpha = value;
  18931. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18932. },
  18933. enumerable: true,
  18934. configurable: true
  18935. });
  18936. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18937. get: function () {
  18938. return this._coordinatesMode;
  18939. },
  18940. set: function (value) {
  18941. if (this._coordinatesMode === value) {
  18942. return;
  18943. }
  18944. this._coordinatesMode = value;
  18945. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18946. },
  18947. enumerable: true,
  18948. configurable: true
  18949. });
  18950. Object.defineProperty(BaseTexture.prototype, "uid", {
  18951. get: function () {
  18952. if (!this._uid) {
  18953. this._uid = BABYLON.Tools.RandomId();
  18954. }
  18955. return this._uid;
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. BaseTexture.prototype.toString = function () {
  18961. return this.name;
  18962. };
  18963. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18964. set: function (callback) {
  18965. if (this._onDisposeObserver) {
  18966. this.onDisposeObservable.remove(this._onDisposeObserver);
  18967. }
  18968. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18969. },
  18970. enumerable: true,
  18971. configurable: true
  18972. });
  18973. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18974. get: function () {
  18975. return true;
  18976. },
  18977. enumerable: true,
  18978. configurable: true
  18979. });
  18980. BaseTexture.prototype.getScene = function () {
  18981. return this._scene;
  18982. };
  18983. BaseTexture.prototype.getTextureMatrix = function () {
  18984. return null;
  18985. };
  18986. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18987. return null;
  18988. };
  18989. BaseTexture.prototype.getInternalTexture = function () {
  18990. return this._texture;
  18991. };
  18992. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18993. return !this.isBlocking || this.isReady();
  18994. };
  18995. BaseTexture.prototype.isReady = function () {
  18996. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18997. this.delayLoad();
  18998. return false;
  18999. }
  19000. if (this._texture) {
  19001. return this._texture.isReady;
  19002. }
  19003. return false;
  19004. };
  19005. BaseTexture.prototype.getSize = function () {
  19006. if (this._texture._width) {
  19007. return new BABYLON.Size(this._texture._width, this._texture._height);
  19008. }
  19009. if (this._texture._size) {
  19010. return new BABYLON.Size(this._texture._size, this._texture._size);
  19011. }
  19012. return BABYLON.Size.Zero();
  19013. };
  19014. BaseTexture.prototype.getBaseSize = function () {
  19015. if (!this.isReady() || !this._texture)
  19016. return BABYLON.Size.Zero();
  19017. if (this._texture._size) {
  19018. return new BABYLON.Size(this._texture._size, this._texture._size);
  19019. }
  19020. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19021. };
  19022. BaseTexture.prototype.scale = function (ratio) {
  19023. };
  19024. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19025. get: function () {
  19026. return false;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19032. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19033. for (var index = 0; index < texturesCache.length; index++) {
  19034. var texturesCacheEntry = texturesCache[index];
  19035. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19036. texturesCache.splice(index, 1);
  19037. return;
  19038. }
  19039. }
  19040. };
  19041. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19042. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19043. for (var index = 0; index < texturesCache.length; index++) {
  19044. var texturesCacheEntry = texturesCache[index];
  19045. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19046. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19047. texturesCacheEntry.references++;
  19048. return texturesCacheEntry;
  19049. }
  19050. }
  19051. }
  19052. return null;
  19053. };
  19054. BaseTexture.prototype.delayLoad = function () {
  19055. };
  19056. BaseTexture.prototype.clone = function () {
  19057. return null;
  19058. };
  19059. BaseTexture.prototype.readPixels = function (faceIndex) {
  19060. if (faceIndex === void 0) { faceIndex = 0; }
  19061. if (!this._texture) {
  19062. return null;
  19063. }
  19064. var size = this.getSize();
  19065. var engine = this.getScene().getEngine();
  19066. if (this._texture.isCube) {
  19067. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19068. }
  19069. return engine._readTexturePixels(this._texture, size.width, size.height);
  19070. };
  19071. BaseTexture.prototype.releaseInternalTexture = function () {
  19072. if (this._texture) {
  19073. this._scene.getEngine().releaseInternalTexture(this._texture);
  19074. delete this._texture;
  19075. }
  19076. };
  19077. BaseTexture.prototype.dispose = function () {
  19078. // Animations
  19079. this.getScene().stopAnimation(this);
  19080. // Remove from scene
  19081. this._scene._removePendingData(this);
  19082. var index = this._scene.textures.indexOf(this);
  19083. if (index >= 0) {
  19084. this._scene.textures.splice(index, 1);
  19085. }
  19086. if (this._texture === undefined) {
  19087. return;
  19088. }
  19089. // Release
  19090. this.releaseInternalTexture();
  19091. // Callback
  19092. this.onDisposeObservable.notifyObservers(this);
  19093. this.onDisposeObservable.clear();
  19094. };
  19095. BaseTexture.prototype.serialize = function () {
  19096. if (!this.name) {
  19097. return null;
  19098. }
  19099. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19100. // Animations
  19101. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19102. return serializationObject;
  19103. };
  19104. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19105. var numReady = 0;
  19106. var _loop_1 = function () {
  19107. texture = textures[i];
  19108. if (texture.isReady()) {
  19109. if (++numReady === textures.length) {
  19110. onLoad();
  19111. }
  19112. }
  19113. else {
  19114. observable = texture.onLoadObservable;
  19115. var callback_1 = function () {
  19116. observable.removeCallback(callback_1);
  19117. if (++numReady === textures.length) {
  19118. onLoad();
  19119. }
  19120. };
  19121. observable.add(callback_1);
  19122. }
  19123. };
  19124. var texture, observable;
  19125. for (var i = 0; i < textures.length; i++) {
  19126. _loop_1();
  19127. }
  19128. };
  19129. return BaseTexture;
  19130. }());
  19131. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19132. __decorate([
  19133. BABYLON.serialize()
  19134. ], BaseTexture.prototype, "name", void 0);
  19135. __decorate([
  19136. BABYLON.serialize("hasAlpha")
  19137. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19138. __decorate([
  19139. BABYLON.serialize()
  19140. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19141. __decorate([
  19142. BABYLON.serialize()
  19143. ], BaseTexture.prototype, "level", void 0);
  19144. __decorate([
  19145. BABYLON.serialize()
  19146. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19147. __decorate([
  19148. BABYLON.serialize("coordinatesMode")
  19149. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19150. __decorate([
  19151. BABYLON.serialize()
  19152. ], BaseTexture.prototype, "wrapU", void 0);
  19153. __decorate([
  19154. BABYLON.serialize()
  19155. ], BaseTexture.prototype, "wrapV", void 0);
  19156. __decorate([
  19157. BABYLON.serialize()
  19158. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19159. __decorate([
  19160. BABYLON.serialize()
  19161. ], BaseTexture.prototype, "isCube", void 0);
  19162. __decorate([
  19163. BABYLON.serialize()
  19164. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19165. BABYLON.BaseTexture = BaseTexture;
  19166. })(BABYLON || (BABYLON = {}));
  19167. //# sourceMappingURL=babylon.baseTexture.js.map
  19168. var BABYLON;
  19169. (function (BABYLON) {
  19170. var Texture = (function (_super) {
  19171. __extends(Texture, _super);
  19172. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19173. if (noMipmap === void 0) { noMipmap = false; }
  19174. if (invertY === void 0) { invertY = true; }
  19175. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19176. if (onLoad === void 0) { onLoad = null; }
  19177. if (onError === void 0) { onError = null; }
  19178. if (buffer === void 0) { buffer = null; }
  19179. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19180. var _this = _super.call(this, scene) || this;
  19181. _this.uOffset = 0;
  19182. _this.vOffset = 0;
  19183. _this.uScale = 1.0;
  19184. _this.vScale = 1.0;
  19185. _this.uAng = 0;
  19186. _this.vAng = 0;
  19187. _this.wAng = 0;
  19188. _this._isBlocking = true;
  19189. _this.name = url;
  19190. _this.url = url;
  19191. _this._noMipmap = noMipmap;
  19192. _this._invertY = invertY;
  19193. _this._samplingMode = samplingMode;
  19194. _this._buffer = buffer;
  19195. _this._deleteBuffer = deleteBuffer;
  19196. _this._format = format;
  19197. scene = _this.getScene();
  19198. var load = function () {
  19199. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19200. _this.onLoadObservable.notifyObservers(_this);
  19201. }
  19202. if (onLoad) {
  19203. onLoad();
  19204. }
  19205. if (!_this.isBlocking) {
  19206. scene.resetCachedMaterial();
  19207. }
  19208. };
  19209. if (!url) {
  19210. _this._delayedOnLoad = load;
  19211. _this._delayedOnError = onError;
  19212. return _this;
  19213. }
  19214. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19215. if (!_this._texture) {
  19216. if (!scene.useDelayedTextureLoading) {
  19217. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19218. if (deleteBuffer) {
  19219. delete _this._buffer;
  19220. }
  19221. }
  19222. else {
  19223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19224. _this._delayedOnLoad = load;
  19225. _this._delayedOnError = onError;
  19226. }
  19227. }
  19228. else {
  19229. if (_this._texture.isReady) {
  19230. BABYLON.Tools.SetImmediate(function () { return load(); });
  19231. }
  19232. else {
  19233. _this._texture.onLoadedCallbacks.push(load);
  19234. }
  19235. }
  19236. return _this;
  19237. }
  19238. Object.defineProperty(Texture.prototype, "noMipmap", {
  19239. get: function () {
  19240. return this._noMipmap;
  19241. },
  19242. enumerable: true,
  19243. configurable: true
  19244. });
  19245. Object.defineProperty(Texture.prototype, "isBlocking", {
  19246. get: function () {
  19247. return this._isBlocking;
  19248. },
  19249. set: function (value) {
  19250. this._isBlocking = value;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Texture.prototype.updateURL = function (url) {
  19256. this.url = url;
  19257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19258. this.delayLoad();
  19259. };
  19260. Texture.prototype.delayLoad = function () {
  19261. var _this = this;
  19262. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19263. return;
  19264. }
  19265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19266. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19267. if (!this._texture) {
  19268. 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);
  19269. if (this._deleteBuffer) {
  19270. delete this._buffer;
  19271. }
  19272. }
  19273. else {
  19274. if (this._texture.isReady) {
  19275. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19276. }
  19277. else {
  19278. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19279. }
  19280. }
  19281. };
  19282. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19283. if (!this._texture) {
  19284. return;
  19285. }
  19286. this._samplingMode = samplingMode;
  19287. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19288. };
  19289. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19290. x *= this.uScale;
  19291. y *= this.vScale;
  19292. x -= 0.5 * this.uScale;
  19293. y -= 0.5 * this.vScale;
  19294. z -= 0.5;
  19295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19296. t.x += 0.5 * this.uScale + this.uOffset;
  19297. t.y += 0.5 * this.vScale + this.vOffset;
  19298. t.z += 0.5;
  19299. };
  19300. Texture.prototype.getTextureMatrix = function () {
  19301. if (this.uOffset === this._cachedUOffset &&
  19302. this.vOffset === this._cachedVOffset &&
  19303. this.uScale === this._cachedUScale &&
  19304. this.vScale === this._cachedVScale &&
  19305. this.uAng === this._cachedUAng &&
  19306. this.vAng === this._cachedVAng &&
  19307. this.wAng === this._cachedWAng) {
  19308. return this._cachedTextureMatrix;
  19309. }
  19310. this._cachedUOffset = this.uOffset;
  19311. this._cachedVOffset = this.vOffset;
  19312. this._cachedUScale = this.uScale;
  19313. this._cachedVScale = this.vScale;
  19314. this._cachedUAng = this.uAng;
  19315. this._cachedVAng = this.vAng;
  19316. this._cachedWAng = this.wAng;
  19317. if (!this._cachedTextureMatrix) {
  19318. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19319. this._rowGenerationMatrix = new BABYLON.Matrix();
  19320. this._t0 = BABYLON.Vector3.Zero();
  19321. this._t1 = BABYLON.Vector3.Zero();
  19322. this._t2 = BABYLON.Vector3.Zero();
  19323. }
  19324. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19325. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19326. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19327. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19328. this._t1.subtractInPlace(this._t0);
  19329. this._t2.subtractInPlace(this._t0);
  19330. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19331. this._cachedTextureMatrix.m[0] = this._t1.x;
  19332. this._cachedTextureMatrix.m[1] = this._t1.y;
  19333. this._cachedTextureMatrix.m[2] = this._t1.z;
  19334. this._cachedTextureMatrix.m[4] = this._t2.x;
  19335. this._cachedTextureMatrix.m[5] = this._t2.y;
  19336. this._cachedTextureMatrix.m[6] = this._t2.z;
  19337. this._cachedTextureMatrix.m[8] = this._t0.x;
  19338. this._cachedTextureMatrix.m[9] = this._t0.y;
  19339. this._cachedTextureMatrix.m[10] = this._t0.z;
  19340. return this._cachedTextureMatrix;
  19341. };
  19342. Texture.prototype.getReflectionTextureMatrix = function () {
  19343. if (this.uOffset === this._cachedUOffset &&
  19344. this.vOffset === this._cachedVOffset &&
  19345. this.uScale === this._cachedUScale &&
  19346. this.vScale === this._cachedVScale &&
  19347. this.coordinatesMode === this._cachedCoordinatesMode) {
  19348. return this._cachedTextureMatrix;
  19349. }
  19350. if (!this._cachedTextureMatrix) {
  19351. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19352. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19353. }
  19354. this._cachedCoordinatesMode = this.coordinatesMode;
  19355. switch (this.coordinatesMode) {
  19356. case Texture.PLANAR_MODE:
  19357. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19358. this._cachedTextureMatrix[0] = this.uScale;
  19359. this._cachedTextureMatrix[5] = this.vScale;
  19360. this._cachedTextureMatrix[12] = this.uOffset;
  19361. this._cachedTextureMatrix[13] = this.vOffset;
  19362. break;
  19363. case Texture.PROJECTION_MODE:
  19364. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19365. this._projectionModeMatrix.m[0] = 0.5;
  19366. this._projectionModeMatrix.m[5] = -0.5;
  19367. this._projectionModeMatrix.m[10] = 0.0;
  19368. this._projectionModeMatrix.m[12] = 0.5;
  19369. this._projectionModeMatrix.m[13] = 0.5;
  19370. this._projectionModeMatrix.m[14] = 1.0;
  19371. this._projectionModeMatrix.m[15] = 1.0;
  19372. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19373. break;
  19374. default:
  19375. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19376. break;
  19377. }
  19378. return this._cachedTextureMatrix;
  19379. };
  19380. Texture.prototype.clone = function () {
  19381. var _this = this;
  19382. return BABYLON.SerializationHelper.Clone(function () {
  19383. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19384. }, this);
  19385. };
  19386. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19387. get: function () {
  19388. if (!this._onLoadObservable) {
  19389. this._onLoadObservable = new BABYLON.Observable();
  19390. }
  19391. return this._onLoadObservable;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. // Statics
  19397. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19398. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19399. if (onLoad === void 0) { onLoad = null; }
  19400. if (onError === void 0) { onError = null; }
  19401. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19402. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19403. };
  19404. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19405. if (parsedTexture.customType) {
  19406. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19407. // Update Sampling Mode
  19408. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19409. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19410. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19411. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19412. }
  19413. }
  19414. return parsedCustomTexture;
  19415. }
  19416. if (parsedTexture.isCube) {
  19417. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19418. }
  19419. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19420. return null;
  19421. }
  19422. var texture = BABYLON.SerializationHelper.Parse(function () {
  19423. if (parsedTexture.mirrorPlane) {
  19424. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19425. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19426. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19427. return mirrorTexture;
  19428. }
  19429. else if (parsedTexture.isRenderTarget) {
  19430. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19431. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19432. return renderTargetTexture;
  19433. }
  19434. else {
  19435. var texture;
  19436. if (parsedTexture.base64String) {
  19437. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19438. }
  19439. else {
  19440. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19441. }
  19442. return texture;
  19443. }
  19444. }, parsedTexture, scene);
  19445. // Update Sampling Mode
  19446. if (parsedTexture.samplingMode) {
  19447. var sampling = parsedTexture.samplingMode;
  19448. if (texture._samplingMode !== sampling) {
  19449. texture.updateSamplingMode(sampling);
  19450. }
  19451. }
  19452. // Animations
  19453. if (parsedTexture.animations) {
  19454. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19455. var parsedAnimation = parsedTexture.animations[animationIndex];
  19456. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19457. }
  19458. }
  19459. return texture;
  19460. };
  19461. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19462. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19463. if (noMipmap === void 0) { noMipmap = false; }
  19464. if (invertY === void 0) { invertY = true; }
  19465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19466. if (onLoad === void 0) { onLoad = null; }
  19467. if (onError === void 0) { onError = null; }
  19468. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19469. if (name.substr(0, 5) !== "data:") {
  19470. name = "data:" + name;
  19471. }
  19472. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19473. };
  19474. return Texture;
  19475. }(BABYLON.BaseTexture));
  19476. // Constants
  19477. Texture.NEAREST_SAMPLINGMODE = 1;
  19478. Texture.BILINEAR_SAMPLINGMODE = 2;
  19479. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19480. Texture.EXPLICIT_MODE = 0;
  19481. Texture.SPHERICAL_MODE = 1;
  19482. Texture.PLANAR_MODE = 2;
  19483. Texture.CUBIC_MODE = 3;
  19484. Texture.PROJECTION_MODE = 4;
  19485. Texture.SKYBOX_MODE = 5;
  19486. Texture.INVCUBIC_MODE = 6;
  19487. Texture.EQUIRECTANGULAR_MODE = 7;
  19488. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19489. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19490. Texture.CLAMP_ADDRESSMODE = 0;
  19491. Texture.WRAP_ADDRESSMODE = 1;
  19492. Texture.MIRROR_ADDRESSMODE = 2;
  19493. __decorate([
  19494. BABYLON.serialize()
  19495. ], Texture.prototype, "url", void 0);
  19496. __decorate([
  19497. BABYLON.serialize()
  19498. ], Texture.prototype, "uOffset", void 0);
  19499. __decorate([
  19500. BABYLON.serialize()
  19501. ], Texture.prototype, "vOffset", void 0);
  19502. __decorate([
  19503. BABYLON.serialize()
  19504. ], Texture.prototype, "uScale", void 0);
  19505. __decorate([
  19506. BABYLON.serialize()
  19507. ], Texture.prototype, "vScale", void 0);
  19508. __decorate([
  19509. BABYLON.serialize()
  19510. ], Texture.prototype, "uAng", void 0);
  19511. __decorate([
  19512. BABYLON.serialize()
  19513. ], Texture.prototype, "vAng", void 0);
  19514. __decorate([
  19515. BABYLON.serialize()
  19516. ], Texture.prototype, "wAng", void 0);
  19517. __decorate([
  19518. BABYLON.serialize()
  19519. ], Texture.prototype, "isBlocking", null);
  19520. BABYLON.Texture = Texture;
  19521. })(BABYLON || (BABYLON = {}));
  19522. //# sourceMappingURL=babylon.texture.js.map
  19523. var BABYLON;
  19524. (function (BABYLON) {
  19525. var _InstancesBatch = (function () {
  19526. function _InstancesBatch() {
  19527. this.mustReturn = false;
  19528. this.visibleInstances = new Array();
  19529. this.renderSelf = new Array();
  19530. }
  19531. return _InstancesBatch;
  19532. }());
  19533. BABYLON._InstancesBatch = _InstancesBatch;
  19534. var Mesh = (function (_super) {
  19535. __extends(Mesh, _super);
  19536. /**
  19537. * @constructor
  19538. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19539. * @param {Scene} scene The scene to add this mesh to.
  19540. * @param {Node} parent The parent of this mesh, if it has one
  19541. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19542. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19543. * When false, achieved by calling a clone(), also passing False.
  19544. * This will make creation of children, recursive.
  19545. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19546. */
  19547. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19548. if (parent === void 0) { parent = null; }
  19549. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19550. var _this = _super.call(this, name, scene) || this;
  19551. // Events
  19552. /**
  19553. * An event triggered before rendering the mesh
  19554. * @type {BABYLON.Observable}
  19555. */
  19556. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19557. /**
  19558. * An event triggered after rendering the mesh
  19559. * @type {BABYLON.Observable}
  19560. */
  19561. _this.onAfterRenderObservable = new BABYLON.Observable();
  19562. /**
  19563. * An event triggered before drawing the mesh
  19564. * @type {BABYLON.Observable}
  19565. */
  19566. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19567. // Members
  19568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19569. _this.instances = new Array();
  19570. _this._LODLevels = new Array();
  19571. _this._visibleInstances = {};
  19572. _this._renderIdForInstances = new Array();
  19573. _this._batchCache = new _InstancesBatch();
  19574. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19575. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19576. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19577. // Will be used to save a source mesh reference, If any
  19578. _this._source = null;
  19579. if (source) {
  19580. // Source mesh
  19581. _this._source = source;
  19582. // Geometry
  19583. if (source._geometry) {
  19584. source._geometry.applyToMesh(_this);
  19585. }
  19586. // Deep copy
  19587. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19588. // Parent
  19589. _this.parent = source.parent;
  19590. // Pivot
  19591. _this.setPivotMatrix(source.getPivotMatrix());
  19592. _this.id = name + "." + source.id;
  19593. // Material
  19594. _this.material = source.material;
  19595. var index;
  19596. if (!doNotCloneChildren) {
  19597. // Children
  19598. for (index = 0; index < scene.meshes.length; index++) {
  19599. var mesh = scene.meshes[index];
  19600. if (mesh.parent === source) {
  19601. // doNotCloneChildren is always going to be False
  19602. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19603. }
  19604. }
  19605. }
  19606. // Physics clone
  19607. var physicsEngine = _this.getScene().getPhysicsEngine();
  19608. if (clonePhysicsImpostor && physicsEngine) {
  19609. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19610. if (impostor) {
  19611. _this.physicsImpostor = impostor.clone(_this);
  19612. }
  19613. }
  19614. // Particles
  19615. for (index = 0; index < scene.particleSystems.length; index++) {
  19616. var system = scene.particleSystems[index];
  19617. if (system.emitter === source) {
  19618. system.clone(system.name, _this);
  19619. }
  19620. }
  19621. _this.computeWorldMatrix(true);
  19622. }
  19623. // Parent
  19624. if (parent !== null) {
  19625. _this.parent = parent;
  19626. }
  19627. return _this;
  19628. }
  19629. Object.defineProperty(Mesh, "FRONTSIDE", {
  19630. /**
  19631. * Mesh side orientation : usually the external or front surface
  19632. */
  19633. get: function () {
  19634. return Mesh._FRONTSIDE;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Mesh, "BACKSIDE", {
  19640. /**
  19641. * Mesh side orientation : usually the internal or back surface
  19642. */
  19643. get: function () {
  19644. return Mesh._BACKSIDE;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19650. /**
  19651. * Mesh side orientation : both internal and external or front and back surfaces
  19652. */
  19653. get: function () {
  19654. return Mesh._DOUBLESIDE;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19660. /**
  19661. * Mesh side orientation : by default, `FRONTSIDE`
  19662. */
  19663. get: function () {
  19664. return Mesh._DEFAULTSIDE;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(Mesh, "NO_CAP", {
  19670. /**
  19671. * Mesh cap setting : no cap
  19672. */
  19673. get: function () {
  19674. return Mesh._NO_CAP;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Mesh, "CAP_START", {
  19680. /**
  19681. * Mesh cap setting : one cap at the beginning of the mesh
  19682. */
  19683. get: function () {
  19684. return Mesh._CAP_START;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(Mesh, "CAP_END", {
  19690. /**
  19691. * Mesh cap setting : one cap at the end of the mesh
  19692. */
  19693. get: function () {
  19694. return Mesh._CAP_END;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Mesh, "CAP_ALL", {
  19700. /**
  19701. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19702. */
  19703. get: function () {
  19704. return Mesh._CAP_ALL;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19710. set: function (callback) {
  19711. if (this._onBeforeDrawObserver) {
  19712. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19713. }
  19714. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19720. get: function () {
  19721. return this._morphTargetManager;
  19722. },
  19723. set: function (value) {
  19724. if (this._morphTargetManager === value) {
  19725. return;
  19726. }
  19727. this._morphTargetManager = value;
  19728. this._syncGeometryWithMorphTargetManager();
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Mesh.prototype, "source", {
  19734. get: function () {
  19735. return this._source;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. // Methods
  19741. /**
  19742. * Returns the string "Mesh".
  19743. */
  19744. Mesh.prototype.getClassName = function () {
  19745. return "Mesh";
  19746. };
  19747. /**
  19748. * Returns a string.
  19749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19750. */
  19751. Mesh.prototype.toString = function (fullDetails) {
  19752. var ret = _super.prototype.toString.call(this, fullDetails);
  19753. ret += ", n vertices: " + this.getTotalVertices();
  19754. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19755. if (this.animations) {
  19756. for (var i = 0; i < this.animations.length; i++) {
  19757. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19758. }
  19759. }
  19760. if (fullDetails) {
  19761. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19762. }
  19763. return ret;
  19764. };
  19765. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19766. /**
  19767. * True if the mesh has some Levels Of Details (LOD).
  19768. * Returns a boolean.
  19769. */
  19770. get: function () {
  19771. return this._LODLevels.length > 0;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Mesh.prototype._sortLODLevels = function () {
  19777. this._LODLevels.sort(function (a, b) {
  19778. if (a.distance < b.distance) {
  19779. return 1;
  19780. }
  19781. if (a.distance > b.distance) {
  19782. return -1;
  19783. }
  19784. return 0;
  19785. });
  19786. };
  19787. /**
  19788. * Add a mesh as LOD level triggered at the given distance.
  19789. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19790. * @param {number} distance The distance from the center of the object to show this level
  19791. * @param {Mesh} mesh The mesh to be added as LOD level
  19792. * @return {Mesh} This mesh (for chaining)
  19793. */
  19794. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19795. if (mesh && mesh._masterMesh) {
  19796. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19797. return this;
  19798. }
  19799. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19800. this._LODLevels.push(level);
  19801. if (mesh) {
  19802. mesh._masterMesh = this;
  19803. }
  19804. this._sortLODLevels();
  19805. return this;
  19806. };
  19807. /**
  19808. * Returns the LOD level mesh at the passed distance or null if not found.
  19809. * It is related to the method `addLODLevel(distance, mesh)`.
  19810. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19811. * Returns an object Mesh or `null`.
  19812. */
  19813. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19814. for (var index = 0; index < this._LODLevels.length; index++) {
  19815. var level = this._LODLevels[index];
  19816. if (level.distance === distance) {
  19817. return level.mesh;
  19818. }
  19819. }
  19820. return null;
  19821. };
  19822. /**
  19823. * Remove a mesh from the LOD array
  19824. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19825. * @param {Mesh} mesh The mesh to be removed.
  19826. * @return {Mesh} This mesh (for chaining)
  19827. */
  19828. Mesh.prototype.removeLODLevel = function (mesh) {
  19829. for (var index = 0; index < this._LODLevels.length; index++) {
  19830. if (this._LODLevels[index].mesh === mesh) {
  19831. this._LODLevels.splice(index, 1);
  19832. if (mesh) {
  19833. mesh._masterMesh = null;
  19834. }
  19835. }
  19836. }
  19837. this._sortLODLevels();
  19838. return this;
  19839. };
  19840. /**
  19841. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19843. */
  19844. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19845. if (!this._LODLevels || this._LODLevels.length === 0) {
  19846. return this;
  19847. }
  19848. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19849. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19850. if (this.onLODLevelSelection) {
  19851. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19852. }
  19853. return this;
  19854. }
  19855. for (var index = 0; index < this._LODLevels.length; index++) {
  19856. var level = this._LODLevels[index];
  19857. if (level.distance < distanceToCamera) {
  19858. if (level.mesh) {
  19859. level.mesh._preActivate();
  19860. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19861. }
  19862. if (this.onLODLevelSelection) {
  19863. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19864. }
  19865. return level.mesh;
  19866. }
  19867. }
  19868. if (this.onLODLevelSelection) {
  19869. this.onLODLevelSelection(distanceToCamera, this, this);
  19870. }
  19871. return this;
  19872. };
  19873. Object.defineProperty(Mesh.prototype, "geometry", {
  19874. /**
  19875. * Returns the mesh internal Geometry object.
  19876. */
  19877. get: function () {
  19878. return this._geometry;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. /**
  19884. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19885. */
  19886. Mesh.prototype.getTotalVertices = function () {
  19887. if (!this._geometry) {
  19888. return 0;
  19889. }
  19890. return this._geometry.getTotalVertices();
  19891. };
  19892. /**
  19893. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19894. * 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.
  19895. * You can force the copy with forceCopy === true
  19896. * Returns null if the mesh has no geometry or no vertex buffer.
  19897. * Possible `kind` values :
  19898. * - BABYLON.VertexBuffer.PositionKind
  19899. * - BABYLON.VertexBuffer.UVKind
  19900. * - BABYLON.VertexBuffer.UV2Kind
  19901. * - BABYLON.VertexBuffer.UV3Kind
  19902. * - BABYLON.VertexBuffer.UV4Kind
  19903. * - BABYLON.VertexBuffer.UV5Kind
  19904. * - BABYLON.VertexBuffer.UV6Kind
  19905. * - BABYLON.VertexBuffer.ColorKind
  19906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19910. */
  19911. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19912. if (!this._geometry) {
  19913. return null;
  19914. }
  19915. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19916. };
  19917. /**
  19918. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19919. * Returns `undefined` if the mesh has no geometry.
  19920. * Possible `kind` values :
  19921. * - BABYLON.VertexBuffer.PositionKind
  19922. * - BABYLON.VertexBuffer.UVKind
  19923. * - BABYLON.VertexBuffer.UV2Kind
  19924. * - BABYLON.VertexBuffer.UV3Kind
  19925. * - BABYLON.VertexBuffer.UV4Kind
  19926. * - BABYLON.VertexBuffer.UV5Kind
  19927. * - BABYLON.VertexBuffer.UV6Kind
  19928. * - BABYLON.VertexBuffer.ColorKind
  19929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19933. */
  19934. Mesh.prototype.getVertexBuffer = function (kind) {
  19935. if (!this._geometry) {
  19936. return undefined;
  19937. }
  19938. return this._geometry.getVertexBuffer(kind);
  19939. };
  19940. /**
  19941. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19942. * Possible `kind` values :
  19943. * - BABYLON.VertexBuffer.PositionKind
  19944. * - BABYLON.VertexBuffer.UVKind
  19945. * - BABYLON.VertexBuffer.UV2Kind
  19946. * - BABYLON.VertexBuffer.UV3Kind
  19947. * - BABYLON.VertexBuffer.UV4Kind
  19948. * - BABYLON.VertexBuffer.UV5Kind
  19949. * - BABYLON.VertexBuffer.UV6Kind
  19950. * - BABYLON.VertexBuffer.ColorKind
  19951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19955. */
  19956. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19957. if (!this._geometry) {
  19958. if (this._delayInfo) {
  19959. return this._delayInfo.indexOf(kind) !== -1;
  19960. }
  19961. return false;
  19962. }
  19963. return this._geometry.isVerticesDataPresent(kind);
  19964. };
  19965. /**
  19966. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19967. * Possible `kind` values :
  19968. * - BABYLON.VertexBuffer.PositionKind
  19969. * - BABYLON.VertexBuffer.UVKind
  19970. * - BABYLON.VertexBuffer.UV2Kind
  19971. * - BABYLON.VertexBuffer.UV3Kind
  19972. * - BABYLON.VertexBuffer.UV4Kind
  19973. * - BABYLON.VertexBuffer.UV5Kind
  19974. * - BABYLON.VertexBuffer.UV6Kind
  19975. * - BABYLON.VertexBuffer.ColorKind
  19976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19980. */
  19981. Mesh.prototype.getVerticesDataKinds = function () {
  19982. if (!this._geometry) {
  19983. var result = [];
  19984. if (this._delayInfo) {
  19985. this._delayInfo.forEach(function (kind, index, array) {
  19986. result.push(kind);
  19987. });
  19988. }
  19989. return result;
  19990. }
  19991. return this._geometry.getVerticesDataKinds();
  19992. };
  19993. /**
  19994. * Returns a positive integer : the total number of indices in this mesh geometry.
  19995. * Returns zero if the mesh has no geometry.
  19996. */
  19997. Mesh.prototype.getTotalIndices = function () {
  19998. if (!this._geometry) {
  19999. return 0;
  20000. }
  20001. return this._geometry.getTotalIndices();
  20002. };
  20003. /**
  20004. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20005. * 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.
  20006. * Returns an empty array if the mesh has no geometry.
  20007. */
  20008. Mesh.prototype.getIndices = function (copyWhenShared) {
  20009. if (!this._geometry) {
  20010. return [];
  20011. }
  20012. return this._geometry.getIndices(copyWhenShared);
  20013. };
  20014. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20015. get: function () {
  20016. return this._masterMesh !== null && this._masterMesh !== undefined;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20023. */
  20024. Mesh.prototype.isReady = function () {
  20025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20026. return false;
  20027. }
  20028. return _super.prototype.isReady.call(this);
  20029. };
  20030. /**
  20031. * Boolean : true if the mesh has been disposed.
  20032. */
  20033. Mesh.prototype.isDisposed = function () {
  20034. return this._isDisposed;
  20035. };
  20036. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20037. get: function () {
  20038. return this._sideOrientation;
  20039. },
  20040. /**
  20041. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20042. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20043. */
  20044. set: function (sideO) {
  20045. this._sideOrientation = sideO;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20051. /**
  20052. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20053. * This property is pertinent only for updatable parametric shapes.
  20054. */
  20055. get: function () {
  20056. return this._areNormalsFrozen;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. /**
  20062. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20063. * It has no effect at all on other shapes.
  20064. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20065. * Returns the Mesh.
  20066. */
  20067. Mesh.prototype.freezeNormals = function () {
  20068. this._areNormalsFrozen = true;
  20069. return this;
  20070. };
  20071. /**
  20072. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20073. * It has no effect at all on other shapes.
  20074. * It reactivates the mesh normals computation if it was previously frozen.
  20075. * Returns the Mesh.
  20076. */
  20077. Mesh.prototype.unfreezeNormals = function () {
  20078. this._areNormalsFrozen = false;
  20079. return this;
  20080. };
  20081. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20082. /**
  20083. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20084. */
  20085. set: function (count) {
  20086. this._overridenInstanceCount = count;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. // Methods
  20092. Mesh.prototype._preActivate = function () {
  20093. var sceneRenderId = this.getScene().getRenderId();
  20094. if (this._preActivateId === sceneRenderId) {
  20095. return this;
  20096. }
  20097. this._preActivateId = sceneRenderId;
  20098. this._visibleInstances = null;
  20099. return this;
  20100. };
  20101. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20102. if (this._visibleInstances) {
  20103. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20104. }
  20105. return this;
  20106. };
  20107. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20108. if (!this._visibleInstances) {
  20109. this._visibleInstances = {};
  20110. this._visibleInstances.defaultRenderId = renderId;
  20111. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20112. }
  20113. if (!this._visibleInstances[renderId]) {
  20114. this._visibleInstances[renderId] = new Array();
  20115. }
  20116. this._visibleInstances[renderId].push(instance);
  20117. return this;
  20118. };
  20119. /**
  20120. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20121. * This means the mesh underlying bounding box and sphere are recomputed.
  20122. * Returns the Mesh.
  20123. */
  20124. Mesh.prototype.refreshBoundingInfo = function () {
  20125. if (this._boundingInfo.isLocked) {
  20126. return;
  20127. }
  20128. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20129. if (data) {
  20130. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20131. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20132. }
  20133. if (this.subMeshes) {
  20134. for (var index = 0; index < this.subMeshes.length; index++) {
  20135. this.subMeshes[index].refreshBoundingInfo();
  20136. }
  20137. }
  20138. this._updateBoundingInfo();
  20139. return this;
  20140. };
  20141. Mesh.prototype._createGlobalSubMesh = function () {
  20142. var totalVertices = this.getTotalVertices();
  20143. if (!totalVertices || !this.getIndices()) {
  20144. return null;
  20145. }
  20146. this.releaseSubMeshes();
  20147. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20148. };
  20149. Mesh.prototype.subdivide = function (count) {
  20150. if (count < 1) {
  20151. return;
  20152. }
  20153. var totalIndices = this.getTotalIndices();
  20154. var subdivisionSize = (totalIndices / count) | 0;
  20155. var offset = 0;
  20156. // Ensure that subdivisionSize is a multiple of 3
  20157. while (subdivisionSize % 3 !== 0) {
  20158. subdivisionSize++;
  20159. }
  20160. this.releaseSubMeshes();
  20161. for (var index = 0; index < count; index++) {
  20162. if (offset >= totalIndices) {
  20163. break;
  20164. }
  20165. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20166. offset += subdivisionSize;
  20167. }
  20168. this.synchronizeInstances();
  20169. };
  20170. /**
  20171. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20172. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20173. * The `data` are either a numeric array either a Float32Array.
  20174. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20175. * 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).
  20176. * Note that a new underlying VertexBuffer object is created each call.
  20177. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20178. *
  20179. * Possible `kind` values :
  20180. * - BABYLON.VertexBuffer.PositionKind
  20181. * - BABYLON.VertexBuffer.UVKind
  20182. * - BABYLON.VertexBuffer.UV2Kind
  20183. * - BABYLON.VertexBuffer.UV3Kind
  20184. * - BABYLON.VertexBuffer.UV4Kind
  20185. * - BABYLON.VertexBuffer.UV5Kind
  20186. * - BABYLON.VertexBuffer.UV6Kind
  20187. * - BABYLON.VertexBuffer.ColorKind
  20188. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20189. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20190. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20191. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20192. *
  20193. * Returns the Mesh.
  20194. */
  20195. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20196. if (!this._geometry) {
  20197. var vertexData = new BABYLON.VertexData();
  20198. vertexData.set(data, kind);
  20199. var scene = this.getScene();
  20200. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20201. }
  20202. else {
  20203. this._geometry.setVerticesData(kind, data, updatable, stride);
  20204. }
  20205. return this;
  20206. };
  20207. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20208. if (updatable === void 0) { updatable = true; }
  20209. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20210. return;
  20211. }
  20212. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20213. };
  20214. /**
  20215. * Sets the mesh VertexBuffer.
  20216. * Returns the Mesh.
  20217. */
  20218. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20219. if (!this._geometry) {
  20220. var scene = this.getScene();
  20221. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20222. }
  20223. this._geometry.setVerticesBuffer(buffer);
  20224. return this;
  20225. };
  20226. /**
  20227. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20228. * If the mesh has no geometry, it is simply returned as it is.
  20229. * The `data` are either a numeric array either a Float32Array.
  20230. * No new underlying VertexBuffer object is created.
  20231. * 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.
  20232. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20233. *
  20234. * Possible `kind` values :
  20235. * - BABYLON.VertexBuffer.PositionKind
  20236. * - BABYLON.VertexBuffer.UVKind
  20237. * - BABYLON.VertexBuffer.UV2Kind
  20238. * - BABYLON.VertexBuffer.UV3Kind
  20239. * - BABYLON.VertexBuffer.UV4Kind
  20240. * - BABYLON.VertexBuffer.UV5Kind
  20241. * - BABYLON.VertexBuffer.UV6Kind
  20242. * - BABYLON.VertexBuffer.ColorKind
  20243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20247. *
  20248. * Returns the Mesh.
  20249. */
  20250. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20251. if (!this._geometry) {
  20252. return;
  20253. }
  20254. if (!makeItUnique) {
  20255. this._geometry.updateVerticesData(kind, data, updateExtends);
  20256. }
  20257. else {
  20258. this.makeGeometryUnique();
  20259. this.updateVerticesData(kind, data, updateExtends, false);
  20260. }
  20261. return this;
  20262. };
  20263. /**
  20264. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20265. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20266. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20267. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20268. * Returns the Mesh.
  20269. */
  20270. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20271. if (computeNormals === void 0) { computeNormals = true; }
  20272. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20273. positionFunction(positions);
  20274. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20275. if (computeNormals) {
  20276. var indices = this.getIndices();
  20277. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20278. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20279. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20280. }
  20281. return this;
  20282. };
  20283. /**
  20284. * Creates a un-shared specific occurence of the geometry for the mesh.
  20285. * Returns the Mesh.
  20286. */
  20287. Mesh.prototype.makeGeometryUnique = function () {
  20288. if (!this._geometry) {
  20289. return;
  20290. }
  20291. var oldGeometry = this._geometry;
  20292. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20293. oldGeometry.releaseForMesh(this, true);
  20294. geometry.applyToMesh(this);
  20295. return this;
  20296. };
  20297. /**
  20298. * Sets the mesh indices.
  20299. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20300. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20301. * This method creates a new index buffer each call.
  20302. * Returns the Mesh.
  20303. */
  20304. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20305. if (!this._geometry) {
  20306. var vertexData = new BABYLON.VertexData();
  20307. vertexData.indices = indices;
  20308. var scene = this.getScene();
  20309. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20310. }
  20311. else {
  20312. this._geometry.setIndices(indices, totalVertices);
  20313. }
  20314. return this;
  20315. };
  20316. /**
  20317. * Invert the geometry to move from a right handed system to a left handed one.
  20318. * Returns the Mesh.
  20319. */
  20320. Mesh.prototype.toLeftHanded = function () {
  20321. if (!this._geometry) {
  20322. return;
  20323. }
  20324. this._geometry.toLeftHanded();
  20325. return this;
  20326. };
  20327. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20328. var engine = this.getScene().getEngine();
  20329. // Wireframe
  20330. var indexToBind;
  20331. if (this._unIndexed) {
  20332. indexToBind = null;
  20333. }
  20334. else {
  20335. switch (fillMode) {
  20336. case BABYLON.Material.PointFillMode:
  20337. indexToBind = null;
  20338. break;
  20339. case BABYLON.Material.WireFrameFillMode:
  20340. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20341. break;
  20342. default:
  20343. case BABYLON.Material.TriangleFillMode:
  20344. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20345. break;
  20346. }
  20347. }
  20348. // VBOs
  20349. this._geometry._bind(effect, indexToBind);
  20350. return this;
  20351. };
  20352. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20354. return this;
  20355. }
  20356. this.onBeforeDrawObservable.notifyObservers(this);
  20357. var engine = this.getScene().getEngine();
  20358. // Draw order
  20359. switch (fillMode) {
  20360. case BABYLON.Material.PointFillMode:
  20361. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20362. break;
  20363. case BABYLON.Material.WireFrameFillMode:
  20364. if (this._unIndexed) {
  20365. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20366. }
  20367. else {
  20368. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20369. }
  20370. break;
  20371. default:
  20372. if (this._unIndexed) {
  20373. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20374. }
  20375. else {
  20376. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20377. }
  20378. }
  20379. return this;
  20380. };
  20381. /**
  20382. * Registers for this mesh a javascript function called just before the rendering process.
  20383. * This function is passed the current mesh.
  20384. * Return the Mesh.
  20385. */
  20386. Mesh.prototype.registerBeforeRender = function (func) {
  20387. this.onBeforeRenderObservable.add(func);
  20388. return this;
  20389. };
  20390. /**
  20391. * Disposes a previously registered javascript function called before the rendering.
  20392. * This function is passed the current mesh.
  20393. * Returns the Mesh.
  20394. */
  20395. Mesh.prototype.unregisterBeforeRender = function (func) {
  20396. this.onBeforeRenderObservable.removeCallback(func);
  20397. return this;
  20398. };
  20399. /**
  20400. * Registers for this mesh a javascript function called just after the rendering is complete.
  20401. * This function is passed the current mesh.
  20402. * Returns the Mesh.
  20403. */
  20404. Mesh.prototype.registerAfterRender = function (func) {
  20405. this.onAfterRenderObservable.add(func);
  20406. return this;
  20407. };
  20408. /**
  20409. * Disposes a previously registered javascript function called after the rendering.
  20410. * This function is passed the current mesh.
  20411. * Return the Mesh.
  20412. */
  20413. Mesh.prototype.unregisterAfterRender = function (func) {
  20414. this.onAfterRenderObservable.removeCallback(func);
  20415. return this;
  20416. };
  20417. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20418. var scene = this.getScene();
  20419. this._batchCache.mustReturn = false;
  20420. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20421. this._batchCache.visibleInstances[subMeshId] = null;
  20422. if (this._visibleInstances) {
  20423. var currentRenderId = scene.getRenderId();
  20424. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20425. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20426. var selfRenderId = this._renderId;
  20427. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20428. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20429. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20430. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20431. }
  20432. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20433. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20434. this._batchCache.mustReturn = true;
  20435. return this._batchCache;
  20436. }
  20437. if (currentRenderId !== selfRenderId) {
  20438. this._batchCache.renderSelf[subMeshId] = false;
  20439. }
  20440. }
  20441. this._renderIdForInstances[subMeshId] = currentRenderId;
  20442. }
  20443. return this._batchCache;
  20444. };
  20445. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20446. var visibleInstances = batch.visibleInstances[subMesh._id];
  20447. var matricesCount = visibleInstances.length + 1;
  20448. var bufferSize = matricesCount * 16 * 4;
  20449. var currentInstancesBufferSize = this._instancesBufferSize;
  20450. var instancesBuffer = this._instancesBuffer;
  20451. while (this._instancesBufferSize < bufferSize) {
  20452. this._instancesBufferSize *= 2;
  20453. }
  20454. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20455. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20456. }
  20457. var offset = 0;
  20458. var instancesCount = 0;
  20459. var world = this.getWorldMatrix();
  20460. if (batch.renderSelf[subMesh._id]) {
  20461. world.copyToArray(this._instancesData, offset);
  20462. offset += 16;
  20463. instancesCount++;
  20464. }
  20465. if (visibleInstances) {
  20466. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20467. var instance = visibleInstances[instanceIndex];
  20468. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20469. offset += 16;
  20470. instancesCount++;
  20471. }
  20472. }
  20473. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20474. if (instancesBuffer) {
  20475. instancesBuffer.dispose();
  20476. }
  20477. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20478. this._instancesBuffer = instancesBuffer;
  20479. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20480. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20481. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20482. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20483. }
  20484. else {
  20485. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20486. }
  20487. this.geometry._bind(effect);
  20488. this._draw(subMesh, fillMode, instancesCount);
  20489. engine.unbindInstanceAttributes();
  20490. return this;
  20491. };
  20492. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20493. var scene = this.getScene();
  20494. var engine = scene.getEngine();
  20495. if (hardwareInstancedRendering) {
  20496. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20497. }
  20498. else {
  20499. if (batch.renderSelf[subMesh._id]) {
  20500. // Draw
  20501. if (onBeforeDraw) {
  20502. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20503. }
  20504. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20505. }
  20506. if (batch.visibleInstances[subMesh._id]) {
  20507. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20508. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20509. // World
  20510. var world = instance.getWorldMatrix();
  20511. if (onBeforeDraw) {
  20512. onBeforeDraw(true, world, effectiveMaterial);
  20513. }
  20514. // Draw
  20515. this._draw(subMesh, fillMode);
  20516. }
  20517. }
  20518. }
  20519. return this;
  20520. };
  20521. /**
  20522. * Triggers the draw call for the mesh.
  20523. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20524. * Returns the Mesh.
  20525. */
  20526. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20527. var scene = this.getScene();
  20528. // Managing instances
  20529. var batch = this._getInstancesRenderList(subMesh._id);
  20530. if (batch.mustReturn) {
  20531. return this;
  20532. }
  20533. // Checking geometry state
  20534. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20535. return this;
  20536. }
  20537. var callbackIndex;
  20538. this.onBeforeRenderObservable.notifyObservers(this);
  20539. var engine = scene.getEngine();
  20540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20541. // Material
  20542. var effectiveMaterial = subMesh.getMaterial();
  20543. if (!effectiveMaterial) {
  20544. return this;
  20545. }
  20546. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20547. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20548. return this;
  20549. }
  20550. }
  20551. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20552. return this;
  20553. }
  20554. // Alpha mode
  20555. if (enableAlphaMode) {
  20556. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20557. }
  20558. // Outline - step 1
  20559. var savedDepthWrite = engine.getDepthWrite();
  20560. if (this.renderOutline) {
  20561. engine.setDepthWrite(false);
  20562. scene.getOutlineRenderer().render(subMesh, batch);
  20563. engine.setDepthWrite(savedDepthWrite);
  20564. }
  20565. var effect;
  20566. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20567. effect = subMesh.effect;
  20568. }
  20569. else {
  20570. effect = effectiveMaterial.getEffect();
  20571. }
  20572. effectiveMaterial._preBind(effect);
  20573. // Bind
  20574. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20575. this._bind(subMesh, effect, fillMode);
  20576. var world = this.getWorldMatrix();
  20577. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20578. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20579. }
  20580. else {
  20581. effectiveMaterial.bind(world, this);
  20582. }
  20583. // Draw
  20584. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20585. // Unbind
  20586. effectiveMaterial.unbind();
  20587. // Outline - step 2
  20588. if (this.renderOutline && savedDepthWrite) {
  20589. engine.setDepthWrite(true);
  20590. engine.setColorWrite(false);
  20591. scene.getOutlineRenderer().render(subMesh, batch);
  20592. engine.setColorWrite(true);
  20593. }
  20594. // Overlay
  20595. if (this.renderOverlay) {
  20596. var currentMode = engine.getAlphaMode();
  20597. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20598. scene.getOutlineRenderer().render(subMesh, batch, true);
  20599. engine.setAlphaMode(currentMode);
  20600. }
  20601. this.onAfterRenderObservable.notifyObservers(this);
  20602. return this;
  20603. };
  20604. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20605. if (isInstance) {
  20606. effectiveMaterial.bindOnlyWorldMatrix(world);
  20607. }
  20608. return this;
  20609. };
  20610. /**
  20611. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20612. */
  20613. Mesh.prototype.getEmittedParticleSystems = function () {
  20614. var results = new Array();
  20615. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20616. var particleSystem = this.getScene().particleSystems[index];
  20617. if (particleSystem.emitter === this) {
  20618. results.push(particleSystem);
  20619. }
  20620. }
  20621. return results;
  20622. };
  20623. /**
  20624. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20625. */
  20626. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20627. var results = new Array();
  20628. var descendants = this.getDescendants();
  20629. descendants.push(this);
  20630. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20631. var particleSystem = this.getScene().particleSystems[index];
  20632. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20633. results.push(particleSystem);
  20634. }
  20635. }
  20636. return results;
  20637. };
  20638. Mesh.prototype._checkDelayState = function () {
  20639. var scene = this.getScene();
  20640. if (this._geometry) {
  20641. this._geometry.load(scene);
  20642. }
  20643. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20645. this._queueLoad(this, scene);
  20646. }
  20647. return this;
  20648. };
  20649. Mesh.prototype._queueLoad = function (mesh, scene) {
  20650. var _this = this;
  20651. scene._addPendingData(mesh);
  20652. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20653. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20654. if (data instanceof ArrayBuffer) {
  20655. _this._delayLoadingFunction(data, _this);
  20656. }
  20657. else {
  20658. _this._delayLoadingFunction(JSON.parse(data), _this);
  20659. }
  20660. _this.instances.forEach(function (instance) {
  20661. instance._syncSubMeshes();
  20662. });
  20663. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20664. scene._removePendingData(_this);
  20665. }, function () { }, scene.database, getBinaryData);
  20666. return this;
  20667. };
  20668. /**
  20669. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20670. */
  20671. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20672. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20673. return false;
  20674. }
  20675. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20676. return false;
  20677. }
  20678. this._checkDelayState();
  20679. return true;
  20680. };
  20681. /**
  20682. * Sets the mesh material by the material or multiMaterial `id` property.
  20683. * The material `id` is a string identifying the material or the multiMaterial.
  20684. * This method returns the Mesh.
  20685. */
  20686. Mesh.prototype.setMaterialByID = function (id) {
  20687. var materials = this.getScene().materials;
  20688. var index;
  20689. for (index = materials.length - 1; index > -1; index--) {
  20690. if (materials[index].id === id) {
  20691. this.material = materials[index];
  20692. return this;
  20693. }
  20694. }
  20695. // Multi
  20696. var multiMaterials = this.getScene().multiMaterials;
  20697. for (index = multiMaterials.length - 1; index > -1; index--) {
  20698. if (multiMaterials[index].id === id) {
  20699. this.material = multiMaterials[index];
  20700. return this;
  20701. }
  20702. }
  20703. return this;
  20704. };
  20705. /**
  20706. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20707. */
  20708. Mesh.prototype.getAnimatables = function () {
  20709. var results = [];
  20710. if (this.material) {
  20711. results.push(this.material);
  20712. }
  20713. if (this.skeleton) {
  20714. results.push(this.skeleton);
  20715. }
  20716. return results;
  20717. };
  20718. /**
  20719. * Modifies the mesh geometry according to the passed transformation matrix.
  20720. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20721. * The mesh normals are modified accordingly the same transformation.
  20722. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20723. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20724. * Returns the Mesh.
  20725. */
  20726. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20727. // Position
  20728. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20729. return this;
  20730. }
  20731. var submeshes = this.subMeshes.splice(0);
  20732. this._resetPointsArrayCache();
  20733. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20734. var temp = [];
  20735. var index;
  20736. for (index = 0; index < data.length; index += 3) {
  20737. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20738. }
  20739. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20740. // Normals
  20741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20742. return this;
  20743. }
  20744. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20745. temp = [];
  20746. for (index = 0; index < data.length; index += 3) {
  20747. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20748. }
  20749. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20750. // flip faces?
  20751. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20752. this.flipFaces();
  20753. }
  20754. // Restore submeshes
  20755. this.releaseSubMeshes();
  20756. this.subMeshes = submeshes;
  20757. return this;
  20758. };
  20759. /**
  20760. * Modifies the mesh geometry according to its own current World Matrix.
  20761. * The mesh World Matrix is then reset.
  20762. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20763. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20765. * Returns the Mesh.
  20766. */
  20767. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20768. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20769. this.scaling.copyFromFloats(1, 1, 1);
  20770. this.position.copyFromFloats(0, 0, 0);
  20771. this.rotation.copyFromFloats(0, 0, 0);
  20772. //only if quaternion is already set
  20773. if (this.rotationQuaternion) {
  20774. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20775. }
  20776. this._worldMatrix = BABYLON.Matrix.Identity();
  20777. return this;
  20778. };
  20779. Object.defineProperty(Mesh.prototype, "_positions", {
  20780. // Cache
  20781. get: function () {
  20782. if (this._geometry) {
  20783. return this._geometry._positions;
  20784. }
  20785. return null;
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Mesh.prototype._resetPointsArrayCache = function () {
  20791. if (this._geometry) {
  20792. this._geometry._resetPointsArrayCache();
  20793. }
  20794. return this;
  20795. };
  20796. Mesh.prototype._generatePointsArray = function () {
  20797. if (this._geometry) {
  20798. return this._geometry._generatePointsArray();
  20799. }
  20800. return false;
  20801. };
  20802. /**
  20803. * Returns a new Mesh object generated from the current mesh properties.
  20804. * This method must not get confused with createInstance().
  20805. * The parameter `name` is a string, the name given to the new mesh.
  20806. * The optional parameter `newParent` can be any Node object (default `null`).
  20807. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20808. * 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.
  20809. */
  20810. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20811. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20812. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20813. };
  20814. /**
  20815. * Disposes the mesh.
  20816. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20817. */
  20818. Mesh.prototype.dispose = function (doNotRecurse) {
  20819. var _this = this;
  20820. this.morphTargetManager = undefined;
  20821. if (this._geometry) {
  20822. this._geometry.releaseForMesh(this, true);
  20823. }
  20824. // Sources
  20825. var meshes = this.getScene().meshes;
  20826. meshes.forEach(function (mesh) {
  20827. if (mesh._source && mesh._source === _this) {
  20828. mesh._source = null;
  20829. }
  20830. });
  20831. this._source = null;
  20832. // Instances
  20833. if (this._instancesBuffer) {
  20834. this._instancesBuffer.dispose();
  20835. this._instancesBuffer = null;
  20836. }
  20837. while (this.instances.length) {
  20838. this.instances[0].dispose();
  20839. }
  20840. // Highlight layers.
  20841. var highlightLayers = this.getScene().highlightLayers;
  20842. for (var i = 0; i < highlightLayers.length; i++) {
  20843. var highlightLayer = highlightLayers[i];
  20844. if (highlightLayer) {
  20845. highlightLayer.removeMesh(this);
  20846. highlightLayer.removeExcludedMesh(this);
  20847. }
  20848. }
  20849. _super.prototype.dispose.call(this, doNotRecurse);
  20850. };
  20851. /**
  20852. * Modifies the mesh geometry according to a displacement map.
  20853. * 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.
  20854. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20855. * This method returns nothing.
  20856. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20857. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20858. * 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.
  20859. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20860. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20861. *
  20862. * Returns the Mesh.
  20863. */
  20864. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20865. var _this = this;
  20866. var scene = this.getScene();
  20867. var onload = function (img) {
  20868. // Getting height map data
  20869. var canvas = document.createElement("canvas");
  20870. var context = canvas.getContext("2d");
  20871. var heightMapWidth = img.width;
  20872. var heightMapHeight = img.height;
  20873. canvas.width = heightMapWidth;
  20874. canvas.height = heightMapHeight;
  20875. context.drawImage(img, 0, 0);
  20876. // Create VertexData from map data
  20877. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20878. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20879. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20880. //execute success callback, if set
  20881. if (onSuccess) {
  20882. onSuccess(_this);
  20883. }
  20884. };
  20885. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20886. return this;
  20887. };
  20888. /**
  20889. * Modifies the mesh geometry according to a displacementMap buffer.
  20890. * 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.
  20891. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20892. * This method returns nothing.
  20893. * 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.
  20894. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20895. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20896. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20897. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20898. *
  20899. * Returns the Mesh.
  20900. */
  20901. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20902. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20903. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20904. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20905. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20906. return this;
  20907. }
  20908. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20909. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20910. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20911. var position = BABYLON.Vector3.Zero();
  20912. var normal = BABYLON.Vector3.Zero();
  20913. var uv = BABYLON.Vector2.Zero();
  20914. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20915. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20916. for (var index = 0; index < positions.length; index += 3) {
  20917. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20918. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20919. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20920. // Compute height
  20921. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20922. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20923. var pos = (u + v * heightMapWidth) * 4;
  20924. var r = buffer[pos] / 255.0;
  20925. var g = buffer[pos + 1] / 255.0;
  20926. var b = buffer[pos + 2] / 255.0;
  20927. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20928. normal.normalize();
  20929. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20930. position = position.add(normal);
  20931. position.toArray(positions, index);
  20932. }
  20933. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20934. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20935. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20936. return this;
  20937. };
  20938. /**
  20939. * Modify the mesh to get a flat shading rendering.
  20940. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20941. * This method returns the Mesh.
  20942. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20943. */
  20944. Mesh.prototype.convertToFlatShadedMesh = function () {
  20945. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20946. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20947. var kinds = this.getVerticesDataKinds();
  20948. var vbs = [];
  20949. var data = [];
  20950. var newdata = [];
  20951. var updatableNormals = false;
  20952. var kindIndex;
  20953. var kind;
  20954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20955. kind = kinds[kindIndex];
  20956. var vertexBuffer = this.getVertexBuffer(kind);
  20957. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20958. updatableNormals = vertexBuffer.isUpdatable();
  20959. kinds.splice(kindIndex, 1);
  20960. kindIndex--;
  20961. continue;
  20962. }
  20963. vbs[kind] = vertexBuffer;
  20964. data[kind] = vbs[kind].getData();
  20965. newdata[kind] = [];
  20966. }
  20967. // Save previous submeshes
  20968. var previousSubmeshes = this.subMeshes.slice(0);
  20969. var indices = this.getIndices();
  20970. var totalIndices = this.getTotalIndices();
  20971. // Generating unique vertices per face
  20972. var index;
  20973. for (index = 0; index < totalIndices; index++) {
  20974. var vertexIndex = indices[index];
  20975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20976. kind = kinds[kindIndex];
  20977. var stride = vbs[kind].getStrideSize();
  20978. for (var offset = 0; offset < stride; offset++) {
  20979. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20980. }
  20981. }
  20982. }
  20983. // Updating faces & normal
  20984. var normals = [];
  20985. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20986. for (index = 0; index < totalIndices; index += 3) {
  20987. indices[index] = index;
  20988. indices[index + 1] = index + 1;
  20989. indices[index + 2] = index + 2;
  20990. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20991. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20992. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20993. var p1p2 = p1.subtract(p2);
  20994. var p3p2 = p3.subtract(p2);
  20995. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20996. // Store same normals for every vertex
  20997. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20998. normals.push(normal.x);
  20999. normals.push(normal.y);
  21000. normals.push(normal.z);
  21001. }
  21002. }
  21003. this.setIndices(indices);
  21004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21005. // Updating vertex buffers
  21006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21007. kind = kinds[kindIndex];
  21008. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21009. }
  21010. // Updating submeshes
  21011. this.releaseSubMeshes();
  21012. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21013. var previousOne = previousSubmeshes[submeshIndex];
  21014. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21015. }
  21016. this.synchronizeInstances();
  21017. return this;
  21018. };
  21019. /**
  21020. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21021. * In other words, more vertices, no more indices and a single bigger VBO.
  21022. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21023. * Returns the Mesh.
  21024. */
  21025. Mesh.prototype.convertToUnIndexedMesh = function () {
  21026. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21027. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21028. var kinds = this.getVerticesDataKinds();
  21029. var vbs = [];
  21030. var data = [];
  21031. var newdata = [];
  21032. var updatableNormals = false;
  21033. var kindIndex;
  21034. var kind;
  21035. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21036. kind = kinds[kindIndex];
  21037. var vertexBuffer = this.getVertexBuffer(kind);
  21038. vbs[kind] = vertexBuffer;
  21039. data[kind] = vbs[kind].getData();
  21040. newdata[kind] = [];
  21041. }
  21042. // Save previous submeshes
  21043. var previousSubmeshes = this.subMeshes.slice(0);
  21044. var indices = this.getIndices();
  21045. var totalIndices = this.getTotalIndices();
  21046. // Generating unique vertices per face
  21047. var index;
  21048. for (index = 0; index < totalIndices; index++) {
  21049. var vertexIndex = indices[index];
  21050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21051. kind = kinds[kindIndex];
  21052. var stride = vbs[kind].getStrideSize();
  21053. for (var offset = 0; offset < stride; offset++) {
  21054. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21055. }
  21056. }
  21057. }
  21058. // Updating indices
  21059. for (index = 0; index < totalIndices; index += 3) {
  21060. indices[index] = index;
  21061. indices[index + 1] = index + 1;
  21062. indices[index + 2] = index + 2;
  21063. }
  21064. this.setIndices(indices);
  21065. // Updating vertex buffers
  21066. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21067. kind = kinds[kindIndex];
  21068. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21069. }
  21070. // Updating submeshes
  21071. this.releaseSubMeshes();
  21072. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21073. var previousOne = previousSubmeshes[submeshIndex];
  21074. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21075. }
  21076. this._unIndexed = true;
  21077. this.synchronizeInstances();
  21078. return this;
  21079. };
  21080. /**
  21081. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21082. * This method returns the Mesh.
  21083. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21084. */
  21085. Mesh.prototype.flipFaces = function (flipNormals) {
  21086. if (flipNormals === void 0) { flipNormals = false; }
  21087. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21088. var i;
  21089. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21090. for (i = 0; i < vertex_data.normals.length; i++) {
  21091. vertex_data.normals[i] *= -1;
  21092. }
  21093. }
  21094. var temp;
  21095. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21096. // reassign indices
  21097. temp = vertex_data.indices[i + 1];
  21098. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21099. vertex_data.indices[i + 2] = temp;
  21100. }
  21101. vertex_data.applyToMesh(this);
  21102. return this;
  21103. };
  21104. // Instances
  21105. /**
  21106. * Creates a new InstancedMesh object from the mesh model.
  21107. * An instance shares the same properties and the same material than its model.
  21108. * Only these properties of each instance can then be set individually :
  21109. * - position
  21110. * - rotation
  21111. * - rotationQuaternion
  21112. * - setPivotMatrix
  21113. * - scaling
  21114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21115. * Warning : this method is not supported for Line mesh and LineSystem
  21116. */
  21117. Mesh.prototype.createInstance = function (name) {
  21118. return new BABYLON.InstancedMesh(name, this);
  21119. };
  21120. /**
  21121. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21122. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21123. * This method returns the Mesh.
  21124. */
  21125. Mesh.prototype.synchronizeInstances = function () {
  21126. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21127. var instance = this.instances[instanceIndex];
  21128. instance._syncSubMeshes();
  21129. }
  21130. return this;
  21131. };
  21132. /**
  21133. * Simplify the mesh according to the given array of settings.
  21134. * Function will return immediately and will simplify async. It returns the Mesh.
  21135. * @param settings a collection of simplification settings.
  21136. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21137. * @param type the type of simplification to run.
  21138. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21139. */
  21140. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21141. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21142. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21143. this.getScene().simplificationQueue.addTask({
  21144. settings: settings,
  21145. parallelProcessing: parallelProcessing,
  21146. mesh: this,
  21147. simplificationType: simplificationType,
  21148. successCallback: successCallback
  21149. });
  21150. return this;
  21151. };
  21152. /**
  21153. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21154. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21155. * This should be used together with the simplification to avoid disappearing triangles.
  21156. * Returns the Mesh.
  21157. * @param successCallback an optional success callback to be called after the optimization finished.
  21158. */
  21159. Mesh.prototype.optimizeIndices = function (successCallback) {
  21160. var _this = this;
  21161. var indices = this.getIndices();
  21162. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21163. var vectorPositions = [];
  21164. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21165. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21166. }
  21167. var dupes = [];
  21168. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21169. var realPos = vectorPositions.length - 1 - iteration;
  21170. var testedPosition = vectorPositions[realPos];
  21171. for (var j = 0; j < realPos; ++j) {
  21172. var againstPosition = vectorPositions[j];
  21173. if (testedPosition.equals(againstPosition)) {
  21174. dupes[realPos] = j;
  21175. break;
  21176. }
  21177. }
  21178. }, function () {
  21179. for (var i = 0; i < indices.length; ++i) {
  21180. indices[i] = dupes[indices[i]] || indices[i];
  21181. }
  21182. //indices are now reordered
  21183. var originalSubMeshes = _this.subMeshes.slice(0);
  21184. _this.setIndices(indices);
  21185. _this.subMeshes = originalSubMeshes;
  21186. if (successCallback) {
  21187. successCallback(_this);
  21188. }
  21189. });
  21190. return this;
  21191. };
  21192. Mesh.prototype.serialize = function (serializationObject) {
  21193. serializationObject.name = this.name;
  21194. serializationObject.id = this.id;
  21195. serializationObject.type = this.getClassName();
  21196. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21197. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21198. }
  21199. serializationObject.position = this.position.asArray();
  21200. if (this.rotationQuaternion) {
  21201. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21202. }
  21203. else if (this.rotation) {
  21204. serializationObject.rotation = this.rotation.asArray();
  21205. }
  21206. serializationObject.scaling = this.scaling.asArray();
  21207. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21208. serializationObject.isEnabled = this.isEnabled();
  21209. serializationObject.isVisible = this.isVisible;
  21210. serializationObject.infiniteDistance = this.infiniteDistance;
  21211. serializationObject.pickable = this.isPickable;
  21212. serializationObject.receiveShadows = this.receiveShadows;
  21213. serializationObject.billboardMode = this.billboardMode;
  21214. serializationObject.visibility = this.visibility;
  21215. serializationObject.checkCollisions = this.checkCollisions;
  21216. serializationObject.isBlocker = this.isBlocker;
  21217. // Parent
  21218. if (this.parent) {
  21219. serializationObject.parentId = this.parent.id;
  21220. }
  21221. // Geometry
  21222. var geometry = this._geometry;
  21223. if (geometry) {
  21224. var geometryId = geometry.id;
  21225. serializationObject.geometryId = geometryId;
  21226. // SubMeshes
  21227. serializationObject.subMeshes = [];
  21228. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21229. var subMesh = this.subMeshes[subIndex];
  21230. serializationObject.subMeshes.push({
  21231. materialIndex: subMesh.materialIndex,
  21232. verticesStart: subMesh.verticesStart,
  21233. verticesCount: subMesh.verticesCount,
  21234. indexStart: subMesh.indexStart,
  21235. indexCount: subMesh.indexCount
  21236. });
  21237. }
  21238. }
  21239. // Material
  21240. if (this.material) {
  21241. serializationObject.materialId = this.material.id;
  21242. }
  21243. else {
  21244. this.material = null;
  21245. }
  21246. // Morph targets
  21247. if (this.morphTargetManager) {
  21248. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21249. }
  21250. // Skeleton
  21251. if (this.skeleton) {
  21252. serializationObject.skeletonId = this.skeleton.id;
  21253. }
  21254. // Physics
  21255. //TODO implement correct serialization for physics impostors.
  21256. if (this.getPhysicsImpostor()) {
  21257. var impostor = this.getPhysicsImpostor();
  21258. serializationObject.physicsMass = impostor.getParam("mass");
  21259. serializationObject.physicsFriction = impostor.getParam("friction");
  21260. serializationObject.physicsRestitution = impostor.getParam("mass");
  21261. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21262. }
  21263. // Metadata
  21264. if (this.metadata) {
  21265. serializationObject.metadata = this.metadata;
  21266. }
  21267. // Instances
  21268. serializationObject.instances = [];
  21269. for (var index = 0; index < this.instances.length; index++) {
  21270. var instance = this.instances[index];
  21271. var serializationInstance = {
  21272. name: instance.name,
  21273. position: instance.position.asArray(),
  21274. scaling: instance.scaling.asArray()
  21275. };
  21276. if (instance.rotationQuaternion) {
  21277. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21278. }
  21279. else if (instance.rotation) {
  21280. serializationInstance.rotation = instance.rotation.asArray();
  21281. }
  21282. serializationObject.instances.push(serializationInstance);
  21283. // Animations
  21284. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21285. serializationInstance.ranges = instance.serializeAnimationRanges();
  21286. }
  21287. //
  21288. // Animations
  21289. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21290. serializationObject.ranges = this.serializeAnimationRanges();
  21291. // Layer mask
  21292. serializationObject.layerMask = this.layerMask;
  21293. // Alpha
  21294. serializationObject.alphaIndex = this.alphaIndex;
  21295. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21296. // Overlay
  21297. serializationObject.overlayAlpha = this.overlayAlpha;
  21298. serializationObject.overlayColor = this.overlayColor.asArray();
  21299. serializationObject.renderOverlay = this.renderOverlay;
  21300. // Fog
  21301. serializationObject.applyFog = this.applyFog;
  21302. // Action Manager
  21303. if (this.actionManager) {
  21304. serializationObject.actions = this.actionManager.serialize(this.name);
  21305. }
  21306. };
  21307. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21308. if (!this.geometry) {
  21309. return;
  21310. }
  21311. this._markSubMeshesAsAttributesDirty();
  21312. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21313. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21314. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21315. this.morphTargetManager = undefined;
  21316. return;
  21317. }
  21318. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21319. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21320. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21321. if (morphTarget.hasNormals) {
  21322. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21323. }
  21324. if (morphTarget.hasTangents) {
  21325. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21326. }
  21327. }
  21328. }
  21329. else {
  21330. var index = 0;
  21331. // Positions
  21332. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21333. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21334. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21335. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21336. }
  21337. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21338. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21339. }
  21340. index++;
  21341. }
  21342. }
  21343. };
  21344. // Statics
  21345. /**
  21346. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21347. * The parameter `parsedMesh` is the mesh to be copied.
  21348. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21349. */
  21350. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21351. var mesh;
  21352. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21353. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21354. }
  21355. else {
  21356. mesh = new Mesh(parsedMesh.name, scene);
  21357. }
  21358. mesh.id = parsedMesh.id;
  21359. if (BABYLON.Tags) {
  21360. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21361. }
  21362. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21363. if (parsedMesh.metadata !== undefined) {
  21364. mesh.metadata = parsedMesh.metadata;
  21365. }
  21366. if (parsedMesh.rotationQuaternion) {
  21367. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21368. }
  21369. else if (parsedMesh.rotation) {
  21370. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21371. }
  21372. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21373. if (parsedMesh.localMatrix) {
  21374. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21375. }
  21376. else if (parsedMesh.pivotMatrix) {
  21377. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21378. }
  21379. mesh.setEnabled(parsedMesh.isEnabled);
  21380. mesh.isVisible = parsedMesh.isVisible;
  21381. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21382. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21383. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21384. if (parsedMesh.applyFog !== undefined) {
  21385. mesh.applyFog = parsedMesh.applyFog;
  21386. }
  21387. if (parsedMesh.pickable !== undefined) {
  21388. mesh.isPickable = parsedMesh.pickable;
  21389. }
  21390. if (parsedMesh.alphaIndex !== undefined) {
  21391. mesh.alphaIndex = parsedMesh.alphaIndex;
  21392. }
  21393. mesh.receiveShadows = parsedMesh.receiveShadows;
  21394. mesh.billboardMode = parsedMesh.billboardMode;
  21395. if (parsedMesh.visibility !== undefined) {
  21396. mesh.visibility = parsedMesh.visibility;
  21397. }
  21398. mesh.checkCollisions = parsedMesh.checkCollisions;
  21399. if (parsedMesh.isBlocker !== undefined) {
  21400. mesh.isBlocker = parsedMesh.isBlocker;
  21401. }
  21402. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21403. // freezeWorldMatrix
  21404. if (parsedMesh.freezeWorldMatrix) {
  21405. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21406. }
  21407. // Parent
  21408. if (parsedMesh.parentId) {
  21409. mesh._waitingParentId = parsedMesh.parentId;
  21410. }
  21411. // Actions
  21412. if (parsedMesh.actions !== undefined) {
  21413. mesh._waitingActions = parsedMesh.actions;
  21414. }
  21415. // Overlay
  21416. if (parsedMesh.overlayAlpha !== undefined) {
  21417. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21418. }
  21419. if (parsedMesh.overlayColor !== undefined) {
  21420. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21421. }
  21422. if (parsedMesh.renderOverlay !== undefined) {
  21423. mesh.renderOverlay = parsedMesh.renderOverlay;
  21424. }
  21425. // Geometry
  21426. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21427. if (parsedMesh.delayLoadingFile) {
  21428. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21429. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21430. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21431. if (parsedMesh._binaryInfo) {
  21432. mesh._binaryInfo = parsedMesh._binaryInfo;
  21433. }
  21434. mesh._delayInfo = [];
  21435. if (parsedMesh.hasUVs) {
  21436. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21437. }
  21438. if (parsedMesh.hasUVs2) {
  21439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21440. }
  21441. if (parsedMesh.hasUVs3) {
  21442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21443. }
  21444. if (parsedMesh.hasUVs4) {
  21445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21446. }
  21447. if (parsedMesh.hasUVs5) {
  21448. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21449. }
  21450. if (parsedMesh.hasUVs6) {
  21451. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21452. }
  21453. if (parsedMesh.hasColors) {
  21454. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21455. }
  21456. if (parsedMesh.hasMatricesIndices) {
  21457. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21458. }
  21459. if (parsedMesh.hasMatricesWeights) {
  21460. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21461. }
  21462. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21463. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21464. mesh._checkDelayState();
  21465. }
  21466. }
  21467. else {
  21468. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21469. }
  21470. // Material
  21471. if (parsedMesh.materialId) {
  21472. mesh.setMaterialByID(parsedMesh.materialId);
  21473. }
  21474. else {
  21475. mesh.material = null;
  21476. }
  21477. // Morph targets
  21478. if (parsedMesh.morphTargetManagerId > -1) {
  21479. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21480. }
  21481. // Skeleton
  21482. if (parsedMesh.skeletonId > -1) {
  21483. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21484. if (parsedMesh.numBoneInfluencers) {
  21485. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21486. }
  21487. }
  21488. // Animations
  21489. if (parsedMesh.animations) {
  21490. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21491. var parsedAnimation = parsedMesh.animations[animationIndex];
  21492. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21493. }
  21494. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21495. }
  21496. if (parsedMesh.autoAnimate) {
  21497. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21498. }
  21499. // Layer Mask
  21500. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21501. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21502. }
  21503. else {
  21504. mesh.layerMask = 0x0FFFFFFF;
  21505. }
  21506. // Physics
  21507. if (parsedMesh.physicsImpostor) {
  21508. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21509. mass: parsedMesh.physicsMass,
  21510. friction: parsedMesh.physicsFriction,
  21511. restitution: parsedMesh.physicsRestitution
  21512. }, scene);
  21513. }
  21514. // Instances
  21515. if (parsedMesh.instances) {
  21516. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21517. var parsedInstance = parsedMesh.instances[index];
  21518. var instance = mesh.createInstance(parsedInstance.name);
  21519. if (BABYLON.Tags) {
  21520. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21521. }
  21522. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21523. if (parsedInstance.parentId) {
  21524. instance._waitingParentId = parsedInstance.parentId;
  21525. }
  21526. if (parsedInstance.rotationQuaternion) {
  21527. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21528. }
  21529. else if (parsedInstance.rotation) {
  21530. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21531. }
  21532. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21533. instance.checkCollisions = mesh.checkCollisions;
  21534. if (parsedMesh.animations) {
  21535. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21536. parsedAnimation = parsedMesh.animations[animationIndex];
  21537. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21538. }
  21539. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21540. }
  21541. }
  21542. }
  21543. return mesh;
  21544. };
  21545. /**
  21546. * Creates a ribbon mesh.
  21547. * Please consider using the same method from the MeshBuilder class instead.
  21548. * 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.
  21549. *
  21550. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21551. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21552. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21553. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21554. * 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.
  21555. * 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.
  21556. * 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
  21557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21560. */
  21561. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21562. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21563. pathArray: pathArray,
  21564. closeArray: closeArray,
  21565. closePath: closePath,
  21566. offset: offset,
  21567. updatable: updatable,
  21568. sideOrientation: sideOrientation,
  21569. instance: instance
  21570. }, scene);
  21571. };
  21572. /**
  21573. * Creates a plane polygonal mesh. By default, this is a disc.
  21574. * Please consider using the same method from the MeshBuilder class instead.
  21575. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21576. * 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.
  21577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21580. */
  21581. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21582. var options = {
  21583. radius: radius,
  21584. tessellation: tessellation,
  21585. sideOrientation: sideOrientation,
  21586. updatable: updatable
  21587. };
  21588. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21589. };
  21590. /**
  21591. * Creates a box mesh.
  21592. * Please consider using the same method from the MeshBuilder class instead.
  21593. * The parameter `size` sets the size (float) of each box side (default 1).
  21594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21597. */
  21598. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21599. var options = {
  21600. size: size,
  21601. sideOrientation: sideOrientation,
  21602. updatable: updatable
  21603. };
  21604. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21605. };
  21606. /**
  21607. * Creates a sphere mesh.
  21608. * Please consider using the same method from the MeshBuilder class instead.
  21609. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21610. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21614. */
  21615. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21616. var options = {
  21617. segments: segments,
  21618. diameterX: diameter,
  21619. diameterY: diameter,
  21620. diameterZ: diameter,
  21621. sideOrientation: sideOrientation,
  21622. updatable: updatable
  21623. };
  21624. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21625. };
  21626. /**
  21627. * Creates a cylinder or a cone mesh.
  21628. * Please consider using the same method from the MeshBuilder class instead.
  21629. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21630. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21631. * 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.
  21632. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21633. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21637. */
  21638. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21639. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21640. if (scene !== undefined) {
  21641. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21642. updatable = scene;
  21643. }
  21644. scene = subdivisions;
  21645. subdivisions = 1;
  21646. }
  21647. var options = {
  21648. height: height,
  21649. diameterTop: diameterTop,
  21650. diameterBottom: diameterBottom,
  21651. tessellation: tessellation,
  21652. subdivisions: subdivisions,
  21653. sideOrientation: sideOrientation,
  21654. updatable: updatable
  21655. };
  21656. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21657. };
  21658. // Torus (Code from SharpDX.org)
  21659. /**
  21660. * Creates a torus mesh.
  21661. * Please consider using the same method from the MeshBuilder class instead.
  21662. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21663. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21664. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21668. */
  21669. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21670. var options = {
  21671. diameter: diameter,
  21672. thickness: thickness,
  21673. tessellation: tessellation,
  21674. sideOrientation: sideOrientation,
  21675. updatable: updatable
  21676. };
  21677. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21678. };
  21679. /**
  21680. * Creates a torus knot mesh.
  21681. * Please consider using the same method from the MeshBuilder class instead.
  21682. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21683. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21684. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21685. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21689. */
  21690. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21691. var options = {
  21692. radius: radius,
  21693. tube: tube,
  21694. radialSegments: radialSegments,
  21695. tubularSegments: tubularSegments,
  21696. p: p,
  21697. q: q,
  21698. sideOrientation: sideOrientation,
  21699. updatable: updatable
  21700. };
  21701. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21702. };
  21703. /**
  21704. * Creates a line mesh.
  21705. * Please consider using the same method from the MeshBuilder class instead.
  21706. * 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.
  21707. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21708. * The parameter `points` is an array successive Vector3.
  21709. * 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
  21710. * When updating an instance, remember that only point positions can change, not the number of points.
  21711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21712. */
  21713. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21714. var options = {
  21715. points: points,
  21716. updatable: updatable,
  21717. instance: instance
  21718. };
  21719. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21720. };
  21721. /**
  21722. * Creates a dashed line mesh.
  21723. * Please consider using the same method from the MeshBuilder class instead.
  21724. * 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.
  21725. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21726. * The parameter `points` is an array successive Vector3.
  21727. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21728. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21729. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21730. * 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
  21731. * When updating an instance, remember that only point positions can change, not the number of points.
  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.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21735. var options = {
  21736. points: points,
  21737. dashSize: dashSize,
  21738. gapSize: gapSize,
  21739. dashNb: dashNb,
  21740. updatable: updatable,
  21741. instance: instance
  21742. };
  21743. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21744. };
  21745. /**
  21746. * Creates a polygon mesh.
  21747. * Please consider using the same method from the MeshBuilder class instead.
  21748. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21749. * 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.
  21750. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21752. * Remember you can only change the shape positions, not their number when updating a polygon.
  21753. */
  21754. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21755. var options = {
  21756. shape: shape,
  21757. holes: holes,
  21758. updatable: updatable,
  21759. sideOrientation: sideOrientation
  21760. };
  21761. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates an extruded polygon mesh, with depth in the Y direction.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. */
  21767. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21768. var options = {
  21769. shape: shape,
  21770. holes: holes,
  21771. depth: depth,
  21772. updatable: updatable,
  21773. sideOrientation: sideOrientation
  21774. };
  21775. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21776. };
  21777. /**
  21778. * Creates an extruded shape mesh.
  21779. * 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.
  21780. * Please consider using the same method from the MeshBuilder class instead.
  21781. *
  21782. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21783. * 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
  21784. * extruded along the Z axis.
  21785. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21786. * 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.
  21787. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21788. * 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
  21789. * 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
  21790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21794. */
  21795. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21796. var options = {
  21797. shape: shape,
  21798. path: path,
  21799. scale: scale,
  21800. rotation: rotation,
  21801. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21802. sideOrientation: sideOrientation,
  21803. instance: instance,
  21804. updatable: updatable
  21805. };
  21806. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21807. };
  21808. /**
  21809. * Creates an custom extruded shape mesh.
  21810. * 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.
  21811. * Please consider using the same method from the MeshBuilder class instead.
  21812. *
  21813. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21814. * 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
  21815. * extruded along the Z axis.
  21816. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21817. * 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
  21818. * and the distance of this point from the begining of the path :
  21819. * ```javascript
  21820. * var rotationFunction = function(i, distance) {
  21821. * // do things
  21822. * return rotationValue; }
  21823. * ```
  21824. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21825. * 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
  21826. * and the distance of this point from the begining of the path :
  21827. * ```javascript
  21828. * var scaleFunction = function(i, distance) {
  21829. * // do things
  21830. * return scaleValue;}
  21831. * ```
  21832. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21833. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21834. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21835. * 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
  21836. * 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
  21837. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  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.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21843. var options = {
  21844. shape: shape,
  21845. path: path,
  21846. scaleFunction: scaleFunction,
  21847. rotationFunction: rotationFunction,
  21848. ribbonCloseArray: ribbonCloseArray,
  21849. ribbonClosePath: ribbonClosePath,
  21850. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21851. sideOrientation: sideOrientation,
  21852. instance: instance,
  21853. updatable: updatable
  21854. };
  21855. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21856. };
  21857. /**
  21858. * Creates lathe mesh.
  21859. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21860. * Please consider using the same method from the MeshBuilder class instead.
  21861. * 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
  21862. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21863. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21864. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21865. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21868. */
  21869. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21870. var options = {
  21871. shape: shape,
  21872. radius: radius,
  21873. tessellation: tessellation,
  21874. sideOrientation: sideOrientation,
  21875. updatable: updatable
  21876. };
  21877. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21878. };
  21879. /**
  21880. * Creates a plane mesh.
  21881. * Please consider using the same method from the MeshBuilder class instead.
  21882. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21884. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21886. */
  21887. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21888. var options = {
  21889. size: size,
  21890. width: size,
  21891. height: size,
  21892. sideOrientation: sideOrientation,
  21893. updatable: updatable
  21894. };
  21895. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21896. };
  21897. /**
  21898. * Creates a ground mesh.
  21899. * Please consider using the same method from the MeshBuilder class instead.
  21900. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21901. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21903. */
  21904. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21905. var options = {
  21906. width: width,
  21907. height: height,
  21908. subdivisions: subdivisions,
  21909. updatable: updatable
  21910. };
  21911. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21912. };
  21913. /**
  21914. * Creates a tiled ground mesh.
  21915. * Please consider using the same method from the MeshBuilder class instead.
  21916. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21917. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21918. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21919. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21920. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21921. * numbers of subdivisions on the ground width and height of each tile.
  21922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21923. */
  21924. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21925. var options = {
  21926. xmin: xmin,
  21927. zmin: zmin,
  21928. xmax: xmax,
  21929. zmax: zmax,
  21930. subdivisions: subdivisions,
  21931. precision: precision,
  21932. updatable: updatable
  21933. };
  21934. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21935. };
  21936. /**
  21937. * Creates a ground mesh from a height map.
  21938. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21939. * Please consider using the same method from the MeshBuilder class instead.
  21940. * The parameter `url` sets the URL of the height map image resource.
  21941. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21942. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21943. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21944. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21945. * 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).
  21946. * This function is passed the newly built mesh :
  21947. * ```javascript
  21948. * function(mesh) { // do things
  21949. * return; }
  21950. * ```
  21951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21952. */
  21953. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21954. var options = {
  21955. width: width,
  21956. height: height,
  21957. subdivisions: subdivisions,
  21958. minHeight: minHeight,
  21959. maxHeight: maxHeight,
  21960. updatable: updatable,
  21961. onReady: onReady
  21962. };
  21963. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21964. };
  21965. /**
  21966. * Creates a tube mesh.
  21967. * 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.
  21968. * Please consider using the same method from the MeshBuilder class instead.
  21969. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21970. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21971. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21972. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21973. * 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.
  21974. * It must return a radius value (positive float) :
  21975. * ```javascript
  21976. * var radiusFunction = function(i, distance) {
  21977. * // do things
  21978. * return radius; }
  21979. * ```
  21980. * 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
  21981. * 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
  21982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21985. */
  21986. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21987. var options = {
  21988. path: path,
  21989. radius: radius,
  21990. tessellation: tessellation,
  21991. radiusFunction: radiusFunction,
  21992. arc: 1,
  21993. cap: cap,
  21994. updatable: updatable,
  21995. sideOrientation: sideOrientation,
  21996. instance: instance
  21997. };
  21998. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21999. };
  22000. /**
  22001. * Creates a polyhedron mesh.
  22002. * Please consider using the same method from the MeshBuilder class instead.
  22003. * 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
  22004. * to choose the wanted type.
  22005. * The parameter `size` (positive float, default 1) sets the polygon size.
  22006. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22007. * 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`.
  22008. * 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
  22009. * 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)`).
  22010. * 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
  22011. * 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.
  22012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22015. */
  22016. Mesh.CreatePolyhedron = function (name, options, scene) {
  22017. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22018. };
  22019. /**
  22020. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22021. * Please consider using the same method from the MeshBuilder class instead.
  22022. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22023. * 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`).
  22024. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22025. * 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.
  22026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22029. */
  22030. Mesh.CreateIcoSphere = function (name, options, scene) {
  22031. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22032. };
  22033. /**
  22034. * Creates a decal mesh.
  22035. * Please consider using the same method from the MeshBuilder class instead.
  22036. * 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.
  22037. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22038. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22039. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22040. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22041. */
  22042. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22043. var options = {
  22044. position: position,
  22045. normal: normal,
  22046. size: size,
  22047. angle: angle
  22048. };
  22049. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22050. };
  22051. // Skeletons
  22052. /**
  22053. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22054. */
  22055. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22056. var source;
  22057. if (!this._sourcePositions) {
  22058. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22059. this._sourcePositions = new Float32Array(source);
  22060. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22061. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22062. }
  22063. }
  22064. return this._sourcePositions;
  22065. };
  22066. /**
  22067. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22068. */
  22069. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22070. var source;
  22071. if (!this._sourceNormals) {
  22072. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22073. this._sourceNormals = new Float32Array(source);
  22074. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22075. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22076. }
  22077. }
  22078. return this._sourceNormals;
  22079. };
  22080. /**
  22081. * Updates the vertex buffer by applying transformation from the bones.
  22082. * Returns the Mesh.
  22083. *
  22084. * @param {skeleton} skeleton to apply
  22085. */
  22086. Mesh.prototype.applySkeleton = function (skeleton) {
  22087. if (!this.geometry) {
  22088. return this;
  22089. }
  22090. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22091. return this;
  22092. }
  22093. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22095. return this;
  22096. }
  22097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22098. return this;
  22099. }
  22100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22101. return this;
  22102. }
  22103. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22104. return this;
  22105. }
  22106. if (!this._sourcePositions) {
  22107. var submeshes = this.subMeshes.slice();
  22108. this.setPositionsForCPUSkinning();
  22109. this.subMeshes = submeshes;
  22110. }
  22111. if (!this._sourceNormals) {
  22112. this.setNormalsForCPUSkinning();
  22113. }
  22114. // positionsData checks for not being Float32Array will only pass at most once
  22115. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22116. if (!(positionsData instanceof Float32Array)) {
  22117. positionsData = new Float32Array(positionsData);
  22118. }
  22119. // normalsData checks for not being Float32Array will only pass at most once
  22120. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22121. if (!(normalsData instanceof Float32Array)) {
  22122. normalsData = new Float32Array(normalsData);
  22123. }
  22124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22126. var needExtras = this.numBoneInfluencers > 4;
  22127. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22128. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22129. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22130. var tempVector3 = BABYLON.Vector3.Zero();
  22131. var finalMatrix = new BABYLON.Matrix();
  22132. var tempMatrix = new BABYLON.Matrix();
  22133. var matWeightIdx = 0;
  22134. var inf;
  22135. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22136. var weight;
  22137. for (inf = 0; inf < 4; inf++) {
  22138. weight = matricesWeightsData[matWeightIdx + inf];
  22139. if (weight > 0) {
  22140. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22141. finalMatrix.addToSelf(tempMatrix);
  22142. }
  22143. else
  22144. break;
  22145. }
  22146. if (needExtras) {
  22147. for (inf = 0; inf < 4; inf++) {
  22148. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22149. if (weight > 0) {
  22150. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22151. finalMatrix.addToSelf(tempMatrix);
  22152. }
  22153. else
  22154. break;
  22155. }
  22156. }
  22157. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22158. tempVector3.toArray(positionsData, index);
  22159. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22160. tempVector3.toArray(normalsData, index);
  22161. finalMatrix.reset();
  22162. }
  22163. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22164. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22165. return this;
  22166. };
  22167. // Tools
  22168. /**
  22169. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22170. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22171. */
  22172. Mesh.MinMax = function (meshes) {
  22173. var minVector = null;
  22174. var maxVector = null;
  22175. meshes.forEach(function (mesh, index, array) {
  22176. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22177. if (!minVector) {
  22178. minVector = boundingBox.minimumWorld;
  22179. maxVector = boundingBox.maximumWorld;
  22180. }
  22181. else {
  22182. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22183. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22184. }
  22185. });
  22186. return {
  22187. min: minVector,
  22188. max: maxVector
  22189. };
  22190. };
  22191. /**
  22192. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22193. */
  22194. Mesh.Center = function (meshesOrMinMaxVector) {
  22195. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22196. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22197. };
  22198. /**
  22199. * Merge the array of meshes into a single mesh for performance reasons.
  22200. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22201. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22202. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22203. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22204. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22205. */
  22206. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22207. if (disposeSource === void 0) { disposeSource = true; }
  22208. var index;
  22209. if (!allow32BitsIndices) {
  22210. var totalVertices = 0;
  22211. // Counting vertices
  22212. for (index = 0; index < meshes.length; index++) {
  22213. if (meshes[index]) {
  22214. totalVertices += meshes[index].getTotalVertices();
  22215. if (totalVertices > 65536) {
  22216. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22217. return null;
  22218. }
  22219. }
  22220. }
  22221. }
  22222. // Merge
  22223. var vertexData;
  22224. var otherVertexData;
  22225. var indiceArray = new Array();
  22226. var source;
  22227. for (index = 0; index < meshes.length; index++) {
  22228. if (meshes[index]) {
  22229. meshes[index].computeWorldMatrix(true);
  22230. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22231. otherVertexData.transform(meshes[index].getWorldMatrix());
  22232. if (vertexData) {
  22233. vertexData.merge(otherVertexData);
  22234. }
  22235. else {
  22236. vertexData = otherVertexData;
  22237. source = meshes[index];
  22238. }
  22239. if (subdivideWithSubMeshes) {
  22240. indiceArray.push(meshes[index].getTotalIndices());
  22241. }
  22242. }
  22243. }
  22244. if (!meshSubclass) {
  22245. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22246. }
  22247. vertexData.applyToMesh(meshSubclass);
  22248. // Setting properties
  22249. meshSubclass.material = source.material;
  22250. meshSubclass.checkCollisions = source.checkCollisions;
  22251. // Cleaning
  22252. if (disposeSource) {
  22253. for (index = 0; index < meshes.length; index++) {
  22254. if (meshes[index]) {
  22255. meshes[index].dispose();
  22256. }
  22257. }
  22258. }
  22259. // Subdivide
  22260. if (subdivideWithSubMeshes) {
  22261. //-- Suppresions du submesh global
  22262. meshSubclass.releaseSubMeshes();
  22263. index = 0;
  22264. var offset = 0;
  22265. //-- aplique la subdivision en fonction du tableau d'indices
  22266. while (index < indiceArray.length) {
  22267. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22268. offset += indiceArray[index];
  22269. index++;
  22270. }
  22271. }
  22272. return meshSubclass;
  22273. };
  22274. return Mesh;
  22275. }(BABYLON.AbstractMesh));
  22276. // Consts
  22277. Mesh._FRONTSIDE = 0;
  22278. Mesh._BACKSIDE = 1;
  22279. Mesh._DOUBLESIDE = 2;
  22280. Mesh._DEFAULTSIDE = 0;
  22281. Mesh._NO_CAP = 0;
  22282. Mesh._CAP_START = 1;
  22283. Mesh._CAP_END = 2;
  22284. Mesh._CAP_ALL = 3;
  22285. BABYLON.Mesh = Mesh;
  22286. })(BABYLON || (BABYLON = {}));
  22287. //# sourceMappingURL=babylon.mesh.js.map
  22288. var BABYLON;
  22289. (function (BABYLON) {
  22290. var BaseSubMesh = (function () {
  22291. function BaseSubMesh() {
  22292. }
  22293. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22294. get: function () {
  22295. return this._materialEffect;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22301. if (this._materialEffect === effect) {
  22302. return;
  22303. }
  22304. this._materialDefines = defines;
  22305. this._materialEffect = effect;
  22306. };
  22307. return BaseSubMesh;
  22308. }());
  22309. BABYLON.BaseSubMesh = BaseSubMesh;
  22310. var SubMesh = (function (_super) {
  22311. __extends(SubMesh, _super);
  22312. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22313. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22314. var _this = _super.call(this) || this;
  22315. _this.materialIndex = materialIndex;
  22316. _this.verticesStart = verticesStart;
  22317. _this.verticesCount = verticesCount;
  22318. _this.indexStart = indexStart;
  22319. _this.indexCount = indexCount;
  22320. _this._renderId = 0;
  22321. _this._mesh = mesh;
  22322. _this._renderingMesh = renderingMesh || mesh;
  22323. mesh.subMeshes.push(_this);
  22324. _this._trianglePlanes = [];
  22325. _this._id = mesh.subMeshes.length - 1;
  22326. if (createBoundingBox) {
  22327. _this.refreshBoundingInfo();
  22328. mesh.computeWorldMatrix(true);
  22329. }
  22330. return _this;
  22331. }
  22332. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22333. get: function () {
  22334. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Returns the submesh BoudingInfo object.
  22341. */
  22342. SubMesh.prototype.getBoundingInfo = function () {
  22343. if (this.IsGlobal) {
  22344. return this._mesh.getBoundingInfo();
  22345. }
  22346. return this._boundingInfo;
  22347. };
  22348. /**
  22349. * Sets the submesh BoundingInfo.
  22350. * Return the SubMesh.
  22351. */
  22352. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22353. this._boundingInfo = boundingInfo;
  22354. return this;
  22355. };
  22356. /**
  22357. * Returns the mesh of the current submesh.
  22358. */
  22359. SubMesh.prototype.getMesh = function () {
  22360. return this._mesh;
  22361. };
  22362. /**
  22363. * Returns the rendering mesh of the submesh.
  22364. */
  22365. SubMesh.prototype.getRenderingMesh = function () {
  22366. return this._renderingMesh;
  22367. };
  22368. /**
  22369. * Returns the submesh material.
  22370. */
  22371. SubMesh.prototype.getMaterial = function () {
  22372. var rootMaterial = this._renderingMesh.material;
  22373. if (rootMaterial && rootMaterial.getSubMaterial) {
  22374. var multiMaterial = rootMaterial;
  22375. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22376. if (this._currentMaterial !== effectiveMaterial) {
  22377. this._currentMaterial = effectiveMaterial;
  22378. if (this._materialDefines) {
  22379. this._materialDefines.markAllAsDirty();
  22380. }
  22381. }
  22382. return effectiveMaterial;
  22383. }
  22384. if (!rootMaterial) {
  22385. return this._mesh.getScene().defaultMaterial;
  22386. }
  22387. return rootMaterial;
  22388. };
  22389. // Methods
  22390. /**
  22391. * Sets a new updated BoundingInfo object to the submesh.
  22392. * Returns the SubMesh.
  22393. */
  22394. SubMesh.prototype.refreshBoundingInfo = function () {
  22395. this._lastColliderWorldVertices = null;
  22396. if (this.IsGlobal) {
  22397. return;
  22398. }
  22399. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22400. if (!data) {
  22401. this._boundingInfo = this._mesh._boundingInfo;
  22402. return;
  22403. }
  22404. var indices = this._renderingMesh.getIndices();
  22405. var extend;
  22406. //is this the only submesh?
  22407. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22408. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22409. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22410. }
  22411. else {
  22412. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22413. }
  22414. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22415. return this;
  22416. };
  22417. SubMesh.prototype._checkCollision = function (collider) {
  22418. return this.getBoundingInfo()._checkCollision(collider);
  22419. };
  22420. /**
  22421. * Updates the submesh BoundingInfo.
  22422. * Returns the Submesh.
  22423. */
  22424. SubMesh.prototype.updateBoundingInfo = function (world) {
  22425. if (!this.getBoundingInfo()) {
  22426. this.refreshBoundingInfo();
  22427. }
  22428. this.getBoundingInfo().update(world);
  22429. return this;
  22430. };
  22431. /**
  22432. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22433. * Boolean returned.
  22434. */
  22435. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22436. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22437. };
  22438. /**
  22439. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22440. * Boolean returned.
  22441. */
  22442. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22443. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22444. };
  22445. /**
  22446. * Renders the submesh.
  22447. * Returns it.
  22448. */
  22449. SubMesh.prototype.render = function (enableAlphaMode) {
  22450. this._renderingMesh.render(this, enableAlphaMode);
  22451. return this;
  22452. };
  22453. /**
  22454. * Returns a new Index Buffer.
  22455. * Type returned : WebGLBuffer.
  22456. */
  22457. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22458. if (!this._linesIndexBuffer) {
  22459. var linesIndices = [];
  22460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22461. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22462. }
  22463. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22464. this.linesIndexCount = linesIndices.length;
  22465. }
  22466. return this._linesIndexBuffer;
  22467. };
  22468. /**
  22469. * True is the passed Ray intersects the submesh bounding box.
  22470. * Boolean returned.
  22471. */
  22472. SubMesh.prototype.canIntersects = function (ray) {
  22473. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22474. };
  22475. /**
  22476. * Returns an object IntersectionInfo.
  22477. */
  22478. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22479. var intersectInfo = null;
  22480. // LineMesh first as it's also a Mesh...
  22481. if (this._mesh instanceof BABYLON.LinesMesh) {
  22482. var lineMesh = this._mesh;
  22483. // Line test
  22484. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22485. var p0 = positions[indices[index]];
  22486. var p1 = positions[indices[index + 1]];
  22487. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22488. if (length < 0) {
  22489. continue;
  22490. }
  22491. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22492. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22493. if (fastCheck) {
  22494. break;
  22495. }
  22496. }
  22497. }
  22498. }
  22499. else {
  22500. // Triangles test
  22501. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22502. var p0 = positions[indices[index]];
  22503. var p1 = positions[indices[index + 1]];
  22504. var p2 = positions[indices[index + 2]];
  22505. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22506. if (currentIntersectInfo) {
  22507. if (currentIntersectInfo.distance < 0) {
  22508. continue;
  22509. }
  22510. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22511. intersectInfo = currentIntersectInfo;
  22512. intersectInfo.faceId = index / 3;
  22513. if (fastCheck) {
  22514. break;
  22515. }
  22516. }
  22517. }
  22518. }
  22519. }
  22520. return intersectInfo;
  22521. };
  22522. // Clone
  22523. /**
  22524. * Creates a new Submesh from the passed Mesh.
  22525. */
  22526. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22527. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22528. if (!this.IsGlobal) {
  22529. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22530. }
  22531. return result;
  22532. };
  22533. // Dispose
  22534. /**
  22535. * Disposes the Submesh.
  22536. * Returns nothing.
  22537. */
  22538. SubMesh.prototype.dispose = function () {
  22539. if (this._linesIndexBuffer) {
  22540. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22541. this._linesIndexBuffer = null;
  22542. }
  22543. // Remove from mesh
  22544. var index = this._mesh.subMeshes.indexOf(this);
  22545. this._mesh.subMeshes.splice(index, 1);
  22546. };
  22547. // Statics
  22548. /**
  22549. * Creates a new Submesh from the passed parameters :
  22550. * - materialIndex (integer) : the index of the main mesh material.
  22551. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22552. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22553. * - mesh (Mesh) : the main mesh to create the submesh from.
  22554. * - renderingMesh (optional Mesh) : rendering mesh.
  22555. */
  22556. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22557. var minVertexIndex = Number.MAX_VALUE;
  22558. var maxVertexIndex = -Number.MAX_VALUE;
  22559. renderingMesh = renderingMesh || mesh;
  22560. var indices = renderingMesh.getIndices();
  22561. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22562. var vertexIndex = indices[index];
  22563. if (vertexIndex < minVertexIndex)
  22564. minVertexIndex = vertexIndex;
  22565. if (vertexIndex > maxVertexIndex)
  22566. maxVertexIndex = vertexIndex;
  22567. }
  22568. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22569. };
  22570. return SubMesh;
  22571. }(BaseSubMesh));
  22572. BABYLON.SubMesh = SubMesh;
  22573. })(BABYLON || (BABYLON = {}));
  22574. //# sourceMappingURL=babylon.subMesh.js.map
  22575. var BABYLON;
  22576. (function (BABYLON) {
  22577. var EffectFallbacks = (function () {
  22578. function EffectFallbacks() {
  22579. this._defines = {};
  22580. this._currentRank = 32;
  22581. this._maxRank = -1;
  22582. }
  22583. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22584. if (!this._defines[rank]) {
  22585. if (rank < this._currentRank) {
  22586. this._currentRank = rank;
  22587. }
  22588. if (rank > this._maxRank) {
  22589. this._maxRank = rank;
  22590. }
  22591. this._defines[rank] = new Array();
  22592. }
  22593. this._defines[rank].push(define);
  22594. };
  22595. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22596. this._meshRank = rank;
  22597. this._mesh = mesh;
  22598. if (rank < this._currentRank) {
  22599. this._currentRank = rank;
  22600. }
  22601. if (rank > this._maxRank) {
  22602. this._maxRank = rank;
  22603. }
  22604. };
  22605. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22606. get: function () {
  22607. return this._currentRank <= this._maxRank;
  22608. },
  22609. enumerable: true,
  22610. configurable: true
  22611. });
  22612. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22613. // First we try to switch to CPU skinning
  22614. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22615. this._mesh.computeBonesUsingShaders = false;
  22616. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22617. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22618. var scene = this._mesh.getScene();
  22619. for (var index = 0; index < scene.meshes.length; index++) {
  22620. var otherMesh = scene.meshes[index];
  22621. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22622. otherMesh.computeBonesUsingShaders = false;
  22623. }
  22624. }
  22625. }
  22626. else {
  22627. var currentFallbacks = this._defines[this._currentRank];
  22628. if (currentFallbacks) {
  22629. for (var index = 0; index < currentFallbacks.length; index++) {
  22630. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22631. }
  22632. }
  22633. this._currentRank++;
  22634. }
  22635. return currentDefines;
  22636. };
  22637. return EffectFallbacks;
  22638. }());
  22639. BABYLON.EffectFallbacks = EffectFallbacks;
  22640. var EffectCreationOptions = (function () {
  22641. function EffectCreationOptions() {
  22642. }
  22643. return EffectCreationOptions;
  22644. }());
  22645. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22646. var Effect = (function () {
  22647. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22648. var _this = this;
  22649. this.uniqueId = 0;
  22650. this.onCompileObservable = new BABYLON.Observable();
  22651. this.onErrorObservable = new BABYLON.Observable();
  22652. this.onBindObservable = new BABYLON.Observable();
  22653. this._uniformBuffersNames = {};
  22654. this._isReady = false;
  22655. this._compilationError = "";
  22656. this._valueCache = {};
  22657. this.name = baseName;
  22658. if (attributesNamesOrOptions.attributes) {
  22659. var options = attributesNamesOrOptions;
  22660. this._engine = uniformsNamesOrEngine;
  22661. this._attributesNames = options.attributes;
  22662. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22663. this._samplers = options.samplers;
  22664. this.defines = options.defines;
  22665. this.onError = options.onError;
  22666. this.onCompiled = options.onCompiled;
  22667. this._fallbacks = options.fallbacks;
  22668. this._indexParameters = options.indexParameters;
  22669. if (options.uniformBuffersNames) {
  22670. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22671. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22672. }
  22673. }
  22674. }
  22675. else {
  22676. this._engine = engine;
  22677. this.defines = defines;
  22678. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22679. this._samplers = samplers;
  22680. this._attributesNames = attributesNamesOrOptions;
  22681. this.onError = onError;
  22682. this.onCompiled = onCompiled;
  22683. this._indexParameters = indexParameters;
  22684. this._fallbacks = fallbacks;
  22685. }
  22686. this.uniqueId = Effect._uniqueIdSeed++;
  22687. var vertexSource;
  22688. var fragmentSource;
  22689. if (baseName.vertexElement) {
  22690. vertexSource = document.getElementById(baseName.vertexElement);
  22691. if (!vertexSource) {
  22692. vertexSource = baseName.vertexElement;
  22693. }
  22694. }
  22695. else {
  22696. vertexSource = baseName.vertex || baseName;
  22697. }
  22698. if (baseName.fragmentElement) {
  22699. fragmentSource = document.getElementById(baseName.fragmentElement);
  22700. if (!fragmentSource) {
  22701. fragmentSource = baseName.fragmentElement;
  22702. }
  22703. }
  22704. else {
  22705. fragmentSource = baseName.fragment || baseName;
  22706. }
  22707. this._loadVertexShader(vertexSource, function (vertexCode) {
  22708. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22709. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22710. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22711. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22712. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22713. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22714. });
  22715. });
  22716. });
  22717. });
  22718. });
  22719. });
  22720. }
  22721. Object.defineProperty(Effect.prototype, "key", {
  22722. get: function () {
  22723. return this._key;
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. // Properties
  22729. Effect.prototype.isReady = function () {
  22730. return this._isReady;
  22731. };
  22732. Effect.prototype.getEngine = function () {
  22733. return this._engine;
  22734. };
  22735. Effect.prototype.getProgram = function () {
  22736. return this._program;
  22737. };
  22738. Effect.prototype.getAttributesNames = function () {
  22739. return this._attributesNames;
  22740. };
  22741. Effect.prototype.getAttributeLocation = function (index) {
  22742. return this._attributes[index];
  22743. };
  22744. Effect.prototype.getAttributeLocationByName = function (name) {
  22745. var index = this._attributesNames.indexOf(name);
  22746. return this._attributes[index];
  22747. };
  22748. Effect.prototype.getAttributesCount = function () {
  22749. return this._attributes.length;
  22750. };
  22751. Effect.prototype.getUniformIndex = function (uniformName) {
  22752. return this._uniformsNames.indexOf(uniformName);
  22753. };
  22754. Effect.prototype.getUniform = function (uniformName) {
  22755. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22756. };
  22757. Effect.prototype.getSamplers = function () {
  22758. return this._samplers;
  22759. };
  22760. Effect.prototype.getCompilationError = function () {
  22761. return this._compilationError;
  22762. };
  22763. Effect.prototype.getVertexShaderSource = function () {
  22764. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22765. };
  22766. Effect.prototype.getFragmentShaderSource = function () {
  22767. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22768. };
  22769. // Methods
  22770. Effect.prototype.executeWhenCompiled = function (func) {
  22771. var _this = this;
  22772. if (this.isReady()) {
  22773. func(this);
  22774. return;
  22775. }
  22776. var observer = this.onCompileObservable.add(function (effect) {
  22777. _this.onCompileObservable.remove(observer);
  22778. func(effect);
  22779. });
  22780. };
  22781. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22782. // DOM element ?
  22783. if (vertex instanceof HTMLElement) {
  22784. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22785. callback(vertexCode);
  22786. return;
  22787. }
  22788. // Base64 encoded ?
  22789. if (vertex.substr(0, 7) === "base64:") {
  22790. var vertexBinary = window.atob(vertex.substr(7));
  22791. callback(vertexBinary);
  22792. return;
  22793. }
  22794. // Is in local store ?
  22795. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22796. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22797. return;
  22798. }
  22799. var vertexShaderUrl;
  22800. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22801. vertexShaderUrl = vertex;
  22802. }
  22803. else {
  22804. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22805. }
  22806. // Vertex shader
  22807. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22808. };
  22809. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22810. // DOM element ?
  22811. if (fragment instanceof HTMLElement) {
  22812. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22813. callback(fragmentCode);
  22814. return;
  22815. }
  22816. // Base64 encoded ?
  22817. if (fragment.substr(0, 7) === "base64:") {
  22818. var fragmentBinary = window.atob(fragment.substr(7));
  22819. callback(fragmentBinary);
  22820. return;
  22821. }
  22822. // Is in local store ?
  22823. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22824. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22825. return;
  22826. }
  22827. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22828. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22829. return;
  22830. }
  22831. var fragmentShaderUrl;
  22832. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22833. fragmentShaderUrl = fragment;
  22834. }
  22835. else {
  22836. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22837. }
  22838. // Fragment shader
  22839. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22840. };
  22841. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22842. // Rebuild shaders source code
  22843. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22844. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22845. vertexCode = prefix + vertexCode;
  22846. fragmentCode = prefix + fragmentCode;
  22847. // Number lines of shaders source code
  22848. var i = 2;
  22849. var regex = /\n/gm;
  22850. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22851. i = 2;
  22852. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22853. // Dump shaders name and formatted source code
  22854. if (this.name.vertexElement) {
  22855. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22856. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22857. }
  22858. else if (this.name.vertex) {
  22859. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22860. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22861. }
  22862. else {
  22863. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22864. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22865. }
  22866. };
  22867. ;
  22868. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22869. var preparedSourceCode = this._processPrecision(sourceCode);
  22870. if (this._engine.webGLVersion == 1) {
  22871. callback(preparedSourceCode);
  22872. return;
  22873. }
  22874. // Already converted
  22875. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22876. callback(preparedSourceCode.replace("#version 300 es", ""));
  22877. return;
  22878. }
  22879. // Remove extensions
  22880. // #extension GL_OES_standard_derivatives : enable
  22881. // #extension GL_EXT_shader_texture_lod : enable
  22882. // #extension GL_EXT_frag_depth : enable
  22883. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22884. var result = preparedSourceCode.replace(regex, "");
  22885. // Migrate to GLSL v300
  22886. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22887. result = result.replace(/attribute[ \t]/g, "in ");
  22888. result = result.replace(/[ \t]attribute/g, " in");
  22889. if (isFragment) {
  22890. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22891. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22892. result = result.replace(/texture2D\(/g, "texture(");
  22893. result = result.replace(/textureCube\(/g, "texture(");
  22894. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22895. result = result.replace(/gl_FragColor/g, "glFragColor");
  22896. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22897. }
  22898. callback(result);
  22899. };
  22900. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22901. var _this = this;
  22902. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22903. var match = regex.exec(sourceCode);
  22904. var returnValue = new String(sourceCode);
  22905. while (match != null) {
  22906. var includeFile = match[1];
  22907. // Uniform declaration
  22908. if (includeFile.indexOf("__decl__") !== -1) {
  22909. includeFile = includeFile.replace(/__decl__/, "");
  22910. if (this._engine.webGLVersion != 1) {
  22911. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22912. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22913. }
  22914. includeFile = includeFile + "Declaration";
  22915. }
  22916. if (Effect.IncludesShadersStore[includeFile]) {
  22917. // Substitution
  22918. var includeContent = Effect.IncludesShadersStore[includeFile];
  22919. if (match[2]) {
  22920. var splits = match[3].split(",");
  22921. for (var index = 0; index < splits.length; index += 2) {
  22922. var source = new RegExp(splits[index], "g");
  22923. var dest = splits[index + 1];
  22924. includeContent = includeContent.replace(source, dest);
  22925. }
  22926. }
  22927. if (match[4]) {
  22928. var indexString = match[5];
  22929. if (indexString.indexOf("..") !== -1) {
  22930. var indexSplits = indexString.split("..");
  22931. var minIndex = parseInt(indexSplits[0]);
  22932. var maxIndex = parseInt(indexSplits[1]);
  22933. var sourceIncludeContent = includeContent.slice(0);
  22934. includeContent = "";
  22935. if (isNaN(maxIndex)) {
  22936. maxIndex = this._indexParameters[indexSplits[1]];
  22937. }
  22938. for (var i = minIndex; i < maxIndex; i++) {
  22939. if (this._engine.webGLVersion === 1) {
  22940. // Ubo replacement
  22941. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22942. return p1 + "{X}";
  22943. });
  22944. }
  22945. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22946. }
  22947. }
  22948. else {
  22949. if (this._engine.webGLVersion === 1) {
  22950. // Ubo replacement
  22951. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22952. return p1 + "{X}";
  22953. });
  22954. }
  22955. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22956. }
  22957. }
  22958. // Replace
  22959. returnValue = returnValue.replace(match[0], includeContent);
  22960. }
  22961. else {
  22962. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22963. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22964. Effect.IncludesShadersStore[includeFile] = fileContent;
  22965. _this._processIncludes(returnValue, callback);
  22966. });
  22967. return;
  22968. }
  22969. match = regex.exec(sourceCode);
  22970. }
  22971. callback(returnValue);
  22972. };
  22973. Effect.prototype._processPrecision = function (source) {
  22974. if (source.indexOf("precision highp float") === -1) {
  22975. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22976. source = "precision mediump float;\n" + source;
  22977. }
  22978. else {
  22979. source = "precision highp float;\n" + source;
  22980. }
  22981. }
  22982. else {
  22983. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22984. source = source.replace("precision highp float", "precision mediump float");
  22985. }
  22986. }
  22987. return source;
  22988. };
  22989. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22990. try {
  22991. var engine = this._engine;
  22992. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22993. if (engine.webGLVersion > 1) {
  22994. for (var name in this._uniformBuffersNames) {
  22995. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22996. }
  22997. }
  22998. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22999. this._attributes = engine.getAttributes(this._program, attributesNames);
  23000. var index;
  23001. for (index = 0; index < this._samplers.length; index++) {
  23002. var sampler = this.getUniform(this._samplers[index]);
  23003. if (sampler == null) {
  23004. this._samplers.splice(index, 1);
  23005. index--;
  23006. }
  23007. }
  23008. engine.bindSamplers(this);
  23009. this._compilationError = "";
  23010. this._isReady = true;
  23011. if (this.onCompiled) {
  23012. this.onCompiled(this);
  23013. }
  23014. this.onCompileObservable.notifyObservers(this);
  23015. }
  23016. catch (e) {
  23017. this._compilationError = e.message;
  23018. // Let's go through fallbacks then
  23019. BABYLON.Tools.Error("Unable to compile effect:");
  23020. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23021. return " " + uniform;
  23022. }));
  23023. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23024. return " " + attribute;
  23025. }));
  23026. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23027. BABYLON.Tools.Error("Error: " + this._compilationError);
  23028. if (fallbacks && fallbacks.isMoreFallbacks) {
  23029. BABYLON.Tools.Error("Trying next fallback.");
  23030. defines = fallbacks.reduce(defines);
  23031. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23032. }
  23033. else {
  23034. if (this.onError) {
  23035. this.onError(this, this._compilationError);
  23036. }
  23037. this.onErrorObservable.notifyObservers(this);
  23038. }
  23039. }
  23040. };
  23041. Object.defineProperty(Effect.prototype, "isSupported", {
  23042. get: function () {
  23043. return this._compilationError === "";
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Effect.prototype._bindTexture = function (channel, texture) {
  23049. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23050. };
  23051. Effect.prototype.setTexture = function (channel, texture) {
  23052. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23053. };
  23054. Effect.prototype.setTextureArray = function (channel, textures) {
  23055. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23056. var initialPos = this._samplers.indexOf(channel);
  23057. for (var index = 1; index < textures.length; index++) {
  23058. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23059. }
  23060. }
  23061. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23062. };
  23063. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23064. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23065. };
  23066. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23067. var cache = this._valueCache[uniformName];
  23068. var flag = matrix.updateFlag;
  23069. if (cache !== undefined && cache === flag) {
  23070. return false;
  23071. }
  23072. this._valueCache[uniformName] = flag;
  23073. return true;
  23074. };
  23075. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23076. var cache = this._valueCache[uniformName];
  23077. if (!cache) {
  23078. cache = [x, y];
  23079. this._valueCache[uniformName] = cache;
  23080. return true;
  23081. }
  23082. var changed = false;
  23083. if (cache[0] !== x) {
  23084. cache[0] = x;
  23085. changed = true;
  23086. }
  23087. if (cache[1] !== y) {
  23088. cache[1] = y;
  23089. changed = true;
  23090. }
  23091. return changed;
  23092. };
  23093. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23094. var cache = this._valueCache[uniformName];
  23095. if (!cache) {
  23096. cache = [x, y, z];
  23097. this._valueCache[uniformName] = cache;
  23098. return true;
  23099. }
  23100. var changed = false;
  23101. if (cache[0] !== x) {
  23102. cache[0] = x;
  23103. changed = true;
  23104. }
  23105. if (cache[1] !== y) {
  23106. cache[1] = y;
  23107. changed = true;
  23108. }
  23109. if (cache[2] !== z) {
  23110. cache[2] = z;
  23111. changed = true;
  23112. }
  23113. return changed;
  23114. };
  23115. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23116. var cache = this._valueCache[uniformName];
  23117. if (!cache) {
  23118. cache = [x, y, z, w];
  23119. this._valueCache[uniformName] = cache;
  23120. return true;
  23121. }
  23122. var changed = false;
  23123. if (cache[0] !== x) {
  23124. cache[0] = x;
  23125. changed = true;
  23126. }
  23127. if (cache[1] !== y) {
  23128. cache[1] = y;
  23129. changed = true;
  23130. }
  23131. if (cache[2] !== z) {
  23132. cache[2] = z;
  23133. changed = true;
  23134. }
  23135. if (cache[3] !== w) {
  23136. cache[3] = w;
  23137. changed = true;
  23138. }
  23139. return changed;
  23140. };
  23141. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23142. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23143. return;
  23144. }
  23145. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23146. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23147. };
  23148. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23149. this._engine.bindUniformBlock(this._program, blockName, index);
  23150. };
  23151. Effect.prototype.setIntArray = function (uniformName, array) {
  23152. this._valueCache[uniformName] = null;
  23153. this._engine.setIntArray(this.getUniform(uniformName), array);
  23154. return this;
  23155. };
  23156. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23157. this._valueCache[uniformName] = null;
  23158. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23159. return this;
  23160. };
  23161. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23162. this._valueCache[uniformName] = null;
  23163. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23164. return this;
  23165. };
  23166. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23167. this._valueCache[uniformName] = null;
  23168. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23169. return this;
  23170. };
  23171. Effect.prototype.setFloatArray = function (uniformName, array) {
  23172. this._valueCache[uniformName] = null;
  23173. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23174. return this;
  23175. };
  23176. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23177. this._valueCache[uniformName] = null;
  23178. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23179. return this;
  23180. };
  23181. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23182. this._valueCache[uniformName] = null;
  23183. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23184. return this;
  23185. };
  23186. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23187. this._valueCache[uniformName] = null;
  23188. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23189. return this;
  23190. };
  23191. Effect.prototype.setArray = function (uniformName, array) {
  23192. this._valueCache[uniformName] = null;
  23193. this._engine.setArray(this.getUniform(uniformName), array);
  23194. return this;
  23195. };
  23196. Effect.prototype.setArray2 = function (uniformName, array) {
  23197. this._valueCache[uniformName] = null;
  23198. this._engine.setArray2(this.getUniform(uniformName), array);
  23199. return this;
  23200. };
  23201. Effect.prototype.setArray3 = function (uniformName, array) {
  23202. this._valueCache[uniformName] = null;
  23203. this._engine.setArray3(this.getUniform(uniformName), array);
  23204. return this;
  23205. };
  23206. Effect.prototype.setArray4 = function (uniformName, array) {
  23207. this._valueCache[uniformName] = null;
  23208. this._engine.setArray4(this.getUniform(uniformName), array);
  23209. return this;
  23210. };
  23211. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23212. if (!matrices) {
  23213. return;
  23214. }
  23215. this._valueCache[uniformName] = null;
  23216. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23217. return this;
  23218. };
  23219. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23220. if (this._cacheMatrix(uniformName, matrix)) {
  23221. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23222. }
  23223. return this;
  23224. };
  23225. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23226. this._valueCache[uniformName] = null;
  23227. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23228. return this;
  23229. };
  23230. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23231. this._valueCache[uniformName] = null;
  23232. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23233. return this;
  23234. };
  23235. Effect.prototype.setFloat = function (uniformName, value) {
  23236. var cache = this._valueCache[uniformName];
  23237. if (cache !== undefined && cache === value)
  23238. return this;
  23239. this._valueCache[uniformName] = value;
  23240. this._engine.setFloat(this.getUniform(uniformName), value);
  23241. return this;
  23242. };
  23243. Effect.prototype.setBool = function (uniformName, bool) {
  23244. var cache = this._valueCache[uniformName];
  23245. if (cache !== undefined && cache === bool)
  23246. return this;
  23247. this._valueCache[uniformName] = bool;
  23248. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23249. return this;
  23250. };
  23251. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23252. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23253. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23254. }
  23255. return this;
  23256. };
  23257. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23258. if (this._cacheFloat2(uniformName, x, y)) {
  23259. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23260. }
  23261. return this;
  23262. };
  23263. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23264. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23265. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23266. }
  23267. return this;
  23268. };
  23269. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23270. if (this._cacheFloat3(uniformName, x, y, z)) {
  23271. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23272. }
  23273. return this;
  23274. };
  23275. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23276. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23277. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23278. }
  23279. return this;
  23280. };
  23281. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23282. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23283. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23284. }
  23285. return this;
  23286. };
  23287. Effect.prototype.setColor3 = function (uniformName, color3) {
  23288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23289. this._engine.setColor3(this.getUniform(uniformName), color3);
  23290. }
  23291. return this;
  23292. };
  23293. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23294. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23295. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23296. }
  23297. return this;
  23298. };
  23299. Effect.prototype._recombineShader = function (node) {
  23300. if (node.define) {
  23301. if (node.condition) {
  23302. var defineIndex = this.defines.indexOf("#define " + node.define);
  23303. if (defineIndex === -1) {
  23304. return null;
  23305. }
  23306. var nextComma = this.defines.indexOf("\n", defineIndex);
  23307. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23308. var condition = defineValue + node.condition;
  23309. if (!eval(condition)) {
  23310. return null;
  23311. }
  23312. }
  23313. else if (node.ndef) {
  23314. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23315. return null;
  23316. }
  23317. }
  23318. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23319. return null;
  23320. }
  23321. }
  23322. var result = "";
  23323. for (var index = 0; index < node.children.length; index++) {
  23324. var line = node.children[index];
  23325. if (line.children) {
  23326. var combined = this._recombineShader(line);
  23327. if (combined !== null) {
  23328. result += combined + "\r\n";
  23329. }
  23330. continue;
  23331. }
  23332. if (line.length > 0) {
  23333. result += line + "\r\n";
  23334. }
  23335. }
  23336. return result;
  23337. };
  23338. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23339. var root = {
  23340. children: []
  23341. };
  23342. var currentNode = root;
  23343. var lines = shaderString.split("\n");
  23344. for (var index = 0; index < lines.length; index++) {
  23345. var line = lines[index].trim();
  23346. // #ifdef
  23347. var pos = line.indexOf("#ifdef ");
  23348. if (pos !== -1) {
  23349. var define = line.substr(pos + 7);
  23350. var newNode = {
  23351. condition: null,
  23352. ndef: false,
  23353. define: define,
  23354. children: [],
  23355. parent: currentNode
  23356. };
  23357. currentNode.children.push(newNode);
  23358. currentNode = newNode;
  23359. continue;
  23360. }
  23361. // #ifndef
  23362. var pos = line.indexOf("#ifndef ");
  23363. if (pos !== -1) {
  23364. var define = line.substr(pos + 8);
  23365. newNode = {
  23366. condition: null,
  23367. define: define,
  23368. ndef: true,
  23369. children: [],
  23370. parent: currentNode
  23371. };
  23372. currentNode.children.push(newNode);
  23373. currentNode = newNode;
  23374. continue;
  23375. }
  23376. // #if
  23377. var pos = line.indexOf("#if ");
  23378. if (pos !== -1) {
  23379. var define = line.substr(pos + 4).trim();
  23380. var conditionPos = define.indexOf(" ");
  23381. newNode = {
  23382. condition: define.substr(conditionPos + 1),
  23383. define: define.substr(0, conditionPos),
  23384. ndef: false,
  23385. children: [],
  23386. parent: currentNode
  23387. };
  23388. currentNode.children.push(newNode);
  23389. currentNode = newNode;
  23390. continue;
  23391. }
  23392. // #endif
  23393. pos = line.indexOf("#endif");
  23394. if (pos !== -1) {
  23395. currentNode = currentNode.parent;
  23396. continue;
  23397. }
  23398. currentNode.children.push(line);
  23399. }
  23400. // Recombine
  23401. return this._recombineShader(root);
  23402. };
  23403. return Effect;
  23404. }());
  23405. Effect._uniqueIdSeed = 0;
  23406. Effect._baseCache = {};
  23407. // Statics
  23408. Effect.ShadersStore = {};
  23409. Effect.IncludesShadersStore = {};
  23410. BABYLON.Effect = Effect;
  23411. })(BABYLON || (BABYLON = {}));
  23412. //# sourceMappingURL=babylon.effect.js.map
  23413. var BABYLON;
  23414. (function (BABYLON) {
  23415. var MaterialHelper = (function () {
  23416. function MaterialHelper() {
  23417. }
  23418. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23419. if (defines._areMiscDirty) {
  23420. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23421. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23422. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23423. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23424. }
  23425. };
  23426. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23427. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23428. var changed = false;
  23429. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23430. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23431. changed = true;
  23432. }
  23433. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23434. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23435. changed = true;
  23436. }
  23437. if (defines["INSTANCES"] !== useInstances) {
  23438. defines["INSTANCES"] = useInstances;
  23439. changed = true;
  23440. }
  23441. if (changed) {
  23442. defines.markAsUnprocessed();
  23443. }
  23444. };
  23445. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23446. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23447. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23448. return false;
  23449. }
  23450. defines._normals = defines._needNormals;
  23451. defines._uvs = defines._needUVs;
  23452. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23453. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23454. defines["TANGENT"] = true;
  23455. }
  23456. if (defines._needUVs) {
  23457. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23458. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23459. }
  23460. else {
  23461. defines["UV1"] = false;
  23462. defines["UV2"] = false;
  23463. }
  23464. if (useVertexColor) {
  23465. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23466. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23467. }
  23468. if (useBones) {
  23469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23470. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23471. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23472. }
  23473. else {
  23474. defines["NUM_BONE_INFLUENCERS"] = 0;
  23475. defines["BonesPerMesh"] = 0;
  23476. }
  23477. }
  23478. if (useMorphTargets) {
  23479. if (mesh.morphTargetManager) {
  23480. var manager = mesh.morphTargetManager;
  23481. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23482. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23483. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23484. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23485. }
  23486. else {
  23487. defines["MORPHTARGETS_TANGENT"] = false;
  23488. defines["MORPHTARGETS_NORMAL"] = false;
  23489. defines["MORPHTARGETS"] = false;
  23490. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23491. }
  23492. }
  23493. return true;
  23494. };
  23495. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23497. if (disableLighting === void 0) { disableLighting = false; }
  23498. if (!defines._areLightsDirty) {
  23499. return defines._needNormals;
  23500. }
  23501. var lightIndex = 0;
  23502. var needNormals = false;
  23503. var needRebuild = false;
  23504. var lightmapMode = false;
  23505. var shadowEnabled = false;
  23506. var specularEnabled = false;
  23507. if (scene.lightsEnabled && !disableLighting) {
  23508. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23509. var light = _a[_i];
  23510. needNormals = true;
  23511. if (defines["LIGHT" + lightIndex] === undefined) {
  23512. needRebuild = true;
  23513. }
  23514. defines["LIGHT" + lightIndex] = true;
  23515. defines["SPOTLIGHT" + lightIndex] = false;
  23516. defines["HEMILIGHT" + lightIndex] = false;
  23517. defines["POINTLIGHT" + lightIndex] = false;
  23518. defines["DIRLIGHT" + lightIndex] = false;
  23519. var type;
  23520. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23521. type = "SPOTLIGHT" + lightIndex;
  23522. }
  23523. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23524. type = "HEMILIGHT" + lightIndex;
  23525. }
  23526. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23527. type = "POINTLIGHT" + lightIndex;
  23528. }
  23529. else {
  23530. type = "DIRLIGHT" + lightIndex;
  23531. }
  23532. defines[type] = true;
  23533. // Specular
  23534. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23535. specularEnabled = true;
  23536. }
  23537. // Shadows
  23538. defines["SHADOW" + lightIndex] = false;
  23539. defines["SHADOWPCF" + lightIndex] = false;
  23540. defines["SHADOWESM" + lightIndex] = false;
  23541. defines["SHADOWCUBE" + lightIndex] = false;
  23542. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23543. var shadowGenerator = light.getShadowGenerator();
  23544. if (shadowGenerator) {
  23545. shadowEnabled = true;
  23546. shadowGenerator.prepareDefines(defines, lightIndex);
  23547. }
  23548. }
  23549. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23550. lightmapMode = true;
  23551. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23552. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23553. }
  23554. else {
  23555. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23556. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23557. }
  23558. lightIndex++;
  23559. if (lightIndex === maxSimultaneousLights)
  23560. break;
  23561. }
  23562. }
  23563. defines["SPECULARTERM"] = specularEnabled;
  23564. defines["SHADOWS"] = shadowEnabled;
  23565. // Resetting all other lights if any
  23566. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23567. if (defines["LIGHT" + index] !== undefined) {
  23568. defines["LIGHT" + index] = false;
  23569. defines["HEMILIGHT" + lightIndex] = false;
  23570. defines["POINTLIGHT" + lightIndex] = false;
  23571. defines["DIRLIGHT" + lightIndex] = false;
  23572. defines["SPOTLIGHT" + lightIndex] = false;
  23573. defines["SHADOW" + lightIndex] = false;
  23574. }
  23575. }
  23576. var caps = scene.getEngine().getCaps();
  23577. if (defines["SHADOWFLOAT"] === undefined) {
  23578. needRebuild = true;
  23579. }
  23580. defines["SHADOWFLOAT"] = shadowEnabled &&
  23581. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23582. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23583. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23584. if (needRebuild) {
  23585. defines.rebuild();
  23586. }
  23587. return needNormals;
  23588. };
  23589. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23590. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23591. var uniformsList, uniformBuffersList, samplersList, defines;
  23592. if (uniformsListOrOptions.uniformsNames) {
  23593. var options = uniformsListOrOptions;
  23594. uniformsList = options.uniformsNames;
  23595. uniformBuffersList = options.uniformBuffersNames;
  23596. samplersList = options.samplers;
  23597. defines = options.defines;
  23598. maxSimultaneousLights = options.maxSimultaneousLights;
  23599. }
  23600. else {
  23601. uniformsList = uniformsListOrOptions;
  23602. }
  23603. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23604. if (!defines["LIGHT" + lightIndex]) {
  23605. break;
  23606. }
  23607. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23608. if (uniformBuffersList) {
  23609. uniformBuffersList.push("Light" + lightIndex);
  23610. }
  23611. samplersList.push("shadowSampler" + lightIndex);
  23612. }
  23613. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23614. uniformsList.push("morphTargetInfluences");
  23615. }
  23616. };
  23617. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23618. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23619. if (!defines["SHADOWS"]) {
  23620. return;
  23621. }
  23622. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23623. if (!defines["LIGHT" + lightIndex]) {
  23624. break;
  23625. }
  23626. if (lightIndex > 0) {
  23627. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23628. }
  23629. if (defines["SHADOW" + lightIndex]) {
  23630. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23631. }
  23632. if (defines["SHADOWPCF" + lightIndex]) {
  23633. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23634. }
  23635. if (defines["SHADOWESM" + lightIndex]) {
  23636. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23637. }
  23638. }
  23639. };
  23640. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23641. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23642. if (influencers > 0) {
  23643. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23644. var manager = mesh.morphTargetManager;
  23645. var normal = manager.supportsNormals && defines["NORMAL"];
  23646. var tangent = manager.supportsTangents && defines["TANGENT"];
  23647. for (var index = 0; index < influencers; index++) {
  23648. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23649. if (normal) {
  23650. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23651. }
  23652. if (tangent) {
  23653. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23654. }
  23655. if (attribs.length > maxAttributesCount) {
  23656. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23657. }
  23658. }
  23659. }
  23660. };
  23661. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23662. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23663. fallbacks.addCPUSkinningFallback(0, mesh);
  23664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23666. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23669. }
  23670. }
  23671. };
  23672. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23673. if (defines["INSTANCES"]) {
  23674. attribs.push("world0");
  23675. attribs.push("world1");
  23676. attribs.push("world2");
  23677. attribs.push("world3");
  23678. }
  23679. };
  23680. // Bindings
  23681. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23682. if (light.shadowEnabled && mesh.receiveShadows) {
  23683. var shadowGenerator = light.getShadowGenerator();
  23684. if (shadowGenerator) {
  23685. shadowGenerator.bindShadowLight(lightIndex, effect);
  23686. }
  23687. }
  23688. };
  23689. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23690. light.transferToEffect(effect, lightIndex + "");
  23691. };
  23692. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23693. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23694. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23695. var lightIndex = 0;
  23696. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23697. var light = _a[_i];
  23698. var scaledIntensity = light.getScaledIntensity();
  23699. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23700. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23701. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23702. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23703. if (defines["SPECULARTERM"]) {
  23704. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23705. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23706. }
  23707. // Shadows
  23708. if (scene.shadowsEnabled) {
  23709. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23710. }
  23711. light._uniformBuffer.update();
  23712. lightIndex++;
  23713. if (lightIndex === maxSimultaneousLights)
  23714. break;
  23715. }
  23716. };
  23717. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23718. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23719. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23720. effect.setColor3("vFogColor", scene.fogColor);
  23721. }
  23722. };
  23723. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23724. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23725. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23726. if (matrices) {
  23727. effect.setMatrices("mBones", matrices);
  23728. }
  23729. }
  23730. };
  23731. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23732. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23733. return;
  23734. }
  23735. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23736. };
  23737. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23738. if (defines["LOGARITHMICDEPTH"]) {
  23739. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23740. }
  23741. };
  23742. MaterialHelper.BindClipPlane = function (effect, scene) {
  23743. if (scene.clipPlane) {
  23744. var clipPlane = scene.clipPlane;
  23745. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23746. }
  23747. };
  23748. return MaterialHelper;
  23749. }());
  23750. BABYLON.MaterialHelper = MaterialHelper;
  23751. })(BABYLON || (BABYLON = {}));
  23752. //# sourceMappingURL=babylon.materialHelper.js.map
  23753. var BABYLON;
  23754. (function (BABYLON) {
  23755. var MaterialDefines = (function () {
  23756. function MaterialDefines() {
  23757. this._isDirty = true;
  23758. this._areLightsDirty = true;
  23759. this._areAttributesDirty = true;
  23760. this._areTexturesDirty = true;
  23761. this._areFresnelDirty = true;
  23762. this._areMiscDirty = true;
  23763. this._normals = false;
  23764. this._uvs = false;
  23765. this._needNormals = false;
  23766. this._needUVs = false;
  23767. }
  23768. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23769. get: function () {
  23770. return this._isDirty;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. MaterialDefines.prototype.markAsProcessed = function () {
  23776. this._isDirty = false;
  23777. this._areAttributesDirty = false;
  23778. this._areTexturesDirty = false;
  23779. this._areFresnelDirty = false;
  23780. this._areLightsDirty = false;
  23781. this._areMiscDirty = false;
  23782. };
  23783. MaterialDefines.prototype.markAsUnprocessed = function () {
  23784. this._isDirty = true;
  23785. };
  23786. MaterialDefines.prototype.markAllAsDirty = function () {
  23787. this._areTexturesDirty = true;
  23788. this._areAttributesDirty = true;
  23789. this._areLightsDirty = true;
  23790. this._areFresnelDirty = true;
  23791. this._areMiscDirty = true;
  23792. this._isDirty = true;
  23793. };
  23794. MaterialDefines.prototype.markAsLightDirty = function () {
  23795. this._areLightsDirty = true;
  23796. this._isDirty = true;
  23797. };
  23798. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23799. this._areAttributesDirty = true;
  23800. this._isDirty = true;
  23801. };
  23802. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23803. this._areTexturesDirty = true;
  23804. this._isDirty = true;
  23805. };
  23806. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23807. this._areFresnelDirty = true;
  23808. this._isDirty = true;
  23809. };
  23810. MaterialDefines.prototype.markAsMiscDirty = function () {
  23811. this._areMiscDirty = true;
  23812. this._isDirty = true;
  23813. };
  23814. MaterialDefines.prototype.rebuild = function () {
  23815. if (this._keys) {
  23816. delete this._keys;
  23817. }
  23818. this._keys = [];
  23819. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23820. var key = _a[_i];
  23821. if (key[0] === "_") {
  23822. continue;
  23823. }
  23824. this._keys.push(key);
  23825. }
  23826. };
  23827. MaterialDefines.prototype.isEqual = function (other) {
  23828. if (this._keys.length !== other._keys.length) {
  23829. return false;
  23830. }
  23831. for (var index = 0; index < this._keys.length; index++) {
  23832. var prop = this._keys[index];
  23833. if (this[prop] !== other[prop]) {
  23834. return false;
  23835. }
  23836. }
  23837. return true;
  23838. };
  23839. MaterialDefines.prototype.cloneTo = function (other) {
  23840. if (this._keys.length !== other._keys.length) {
  23841. other._keys = this._keys.slice(0);
  23842. }
  23843. for (var index = 0; index < this._keys.length; index++) {
  23844. var prop = this._keys[index];
  23845. other[prop] = this[prop];
  23846. }
  23847. };
  23848. MaterialDefines.prototype.reset = function () {
  23849. for (var index = 0; index < this._keys.length; index++) {
  23850. var prop = this._keys[index];
  23851. if (typeof (this[prop]) === "number") {
  23852. this[prop] = 0;
  23853. }
  23854. else {
  23855. this[prop] = false;
  23856. }
  23857. }
  23858. };
  23859. MaterialDefines.prototype.toString = function () {
  23860. var result = "";
  23861. for (var index = 0; index < this._keys.length; index++) {
  23862. var prop = this._keys[index];
  23863. var value = this[prop];
  23864. if (typeof (value) === "number") {
  23865. result += "#define " + prop + " " + this[prop] + "\n";
  23866. }
  23867. else if (value) {
  23868. result += "#define " + prop + "\n";
  23869. }
  23870. }
  23871. return result;
  23872. };
  23873. return MaterialDefines;
  23874. }());
  23875. BABYLON.MaterialDefines = MaterialDefines;
  23876. var Material = (function () {
  23877. function Material(name, scene, doNotAdd) {
  23878. this.checkReadyOnEveryCall = false;
  23879. this.checkReadyOnlyOnce = false;
  23880. this.state = "";
  23881. this.alpha = 1.0;
  23882. this._backFaceCulling = true;
  23883. this.doNotSerialize = false;
  23884. this.storeEffectOnSubMeshes = false;
  23885. /**
  23886. * An event triggered when the material is disposed.
  23887. * @type {BABYLON.Observable}
  23888. */
  23889. this.onDisposeObservable = new BABYLON.Observable();
  23890. /**
  23891. * An event triggered when the material is bound.
  23892. * @type {BABYLON.Observable}
  23893. */
  23894. this.onBindObservable = new BABYLON.Observable();
  23895. /**
  23896. * An event triggered when the material is unbound.
  23897. * @type {BABYLON.Observable}
  23898. */
  23899. this.onUnBindObservable = new BABYLON.Observable();
  23900. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23901. this.disableDepthWrite = false;
  23902. this._fogEnabled = true;
  23903. this.pointSize = 1.0;
  23904. this.zOffset = 0;
  23905. this._wasPreviouslyReady = false;
  23906. this._fillMode = Material.TriangleFillMode;
  23907. this.name = name;
  23908. this.id = name;
  23909. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23910. if (this._scene.useRightHandedSystem) {
  23911. this.sideOrientation = Material.ClockWiseSideOrientation;
  23912. }
  23913. else {
  23914. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23915. }
  23916. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23917. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23918. if (!doNotAdd) {
  23919. this._scene.materials.push(this);
  23920. }
  23921. }
  23922. Object.defineProperty(Material, "TriangleFillMode", {
  23923. get: function () {
  23924. return Material._TriangleFillMode;
  23925. },
  23926. enumerable: true,
  23927. configurable: true
  23928. });
  23929. Object.defineProperty(Material, "WireFrameFillMode", {
  23930. get: function () {
  23931. return Material._WireFrameFillMode;
  23932. },
  23933. enumerable: true,
  23934. configurable: true
  23935. });
  23936. Object.defineProperty(Material, "PointFillMode", {
  23937. get: function () {
  23938. return Material._PointFillMode;
  23939. },
  23940. enumerable: true,
  23941. configurable: true
  23942. });
  23943. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23944. get: function () {
  23945. return Material._ClockWiseSideOrientation;
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23951. get: function () {
  23952. return Material._CounterClockWiseSideOrientation;
  23953. },
  23954. enumerable: true,
  23955. configurable: true
  23956. });
  23957. Object.defineProperty(Material, "TextureDirtyFlag", {
  23958. get: function () {
  23959. return Material._TextureDirtyFlag;
  23960. },
  23961. enumerable: true,
  23962. configurable: true
  23963. });
  23964. Object.defineProperty(Material, "LightDirtyFlag", {
  23965. get: function () {
  23966. return Material._LightDirtyFlag;
  23967. },
  23968. enumerable: true,
  23969. configurable: true
  23970. });
  23971. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23972. get: function () {
  23973. return Material._FresnelDirtyFlag;
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23979. get: function () {
  23980. return Material._AttributesDirtyFlag;
  23981. },
  23982. enumerable: true,
  23983. configurable: true
  23984. });
  23985. Object.defineProperty(Material, "MiscDirtyFlag", {
  23986. get: function () {
  23987. return Material._MiscDirtyFlag;
  23988. },
  23989. enumerable: true,
  23990. configurable: true
  23991. });
  23992. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23993. get: function () {
  23994. return this._backFaceCulling;
  23995. },
  23996. set: function (value) {
  23997. if (this._backFaceCulling === value) {
  23998. return;
  23999. }
  24000. this._backFaceCulling = value;
  24001. this.markAsDirty(Material.TextureDirtyFlag);
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. Object.defineProperty(Material.prototype, "onDispose", {
  24007. set: function (callback) {
  24008. if (this._onDisposeObserver) {
  24009. this.onDisposeObservable.remove(this._onDisposeObserver);
  24010. }
  24011. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. Object.defineProperty(Material.prototype, "onBind", {
  24017. set: function (callback) {
  24018. if (this._onBindObserver) {
  24019. this.onBindObservable.remove(this._onBindObserver);
  24020. }
  24021. this._onBindObserver = this.onBindObservable.add(callback);
  24022. },
  24023. enumerable: true,
  24024. configurable: true
  24025. });
  24026. Object.defineProperty(Material.prototype, "fogEnabled", {
  24027. get: function () {
  24028. return this._fogEnabled;
  24029. },
  24030. set: function (value) {
  24031. if (this._fogEnabled === value) {
  24032. return;
  24033. }
  24034. this._fogEnabled = value;
  24035. this.markAsDirty(Material.MiscDirtyFlag);
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(Material.prototype, "wireframe", {
  24041. get: function () {
  24042. return this._fillMode === Material.WireFrameFillMode;
  24043. },
  24044. set: function (value) {
  24045. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24046. },
  24047. enumerable: true,
  24048. configurable: true
  24049. });
  24050. Object.defineProperty(Material.prototype, "pointsCloud", {
  24051. get: function () {
  24052. return this._fillMode === Material.PointFillMode;
  24053. },
  24054. set: function (value) {
  24055. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(Material.prototype, "fillMode", {
  24061. get: function () {
  24062. return this._fillMode;
  24063. },
  24064. set: function (value) {
  24065. if (this._fillMode === value) {
  24066. return;
  24067. }
  24068. this._fillMode = value;
  24069. this.markAsDirty(Material.MiscDirtyFlag);
  24070. },
  24071. enumerable: true,
  24072. configurable: true
  24073. });
  24074. /**
  24075. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24076. * subclasses should override adding information pertainent to themselves
  24077. */
  24078. Material.prototype.toString = function (fullDetails) {
  24079. var ret = "Name: " + this.name;
  24080. if (fullDetails) {
  24081. }
  24082. return ret;
  24083. };
  24084. /**
  24085. * Child classes can use it to update shaders
  24086. */
  24087. Material.prototype.getClassName = function () {
  24088. return "Material";
  24089. };
  24090. Object.defineProperty(Material.prototype, "isFrozen", {
  24091. get: function () {
  24092. return this.checkReadyOnlyOnce;
  24093. },
  24094. enumerable: true,
  24095. configurable: true
  24096. });
  24097. Material.prototype.freeze = function () {
  24098. this.checkReadyOnlyOnce = true;
  24099. };
  24100. Material.prototype.unfreeze = function () {
  24101. this.checkReadyOnlyOnce = false;
  24102. };
  24103. Material.prototype.isReady = function (mesh, useInstances) {
  24104. return true;
  24105. };
  24106. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24107. return false;
  24108. };
  24109. Material.prototype.getEffect = function () {
  24110. return this._effect;
  24111. };
  24112. Material.prototype.getScene = function () {
  24113. return this._scene;
  24114. };
  24115. Material.prototype.needAlphaBlending = function () {
  24116. return (this.alpha < 1.0);
  24117. };
  24118. Material.prototype.needAlphaTesting = function () {
  24119. return false;
  24120. };
  24121. Material.prototype.getAlphaTestTexture = function () {
  24122. return null;
  24123. };
  24124. Material.prototype.markDirty = function () {
  24125. this._wasPreviouslyReady = false;
  24126. };
  24127. Material.prototype._preBind = function (effect) {
  24128. var engine = this._scene.getEngine();
  24129. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24130. engine.enableEffect(effect ? effect : this._effect);
  24131. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24132. };
  24133. Material.prototype.bind = function (world, mesh) {
  24134. };
  24135. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24136. };
  24137. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24138. };
  24139. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24140. sceneUbo.bindToEffect(effect, "Scene");
  24141. };
  24142. Material.prototype.bindView = function (effect) {
  24143. if (!this._useUBO) {
  24144. effect.setMatrix("view", this.getScene().getViewMatrix());
  24145. }
  24146. else {
  24147. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24148. }
  24149. };
  24150. Material.prototype.bindViewProjection = function (effect) {
  24151. if (!this._useUBO) {
  24152. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24153. }
  24154. else {
  24155. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24156. }
  24157. };
  24158. Material.prototype._afterBind = function (mesh) {
  24159. this._scene._cachedMaterial = this;
  24160. this.onBindObservable.notifyObservers(mesh);
  24161. if (this.disableDepthWrite) {
  24162. var engine = this._scene.getEngine();
  24163. this._cachedDepthWriteState = engine.getDepthWrite();
  24164. engine.setDepthWrite(false);
  24165. }
  24166. };
  24167. Material.prototype.unbind = function () {
  24168. this.onUnBindObservable.notifyObservers(this);
  24169. if (this.disableDepthWrite) {
  24170. var engine = this._scene.getEngine();
  24171. engine.setDepthWrite(this._cachedDepthWriteState);
  24172. }
  24173. };
  24174. Material.prototype.getActiveTextures = function () {
  24175. return [];
  24176. };
  24177. Material.prototype.clone = function (name) {
  24178. return null;
  24179. };
  24180. Material.prototype.getBindedMeshes = function () {
  24181. var result = new Array();
  24182. for (var index = 0; index < this._scene.meshes.length; index++) {
  24183. var mesh = this._scene.meshes[index];
  24184. if (mesh.material === this) {
  24185. result.push(mesh);
  24186. }
  24187. }
  24188. return result;
  24189. };
  24190. // Force shader compilation including textures ready check
  24191. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24192. var _this = this;
  24193. var subMesh = new BABYLON.BaseSubMesh();
  24194. var scene = this.getScene();
  24195. var engine = scene.getEngine();
  24196. var beforeRenderCallback = function () {
  24197. if (subMesh._materialDefines) {
  24198. subMesh._materialDefines._renderId = -1;
  24199. }
  24200. var alphaTestState = engine.getAlphaTesting();
  24201. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24202. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24203. scene.unregisterBeforeRender(beforeRenderCallback);
  24204. if (onCompiled) {
  24205. onCompiled(_this);
  24206. }
  24207. }
  24208. engine.setAlphaTesting(alphaTestState);
  24209. };
  24210. scene.registerBeforeRender(beforeRenderCallback);
  24211. };
  24212. Material.prototype.markAsDirty = function (flag) {
  24213. if (flag & Material.TextureDirtyFlag) {
  24214. this._markAllSubMeshesAsTexturesDirty();
  24215. }
  24216. if (flag & Material.LightDirtyFlag) {
  24217. this._markAllSubMeshesAsLightsDirty();
  24218. }
  24219. if (flag & Material.FresnelDirtyFlag) {
  24220. this._markAllSubMeshesAsFresnelDirty();
  24221. }
  24222. if (flag & Material.AttributesDirtyFlag) {
  24223. this._markAllSubMeshesAsAttributesDirty();
  24224. }
  24225. if (flag & Material.MiscDirtyFlag) {
  24226. this._markAllSubMeshesAsMiscDirty();
  24227. }
  24228. this.getScene().resetCachedMaterial();
  24229. };
  24230. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24231. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24232. var mesh = _a[_i];
  24233. if (!mesh.subMeshes) {
  24234. continue;
  24235. }
  24236. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24237. var subMesh = _c[_b];
  24238. if (subMesh.getMaterial() !== this) {
  24239. continue;
  24240. }
  24241. if (!subMesh._materialDefines) {
  24242. return;
  24243. }
  24244. func(subMesh._materialDefines);
  24245. }
  24246. }
  24247. };
  24248. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24249. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24250. };
  24251. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24252. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24253. };
  24254. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24255. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24256. };
  24257. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24258. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24259. };
  24260. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24261. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24262. };
  24263. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24264. // Animations
  24265. this.getScene().stopAnimation(this);
  24266. // Remove from scene
  24267. var index = this._scene.materials.indexOf(this);
  24268. if (index >= 0) {
  24269. this._scene.materials.splice(index, 1);
  24270. }
  24271. // Remove from meshes
  24272. for (index = 0; index < this._scene.meshes.length; index++) {
  24273. var mesh = this._scene.meshes[index];
  24274. if (mesh.material === this) {
  24275. mesh.material = null;
  24276. if (mesh.geometry) {
  24277. var geometry = mesh.geometry;
  24278. if (this.storeEffectOnSubMeshes) {
  24279. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24280. var subMesh = _a[_i];
  24281. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24282. }
  24283. }
  24284. else {
  24285. geometry._releaseVertexArrayObject(this._effect);
  24286. }
  24287. }
  24288. }
  24289. }
  24290. this._uniformBuffer.dispose();
  24291. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24292. if (forceDisposeEffect && this._effect) {
  24293. if (this.storeEffectOnSubMeshes) {
  24294. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24295. var subMesh = _c[_b];
  24296. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24297. }
  24298. }
  24299. else {
  24300. this._scene.getEngine()._releaseEffect(this._effect);
  24301. }
  24302. this._effect = null;
  24303. }
  24304. // Callback
  24305. this.onDisposeObservable.notifyObservers(this);
  24306. this.onDisposeObservable.clear();
  24307. this.onBindObservable.clear();
  24308. this.onUnBindObservable.clear();
  24309. };
  24310. Material.prototype.serialize = function () {
  24311. return BABYLON.SerializationHelper.Serialize(this);
  24312. };
  24313. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24314. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24315. multiMaterial.id = parsedMultiMaterial.id;
  24316. if (BABYLON.Tags) {
  24317. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24318. }
  24319. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24320. var subMatId = parsedMultiMaterial.materials[matIndex];
  24321. if (subMatId) {
  24322. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24323. }
  24324. else {
  24325. multiMaterial.subMaterials.push(null);
  24326. }
  24327. }
  24328. return multiMaterial;
  24329. };
  24330. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24331. if (!parsedMaterial.customType) {
  24332. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24333. }
  24334. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24335. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24336. if (!BABYLON.LegacyPBRMaterial) {
  24337. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24338. return;
  24339. }
  24340. }
  24341. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24342. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24343. ;
  24344. };
  24345. return Material;
  24346. }());
  24347. Material._TriangleFillMode = 0;
  24348. Material._WireFrameFillMode = 1;
  24349. Material._PointFillMode = 2;
  24350. Material._ClockWiseSideOrientation = 0;
  24351. Material._CounterClockWiseSideOrientation = 1;
  24352. Material._TextureDirtyFlag = 1;
  24353. Material._LightDirtyFlag = 2;
  24354. Material._FresnelDirtyFlag = 4;
  24355. Material._AttributesDirtyFlag = 8;
  24356. Material._MiscDirtyFlag = 16;
  24357. __decorate([
  24358. BABYLON.serialize()
  24359. ], Material.prototype, "id", void 0);
  24360. __decorate([
  24361. BABYLON.serialize()
  24362. ], Material.prototype, "name", void 0);
  24363. __decorate([
  24364. BABYLON.serialize()
  24365. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24366. __decorate([
  24367. BABYLON.serialize()
  24368. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24369. __decorate([
  24370. BABYLON.serialize()
  24371. ], Material.prototype, "state", void 0);
  24372. __decorate([
  24373. BABYLON.serialize()
  24374. ], Material.prototype, "alpha", void 0);
  24375. __decorate([
  24376. BABYLON.serialize("backFaceCulling")
  24377. ], Material.prototype, "_backFaceCulling", void 0);
  24378. __decorate([
  24379. BABYLON.serialize()
  24380. ], Material.prototype, "sideOrientation", void 0);
  24381. __decorate([
  24382. BABYLON.serialize()
  24383. ], Material.prototype, "alphaMode", void 0);
  24384. __decorate([
  24385. BABYLON.serialize()
  24386. ], Material.prototype, "disableDepthWrite", void 0);
  24387. __decorate([
  24388. BABYLON.serialize("fogEnabled")
  24389. ], Material.prototype, "_fogEnabled", void 0);
  24390. __decorate([
  24391. BABYLON.serialize()
  24392. ], Material.prototype, "pointSize", void 0);
  24393. __decorate([
  24394. BABYLON.serialize()
  24395. ], Material.prototype, "zOffset", void 0);
  24396. __decorate([
  24397. BABYLON.serialize()
  24398. ], Material.prototype, "wireframe", null);
  24399. __decorate([
  24400. BABYLON.serialize()
  24401. ], Material.prototype, "pointsCloud", null);
  24402. __decorate([
  24403. BABYLON.serialize()
  24404. ], Material.prototype, "fillMode", null);
  24405. BABYLON.Material = Material;
  24406. })(BABYLON || (BABYLON = {}));
  24407. //# sourceMappingURL=babylon.material.js.map
  24408. var BABYLON;
  24409. (function (BABYLON) {
  24410. var UniformBuffer = (function () {
  24411. /**
  24412. * Uniform buffer objects.
  24413. *
  24414. * Handles blocks of uniform on the GPU.
  24415. *
  24416. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24417. *
  24418. * For more information, please refer to :
  24419. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24420. */
  24421. function UniformBuffer(engine, data, dynamic) {
  24422. this._engine = engine;
  24423. this._noUBO = engine.webGLVersion === 1;
  24424. this._dynamic = dynamic;
  24425. this._data = data || [];
  24426. this._uniformLocations = {};
  24427. this._uniformSizes = {};
  24428. this._uniformLocationPointer = 0;
  24429. this._needSync = false;
  24430. if (this._noUBO) {
  24431. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24432. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24433. this.updateFloat = this._updateFloatForEffect;
  24434. this.updateFloat2 = this._updateFloat2ForEffect;
  24435. this.updateFloat3 = this._updateFloat3ForEffect;
  24436. this.updateFloat4 = this._updateFloat4ForEffect;
  24437. this.updateMatrix = this._updateMatrixForEffect;
  24438. this.updateVector3 = this._updateVector3ForEffect;
  24439. this.updateVector4 = this._updateVector4ForEffect;
  24440. this.updateColor3 = this._updateColor3ForEffect;
  24441. this.updateColor4 = this._updateColor4ForEffect;
  24442. }
  24443. else {
  24444. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24445. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24446. this.updateFloat = this._updateFloatForUniform;
  24447. this.updateFloat2 = this._updateFloat2ForUniform;
  24448. this.updateFloat3 = this._updateFloat3ForUniform;
  24449. this.updateFloat4 = this._updateFloat4ForUniform;
  24450. this.updateMatrix = this._updateMatrixForUniform;
  24451. this.updateVector3 = this._updateVector3ForUniform;
  24452. this.updateVector4 = this._updateVector4ForUniform;
  24453. this.updateColor3 = this._updateColor3ForUniform;
  24454. this.updateColor4 = this._updateColor4ForUniform;
  24455. }
  24456. }
  24457. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24458. // Properties
  24459. /**
  24460. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24461. * or just falling back on setUniformXXX calls.
  24462. */
  24463. get: function () {
  24464. return !this._noUBO;
  24465. },
  24466. enumerable: true,
  24467. configurable: true
  24468. });
  24469. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24470. /**
  24471. * Indicates if the WebGL underlying uniform buffer is in sync
  24472. * with the javascript cache data.
  24473. */
  24474. get: function () {
  24475. return !this._needSync;
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. /**
  24481. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24482. * Also, a dynamic UniformBuffer will disable cache verification and always
  24483. * update the underlying WebGL uniform buffer to the GPU.
  24484. */
  24485. UniformBuffer.prototype.isDynamic = function () {
  24486. return this._dynamic;
  24487. };
  24488. /**
  24489. * The data cache on JS side.
  24490. */
  24491. UniformBuffer.prototype.getData = function () {
  24492. return this._bufferData;
  24493. };
  24494. /**
  24495. * The underlying WebGL Uniform buffer.
  24496. */
  24497. UniformBuffer.prototype.getBuffer = function () {
  24498. return this._buffer;
  24499. };
  24500. /**
  24501. * std140 layout specifies how to align data within an UBO structure.
  24502. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24503. * for specs.
  24504. */
  24505. UniformBuffer.prototype._fillAlignment = function (size) {
  24506. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24507. // and 4x4 matrices
  24508. // TODO : change if other types are used
  24509. var alignment;
  24510. if (size <= 2) {
  24511. alignment = size;
  24512. }
  24513. else {
  24514. alignment = 4;
  24515. }
  24516. if ((this._uniformLocationPointer % alignment) !== 0) {
  24517. var oldPointer = this._uniformLocationPointer;
  24518. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24519. var diff = this._uniformLocationPointer - oldPointer;
  24520. for (var i = 0; i < diff; i++) {
  24521. this._data.push(0);
  24522. }
  24523. }
  24524. };
  24525. /**
  24526. * Adds an uniform in the buffer.
  24527. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24528. * for the layout to be correct !
  24529. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24530. * @param {number|number[]} size Data size, or data directly.
  24531. */
  24532. UniformBuffer.prototype.addUniform = function (name, size) {
  24533. if (this._noUBO) {
  24534. return;
  24535. }
  24536. if (this._uniformLocations[name] !== undefined) {
  24537. // Already existing uniform
  24538. return;
  24539. }
  24540. // This function must be called in the order of the shader layout !
  24541. // size can be the size of the uniform, or data directly
  24542. var data;
  24543. if (size instanceof Array) {
  24544. data = size;
  24545. size = data.length;
  24546. }
  24547. else {
  24548. size = size;
  24549. data = [];
  24550. // Fill with zeros
  24551. for (var i = 0; i < size; i++) {
  24552. data.push(0);
  24553. }
  24554. }
  24555. this._fillAlignment(size);
  24556. this._uniformSizes[name] = size;
  24557. this._uniformLocations[name] = this._uniformLocationPointer;
  24558. this._uniformLocationPointer += size;
  24559. for (var i = 0; i < size; i++) {
  24560. this._data.push(data[i]);
  24561. }
  24562. this._needSync = true;
  24563. };
  24564. /**
  24565. * Wrapper for addUniform.
  24566. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24567. * @param {Matrix} mat A 4x4 matrix.
  24568. */
  24569. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24570. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24571. };
  24572. /**
  24573. * Wrapper for addUniform.
  24574. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24575. * @param {number} x
  24576. * @param {number} y
  24577. */
  24578. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24579. var temp = [x, y];
  24580. this.addUniform(name, temp);
  24581. };
  24582. /**
  24583. * Wrapper for addUniform.
  24584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24585. * @param {number} x
  24586. * @param {number} y
  24587. * @param {number} z
  24588. */
  24589. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24590. var temp = [x, y, z];
  24591. this.addUniform(name, temp);
  24592. };
  24593. /**
  24594. * Wrapper for addUniform.
  24595. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24596. * @param {Color3} color
  24597. */
  24598. UniformBuffer.prototype.addColor3 = function (name, color) {
  24599. var temp = [];
  24600. color.toArray(temp);
  24601. this.addUniform(name, temp);
  24602. };
  24603. /**
  24604. * Wrapper for addUniform.
  24605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24606. * @param {Color3} color
  24607. * @param {number} alpha
  24608. */
  24609. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24610. var temp = [];
  24611. color.toArray(temp);
  24612. temp.push(alpha);
  24613. this.addUniform(name, temp);
  24614. };
  24615. /**
  24616. * Wrapper for addUniform.
  24617. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24618. * @param {Vector3} vector
  24619. */
  24620. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24621. var temp = [];
  24622. vector.toArray(temp);
  24623. this.addUniform(name, temp);
  24624. };
  24625. /**
  24626. * Wrapper for addUniform.
  24627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24628. */
  24629. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24630. this.addUniform(name, 12);
  24631. };
  24632. /**
  24633. * Wrapper for addUniform.
  24634. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24635. */
  24636. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24637. this.addUniform(name, 8);
  24638. };
  24639. /**
  24640. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24641. */
  24642. UniformBuffer.prototype.create = function () {
  24643. if (this._noUBO) {
  24644. return;
  24645. }
  24646. if (this._buffer) {
  24647. return; // nothing to do
  24648. }
  24649. // See spec, alignment must be filled as a vec4
  24650. this._fillAlignment(4);
  24651. this._bufferData = new Float32Array(this._data);
  24652. if (this._dynamic) {
  24653. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24654. }
  24655. else {
  24656. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24657. }
  24658. this._needSync = true;
  24659. };
  24660. /**
  24661. * Updates the WebGL Uniform Buffer on the GPU.
  24662. * If the `dynamic` flag is set to true, no cache comparison is done.
  24663. * Otherwise, the buffer will be updated only if the cache differs.
  24664. */
  24665. UniformBuffer.prototype.update = function () {
  24666. if (!this._buffer) {
  24667. this.create();
  24668. return;
  24669. }
  24670. if (!this._dynamic && !this._needSync) {
  24671. return;
  24672. }
  24673. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24674. this._needSync = false;
  24675. };
  24676. /**
  24677. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24678. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24679. * @param {number[]|Float32Array} data Flattened data
  24680. * @param {number} size Size of the data.
  24681. */
  24682. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24683. var location = this._uniformLocations[uniformName];
  24684. if (location === undefined) {
  24685. if (this._buffer) {
  24686. // Cannot add an uniform if the buffer is already created
  24687. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24688. return;
  24689. }
  24690. this.addUniform(uniformName, size);
  24691. location = this._uniformLocations[uniformName];
  24692. }
  24693. if (!this._buffer) {
  24694. this.create();
  24695. }
  24696. if (!this._dynamic) {
  24697. // Cache for static uniform buffers
  24698. var changed = false;
  24699. for (var i = 0; i < size; i++) {
  24700. if (this._bufferData[location + i] !== data[i]) {
  24701. changed = true;
  24702. this._bufferData[location + i] = data[i];
  24703. }
  24704. }
  24705. this._needSync = this._needSync || changed;
  24706. }
  24707. else {
  24708. // No cache for dynamic
  24709. for (var i = 0; i < size; i++) {
  24710. this._bufferData[location + i] = data[i];
  24711. }
  24712. }
  24713. };
  24714. // Update methods
  24715. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24716. // To match std140, matrix must be realigned
  24717. for (var i = 0; i < 3; i++) {
  24718. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24719. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24720. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24721. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24722. }
  24723. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24724. };
  24725. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24726. this._currentEffect.setMatrix3x3(name, matrix);
  24727. };
  24728. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24729. this._currentEffect.setMatrix2x2(name, matrix);
  24730. };
  24731. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24732. // To match std140, matrix must be realigned
  24733. for (var i = 0; i < 2; i++) {
  24734. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24735. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24736. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24737. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24738. }
  24739. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24740. };
  24741. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24742. this._currentEffect.setFloat(name, x);
  24743. };
  24744. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24745. UniformBuffer._tempBuffer[0] = x;
  24746. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24747. };
  24748. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24749. if (suffix === void 0) { suffix = ""; }
  24750. this._currentEffect.setFloat2(name + suffix, x, y);
  24751. };
  24752. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24753. if (suffix === void 0) { suffix = ""; }
  24754. UniformBuffer._tempBuffer[0] = x;
  24755. UniformBuffer._tempBuffer[1] = y;
  24756. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24757. };
  24758. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24759. if (suffix === void 0) { suffix = ""; }
  24760. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24761. };
  24762. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24763. if (suffix === void 0) { suffix = ""; }
  24764. UniformBuffer._tempBuffer[0] = x;
  24765. UniformBuffer._tempBuffer[1] = y;
  24766. UniformBuffer._tempBuffer[2] = z;
  24767. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24768. };
  24769. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24770. if (suffix === void 0) { suffix = ""; }
  24771. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24772. };
  24773. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24774. if (suffix === void 0) { suffix = ""; }
  24775. UniformBuffer._tempBuffer[0] = x;
  24776. UniformBuffer._tempBuffer[1] = y;
  24777. UniformBuffer._tempBuffer[2] = z;
  24778. UniformBuffer._tempBuffer[3] = w;
  24779. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24780. };
  24781. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24782. this._currentEffect.setMatrix(name, mat);
  24783. };
  24784. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24785. this.updateUniform(name, mat.toArray(), 16);
  24786. };
  24787. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24788. this._currentEffect.setVector3(name, vector);
  24789. };
  24790. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24791. vector.toArray(UniformBuffer._tempBuffer);
  24792. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24793. };
  24794. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24795. this._currentEffect.setVector4(name, vector);
  24796. };
  24797. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24798. vector.toArray(UniformBuffer._tempBuffer);
  24799. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24800. };
  24801. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24802. if (suffix === void 0) { suffix = ""; }
  24803. this._currentEffect.setColor3(name + suffix, color);
  24804. };
  24805. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24806. if (suffix === void 0) { suffix = ""; }
  24807. color.toArray(UniformBuffer._tempBuffer);
  24808. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24809. };
  24810. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24811. if (suffix === void 0) { suffix = ""; }
  24812. this._currentEffect.setColor4(name + suffix, color, alpha);
  24813. };
  24814. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24815. if (suffix === void 0) { suffix = ""; }
  24816. color.toArray(UniformBuffer._tempBuffer);
  24817. UniformBuffer._tempBuffer[3] = alpha;
  24818. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24819. };
  24820. /**
  24821. * Sets a sampler uniform on the effect.
  24822. * @param {string} name Name of the sampler.
  24823. * @param {Texture} texture
  24824. */
  24825. UniformBuffer.prototype.setTexture = function (name, texture) {
  24826. this._currentEffect.setTexture(name, texture);
  24827. };
  24828. /**
  24829. * Directly updates the value of the uniform in the cache AND on the GPU.
  24830. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24831. * @param {number[]|Float32Array} data Flattened data
  24832. */
  24833. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24834. this.updateUniform(uniformName, data, data.length);
  24835. this.update();
  24836. };
  24837. /**
  24838. * Binds this uniform buffer to an effect.
  24839. * @param {Effect} effect
  24840. * @param {string} name Name of the uniform block in the shader.
  24841. */
  24842. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24843. this._currentEffect = effect;
  24844. if (this._noUBO) {
  24845. return;
  24846. }
  24847. effect.bindUniformBuffer(this._buffer, name);
  24848. };
  24849. /**
  24850. * Disposes the uniform buffer.
  24851. */
  24852. UniformBuffer.prototype.dispose = function () {
  24853. if (!this._buffer) {
  24854. return;
  24855. }
  24856. if (this._engine._releaseBuffer(this._buffer)) {
  24857. this._buffer = null;
  24858. }
  24859. };
  24860. return UniformBuffer;
  24861. }());
  24862. // Pool for avoiding memory leaks
  24863. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24864. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24865. BABYLON.UniformBuffer = UniformBuffer;
  24866. })(BABYLON || (BABYLON = {}));
  24867. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24868. var BABYLON;
  24869. (function (BABYLON) {
  24870. var PushMaterial = (function (_super) {
  24871. __extends(PushMaterial, _super);
  24872. function PushMaterial(name, scene) {
  24873. var _this = _super.call(this, name, scene) || this;
  24874. _this.storeEffectOnSubMeshes = true;
  24875. return _this;
  24876. }
  24877. PushMaterial.prototype.getEffect = function () {
  24878. return this._activeEffect;
  24879. };
  24880. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24881. if (!mesh) {
  24882. return false;
  24883. }
  24884. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24885. return true;
  24886. }
  24887. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24888. };
  24889. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24890. this._activeEffect.setMatrix("world", world);
  24891. };
  24892. PushMaterial.prototype.bind = function (world, mesh) {
  24893. if (!mesh) {
  24894. return;
  24895. }
  24896. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24897. };
  24898. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24899. _super.prototype._afterBind.call(this, mesh);
  24900. this.getScene()._cachedEffect = effect;
  24901. };
  24902. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24903. if (visibility === void 0) { visibility = 0; }
  24904. return scene.isCachedMaterialValid(this, effect, visibility);
  24905. };
  24906. return PushMaterial;
  24907. }(BABYLON.Material));
  24908. BABYLON.PushMaterial = PushMaterial;
  24909. })(BABYLON || (BABYLON = {}));
  24910. //# sourceMappingURL=babylon.pushMaterial.js.map
  24911. var BABYLON;
  24912. (function (BABYLON) {
  24913. var VertexData = (function () {
  24914. function VertexData() {
  24915. }
  24916. VertexData.prototype.set = function (data, kind) {
  24917. switch (kind) {
  24918. case BABYLON.VertexBuffer.PositionKind:
  24919. this.positions = data;
  24920. break;
  24921. case BABYLON.VertexBuffer.NormalKind:
  24922. this.normals = data;
  24923. break;
  24924. case BABYLON.VertexBuffer.TangentKind:
  24925. this.tangents = data;
  24926. break;
  24927. case BABYLON.VertexBuffer.UVKind:
  24928. this.uvs = data;
  24929. break;
  24930. case BABYLON.VertexBuffer.UV2Kind:
  24931. this.uvs2 = data;
  24932. break;
  24933. case BABYLON.VertexBuffer.UV3Kind:
  24934. this.uvs3 = data;
  24935. break;
  24936. case BABYLON.VertexBuffer.UV4Kind:
  24937. this.uvs4 = data;
  24938. break;
  24939. case BABYLON.VertexBuffer.UV5Kind:
  24940. this.uvs5 = data;
  24941. break;
  24942. case BABYLON.VertexBuffer.UV6Kind:
  24943. this.uvs6 = data;
  24944. break;
  24945. case BABYLON.VertexBuffer.ColorKind:
  24946. this.colors = data;
  24947. break;
  24948. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24949. this.matricesIndices = data;
  24950. break;
  24951. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24952. this.matricesWeights = data;
  24953. break;
  24954. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24955. this.matricesIndicesExtra = data;
  24956. break;
  24957. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24958. this.matricesWeightsExtra = data;
  24959. break;
  24960. }
  24961. };
  24962. /**
  24963. * Associates the vertexData to the passed Mesh.
  24964. * Sets it as updatable or not (default `false`).
  24965. * Returns the VertexData.
  24966. */
  24967. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24968. this._applyTo(mesh, updatable);
  24969. return this;
  24970. };
  24971. /**
  24972. * Associates the vertexData to the passed Geometry.
  24973. * Sets it as updatable or not (default `false`).
  24974. * Returns the VertexData.
  24975. */
  24976. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24977. this._applyTo(geometry, updatable);
  24978. return this;
  24979. };
  24980. /**
  24981. * Updates the associated mesh.
  24982. * Returns the VertexData.
  24983. */
  24984. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24985. this._update(mesh);
  24986. return this;
  24987. };
  24988. /**
  24989. * Updates the associated geometry.
  24990. * Returns the VertexData.
  24991. */
  24992. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24993. this._update(geometry);
  24994. return this;
  24995. };
  24996. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24997. if (this.positions) {
  24998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24999. }
  25000. if (this.normals) {
  25001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25002. }
  25003. if (this.tangents) {
  25004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25005. }
  25006. if (this.uvs) {
  25007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25008. }
  25009. if (this.uvs2) {
  25010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25011. }
  25012. if (this.uvs3) {
  25013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25014. }
  25015. if (this.uvs4) {
  25016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25017. }
  25018. if (this.uvs5) {
  25019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25020. }
  25021. if (this.uvs6) {
  25022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25023. }
  25024. if (this.colors) {
  25025. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25026. }
  25027. if (this.matricesIndices) {
  25028. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25029. }
  25030. if (this.matricesWeights) {
  25031. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25032. }
  25033. if (this.matricesIndicesExtra) {
  25034. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25035. }
  25036. if (this.matricesWeightsExtra) {
  25037. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25038. }
  25039. if (this.indices) {
  25040. meshOrGeometry.setIndices(this.indices);
  25041. }
  25042. return this;
  25043. };
  25044. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25045. if (this.positions) {
  25046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25047. }
  25048. if (this.normals) {
  25049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25050. }
  25051. if (this.tangents) {
  25052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25053. }
  25054. if (this.uvs) {
  25055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25056. }
  25057. if (this.uvs2) {
  25058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25059. }
  25060. if (this.uvs3) {
  25061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25062. }
  25063. if (this.uvs4) {
  25064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25065. }
  25066. if (this.uvs5) {
  25067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25068. }
  25069. if (this.uvs6) {
  25070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25071. }
  25072. if (this.colors) {
  25073. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25074. }
  25075. if (this.matricesIndices) {
  25076. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25077. }
  25078. if (this.matricesWeights) {
  25079. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25080. }
  25081. if (this.matricesIndicesExtra) {
  25082. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25083. }
  25084. if (this.matricesWeightsExtra) {
  25085. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25086. }
  25087. if (this.indices) {
  25088. meshOrGeometry.setIndices(this.indices);
  25089. }
  25090. return this;
  25091. };
  25092. /**
  25093. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25094. * Returns the VertexData.
  25095. */
  25096. VertexData.prototype.transform = function (matrix) {
  25097. var transformed = BABYLON.Vector3.Zero();
  25098. var index;
  25099. if (this.positions) {
  25100. var position = BABYLON.Vector3.Zero();
  25101. for (index = 0; index < this.positions.length; index += 3) {
  25102. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25103. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25104. this.positions[index] = transformed.x;
  25105. this.positions[index + 1] = transformed.y;
  25106. this.positions[index + 2] = transformed.z;
  25107. }
  25108. }
  25109. if (this.normals) {
  25110. var normal = BABYLON.Vector3.Zero();
  25111. for (index = 0; index < this.normals.length; index += 3) {
  25112. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25113. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25114. this.normals[index] = transformed.x;
  25115. this.normals[index + 1] = transformed.y;
  25116. this.normals[index + 2] = transformed.z;
  25117. }
  25118. }
  25119. if (this.tangents) {
  25120. var tangent = BABYLON.Vector4.Zero();
  25121. var tangentTransformed = BABYLON.Vector4.Zero();
  25122. for (index = 0; index < this.tangents.length; index += 4) {
  25123. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25124. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25125. this.tangents[index] = tangentTransformed.x;
  25126. this.tangents[index + 1] = tangentTransformed.y;
  25127. this.tangents[index + 2] = tangentTransformed.z;
  25128. this.tangents[index + 3] = tangentTransformed.w;
  25129. }
  25130. }
  25131. return this;
  25132. };
  25133. /**
  25134. * Merges the passed VertexData into the current one.
  25135. * Returns the modified VertexData.
  25136. */
  25137. VertexData.prototype.merge = function (other) {
  25138. if (other.indices) {
  25139. if (!this.indices) {
  25140. this.indices = [];
  25141. }
  25142. var offset = this.positions ? this.positions.length / 3 : 0;
  25143. for (var index = 0; index < other.indices.length; index++) {
  25144. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25145. this.indices.push(other.indices[index] + offset);
  25146. }
  25147. }
  25148. this.positions = this._mergeElement(this.positions, other.positions);
  25149. this.normals = this._mergeElement(this.normals, other.normals);
  25150. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25151. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25152. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25153. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25154. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25155. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25156. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25157. this.colors = this._mergeElement(this.colors, other.colors);
  25158. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25159. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25160. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25161. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25162. return this;
  25163. };
  25164. VertexData.prototype._mergeElement = function (source, other) {
  25165. if (!other)
  25166. return source;
  25167. if (!source)
  25168. return other;
  25169. var len = other.length + source.length;
  25170. var isSrcTypedArray = source instanceof Float32Array;
  25171. var isOthTypedArray = other instanceof Float32Array;
  25172. // use non-loop method when the source is Float32Array
  25173. if (isSrcTypedArray) {
  25174. var ret32 = new Float32Array(len);
  25175. ret32.set(source);
  25176. ret32.set(other, source.length);
  25177. return ret32;
  25178. // source is number[], when other is also use concat
  25179. }
  25180. else if (!isOthTypedArray) {
  25181. return source.concat(other);
  25182. // source is a number[], but other is a Float32Array, loop required
  25183. }
  25184. else {
  25185. var ret = source.slice(0); // copy source to a separate array
  25186. for (var i = 0, len = other.length; i < len; i++) {
  25187. ret.push(other[i]);
  25188. }
  25189. return ret;
  25190. }
  25191. };
  25192. /**
  25193. * Serializes the VertexData.
  25194. * Returns a serialized object.
  25195. */
  25196. VertexData.prototype.serialize = function () {
  25197. var serializationObject = this.serialize();
  25198. if (this.positions) {
  25199. serializationObject.positions = this.positions;
  25200. }
  25201. if (this.normals) {
  25202. serializationObject.normals = this.normals;
  25203. }
  25204. if (this.tangents) {
  25205. serializationObject.tangents = this.tangents;
  25206. }
  25207. if (this.uvs) {
  25208. serializationObject.uvs = this.uvs;
  25209. }
  25210. if (this.uvs2) {
  25211. serializationObject.uvs2 = this.uvs2;
  25212. }
  25213. if (this.uvs3) {
  25214. serializationObject.uvs3 = this.uvs3;
  25215. }
  25216. if (this.uvs4) {
  25217. serializationObject.uvs4 = this.uvs4;
  25218. }
  25219. if (this.uvs5) {
  25220. serializationObject.uvs5 = this.uvs5;
  25221. }
  25222. if (this.uvs6) {
  25223. serializationObject.uvs6 = this.uvs6;
  25224. }
  25225. if (this.colors) {
  25226. serializationObject.colors = this.colors;
  25227. }
  25228. if (this.matricesIndices) {
  25229. serializationObject.matricesIndices = this.matricesIndices;
  25230. serializationObject.matricesIndices._isExpanded = true;
  25231. }
  25232. if (this.matricesWeights) {
  25233. serializationObject.matricesWeights = this.matricesWeights;
  25234. }
  25235. if (this.matricesIndicesExtra) {
  25236. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25237. serializationObject.matricesIndicesExtra._isExpanded = true;
  25238. }
  25239. if (this.matricesWeightsExtra) {
  25240. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25241. }
  25242. serializationObject.indices = this.indices;
  25243. return serializationObject;
  25244. };
  25245. // Statics
  25246. /**
  25247. * Returns the object VertexData associated to the passed mesh.
  25248. */
  25249. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25250. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25251. };
  25252. /**
  25253. * Returns the object VertexData associated to the passed geometry.
  25254. */
  25255. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25256. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25257. };
  25258. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25259. var result = new VertexData();
  25260. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25261. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25262. }
  25263. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25264. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25265. }
  25266. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25267. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25268. }
  25269. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25270. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25271. }
  25272. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25273. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25274. }
  25275. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25276. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25277. }
  25278. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25279. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25280. }
  25281. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25282. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25283. }
  25284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25285. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25286. }
  25287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25288. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25289. }
  25290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25291. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25292. }
  25293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25294. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25295. }
  25296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25297. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25298. }
  25299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25300. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25301. }
  25302. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25303. return result;
  25304. };
  25305. /**
  25306. * Creates the vertexData of the Ribbon.
  25307. */
  25308. VertexData.CreateRibbon = function (options) {
  25309. var pathArray = options.pathArray;
  25310. var closeArray = options.closeArray || false;
  25311. var closePath = options.closePath || false;
  25312. var invertUV = options.invertUV || false;
  25313. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25314. var offset = options.offset || defaultOffset;
  25315. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25316. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25317. var customUV = options.uvs;
  25318. var customColors = options.colors;
  25319. var positions = [];
  25320. var indices = [];
  25321. var normals = [];
  25322. var uvs = [];
  25323. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25324. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25325. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25326. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25327. var minlg; // minimal length among all paths from pathArray
  25328. var lg = []; // array of path lengths : nb of vertex per path
  25329. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25330. var p; // path iterator
  25331. var i; // point iterator
  25332. var j; // point iterator
  25333. // if single path in pathArray
  25334. if (pathArray.length < 2) {
  25335. var ar1 = [];
  25336. var ar2 = [];
  25337. for (i = 0; i < pathArray[0].length - offset; i++) {
  25338. ar1.push(pathArray[0][i]);
  25339. ar2.push(pathArray[0][i + offset]);
  25340. }
  25341. pathArray = [ar1, ar2];
  25342. }
  25343. // positions and horizontal distances (u)
  25344. var idc = 0;
  25345. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25346. var path;
  25347. var l;
  25348. minlg = pathArray[0].length;
  25349. var vectlg;
  25350. var dist;
  25351. for (p = 0; p < pathArray.length; p++) {
  25352. uTotalDistance[p] = 0;
  25353. us[p] = [0];
  25354. path = pathArray[p];
  25355. l = path.length;
  25356. minlg = (minlg < l) ? minlg : l;
  25357. j = 0;
  25358. while (j < l) {
  25359. positions.push(path[j].x, path[j].y, path[j].z);
  25360. if (j > 0) {
  25361. vectlg = path[j].subtract(path[j - 1]).length();
  25362. dist = vectlg + uTotalDistance[p];
  25363. us[p].push(dist);
  25364. uTotalDistance[p] = dist;
  25365. }
  25366. j++;
  25367. }
  25368. if (closePath) {
  25369. j--;
  25370. positions.push(path[0].x, path[0].y, path[0].z);
  25371. vectlg = path[j].subtract(path[0]).length();
  25372. dist = vectlg + uTotalDistance[p];
  25373. us[p].push(dist);
  25374. uTotalDistance[p] = dist;
  25375. }
  25376. lg[p] = l + closePathCorr;
  25377. idx[p] = idc;
  25378. idc += (l + closePathCorr);
  25379. }
  25380. // vertical distances (v)
  25381. var path1;
  25382. var path2;
  25383. var vertex1;
  25384. var vertex2;
  25385. for (i = 0; i < minlg + closePathCorr; i++) {
  25386. vTotalDistance[i] = 0;
  25387. vs[i] = [0];
  25388. for (p = 0; p < pathArray.length - 1; p++) {
  25389. path1 = pathArray[p];
  25390. path2 = pathArray[p + 1];
  25391. if (i === minlg) {
  25392. vertex1 = path1[0];
  25393. vertex2 = path2[0];
  25394. }
  25395. else {
  25396. vertex1 = path1[i];
  25397. vertex2 = path2[i];
  25398. }
  25399. vectlg = vertex2.subtract(vertex1).length();
  25400. dist = vectlg + vTotalDistance[i];
  25401. vs[i].push(dist);
  25402. vTotalDistance[i] = dist;
  25403. }
  25404. if (closeArray) {
  25405. path1 = pathArray[p];
  25406. path2 = pathArray[0];
  25407. if (i === minlg) {
  25408. vertex2 = path2[0];
  25409. }
  25410. vectlg = vertex2.subtract(vertex1).length();
  25411. dist = vectlg + vTotalDistance[i];
  25412. vTotalDistance[i] = dist;
  25413. }
  25414. }
  25415. // uvs
  25416. var u;
  25417. var v;
  25418. if (customUV) {
  25419. for (p = 0; p < customUV.length; p++) {
  25420. uvs.push(customUV[p].x, customUV[p].y);
  25421. }
  25422. }
  25423. else {
  25424. for (p = 0; p < pathArray.length; p++) {
  25425. for (i = 0; i < minlg + closePathCorr; i++) {
  25426. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25427. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25428. if (invertUV) {
  25429. uvs.push(v, u);
  25430. }
  25431. else {
  25432. uvs.push(u, v);
  25433. }
  25434. }
  25435. }
  25436. }
  25437. // indices
  25438. p = 0; // path index
  25439. var pi = 0; // positions array index
  25440. var l1 = lg[p] - 1; // path1 length
  25441. var l2 = lg[p + 1] - 1; // path2 length
  25442. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25443. var shft = idx[1] - idx[0]; // shift
  25444. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25445. while (pi <= min && p < path1nb) {
  25446. // 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
  25447. indices.push(pi, pi + shft, pi + 1);
  25448. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25449. pi += 1;
  25450. if (pi === min) {
  25451. p++;
  25452. if (p === lg.length - 1) {
  25453. shft = idx[0] - idx[p];
  25454. l1 = lg[p] - 1;
  25455. l2 = lg[0] - 1;
  25456. }
  25457. else {
  25458. shft = idx[p + 1] - idx[p];
  25459. l1 = lg[p] - 1;
  25460. l2 = lg[p + 1] - 1;
  25461. }
  25462. pi = idx[p];
  25463. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25464. }
  25465. }
  25466. // normals
  25467. VertexData.ComputeNormals(positions, indices, normals);
  25468. if (closePath) {
  25469. var indexFirst = 0;
  25470. var indexLast = 0;
  25471. for (p = 0; p < pathArray.length; p++) {
  25472. indexFirst = idx[p] * 3;
  25473. if (p + 1 < pathArray.length) {
  25474. indexLast = (idx[p + 1] - 1) * 3;
  25475. }
  25476. else {
  25477. indexLast = normals.length - 3;
  25478. }
  25479. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25480. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25481. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25482. normals[indexLast] = normals[indexFirst];
  25483. normals[indexLast + 1] = normals[indexFirst + 1];
  25484. normals[indexLast + 2] = normals[indexFirst + 2];
  25485. }
  25486. }
  25487. // sides
  25488. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25489. // Colors
  25490. if (customColors) {
  25491. var colors = new Float32Array(customColors.length * 4);
  25492. for (var c = 0; c < customColors.length; c++) {
  25493. colors[c * 4] = customColors[c].r;
  25494. colors[c * 4 + 1] = customColors[c].g;
  25495. colors[c * 4 + 2] = customColors[c].b;
  25496. colors[c * 4 + 3] = customColors[c].a;
  25497. }
  25498. }
  25499. // Result
  25500. var vertexData = new VertexData();
  25501. var positions32 = new Float32Array(positions);
  25502. var normals32 = new Float32Array(normals);
  25503. var uvs32 = new Float32Array(uvs);
  25504. vertexData.indices = indices;
  25505. vertexData.positions = positions32;
  25506. vertexData.normals = normals32;
  25507. vertexData.uvs = uvs32;
  25508. if (customColors) {
  25509. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25510. }
  25511. if (closePath) {
  25512. vertexData._idx = idx;
  25513. }
  25514. return vertexData;
  25515. };
  25516. /**
  25517. * Creates the VertexData of the Box.
  25518. */
  25519. VertexData.CreateBox = function (options) {
  25520. var normalsSource = [
  25521. new BABYLON.Vector3(0, 0, 1),
  25522. new BABYLON.Vector3(0, 0, -1),
  25523. new BABYLON.Vector3(1, 0, 0),
  25524. new BABYLON.Vector3(-1, 0, 0),
  25525. new BABYLON.Vector3(0, 1, 0),
  25526. new BABYLON.Vector3(0, -1, 0)
  25527. ];
  25528. var indices = [];
  25529. var positions = [];
  25530. var normals = [];
  25531. var uvs = [];
  25532. var width = options.width || options.size || 1;
  25533. var height = options.height || options.size || 1;
  25534. var depth = options.depth || options.size || 1;
  25535. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25536. var faceUV = options.faceUV || new Array(6);
  25537. var faceColors = options.faceColors;
  25538. var colors = [];
  25539. // default face colors and UV if undefined
  25540. for (var f = 0; f < 6; f++) {
  25541. if (faceUV[f] === undefined) {
  25542. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25543. }
  25544. if (faceColors && faceColors[f] === undefined) {
  25545. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25546. }
  25547. }
  25548. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25549. // Create each face in turn.
  25550. for (var index = 0; index < normalsSource.length; index++) {
  25551. var normal = normalsSource[index];
  25552. // Get two vectors perpendicular to the face normal and to each other.
  25553. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25554. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25555. // Six indices (two triangles) per face.
  25556. var verticesLength = positions.length / 3;
  25557. indices.push(verticesLength);
  25558. indices.push(verticesLength + 1);
  25559. indices.push(verticesLength + 2);
  25560. indices.push(verticesLength);
  25561. indices.push(verticesLength + 2);
  25562. indices.push(verticesLength + 3);
  25563. // Four vertices per face.
  25564. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25565. positions.push(vertex.x, vertex.y, vertex.z);
  25566. normals.push(normal.x, normal.y, normal.z);
  25567. uvs.push(faceUV[index].z, faceUV[index].w);
  25568. if (faceColors) {
  25569. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25570. }
  25571. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25572. positions.push(vertex.x, vertex.y, vertex.z);
  25573. normals.push(normal.x, normal.y, normal.z);
  25574. uvs.push(faceUV[index].x, faceUV[index].w);
  25575. if (faceColors) {
  25576. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25577. }
  25578. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25579. positions.push(vertex.x, vertex.y, vertex.z);
  25580. normals.push(normal.x, normal.y, normal.z);
  25581. uvs.push(faceUV[index].x, faceUV[index].y);
  25582. if (faceColors) {
  25583. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25584. }
  25585. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25586. positions.push(vertex.x, vertex.y, vertex.z);
  25587. normals.push(normal.x, normal.y, normal.z);
  25588. uvs.push(faceUV[index].z, faceUV[index].y);
  25589. if (faceColors) {
  25590. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25591. }
  25592. }
  25593. // sides
  25594. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25595. // Result
  25596. var vertexData = new VertexData();
  25597. vertexData.indices = indices;
  25598. vertexData.positions = positions;
  25599. vertexData.normals = normals;
  25600. vertexData.uvs = uvs;
  25601. if (faceColors) {
  25602. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25603. vertexData.colors = totalColors;
  25604. }
  25605. return vertexData;
  25606. };
  25607. /**
  25608. * Creates the VertexData of the Sphere.
  25609. */
  25610. VertexData.CreateSphere = function (options) {
  25611. var segments = options.segments || 32;
  25612. var diameterX = options.diameterX || options.diameter || 1;
  25613. var diameterY = options.diameterY || options.diameter || 1;
  25614. var diameterZ = options.diameterZ || options.diameter || 1;
  25615. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25616. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25617. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25618. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25619. var totalZRotationSteps = 2 + segments;
  25620. var totalYRotationSteps = 2 * totalZRotationSteps;
  25621. var indices = [];
  25622. var positions = [];
  25623. var normals = [];
  25624. var uvs = [];
  25625. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25626. var normalizedZ = zRotationStep / totalZRotationSteps;
  25627. var angleZ = normalizedZ * Math.PI * slice;
  25628. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25629. var normalizedY = yRotationStep / totalYRotationSteps;
  25630. var angleY = normalizedY * Math.PI * 2 * arc;
  25631. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25632. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25633. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25634. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25635. var vertex = complete.multiply(radius);
  25636. var normal = complete.divide(radius).normalize();
  25637. positions.push(vertex.x, vertex.y, vertex.z);
  25638. normals.push(normal.x, normal.y, normal.z);
  25639. uvs.push(normalizedY, normalizedZ);
  25640. }
  25641. if (zRotationStep > 0) {
  25642. var verticesCount = positions.length / 3;
  25643. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25644. indices.push((firstIndex));
  25645. indices.push((firstIndex + 1));
  25646. indices.push(firstIndex + totalYRotationSteps + 1);
  25647. indices.push((firstIndex + totalYRotationSteps + 1));
  25648. indices.push((firstIndex + 1));
  25649. indices.push((firstIndex + totalYRotationSteps + 2));
  25650. }
  25651. }
  25652. }
  25653. // Sides
  25654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25655. // Result
  25656. var vertexData = new VertexData();
  25657. vertexData.indices = indices;
  25658. vertexData.positions = positions;
  25659. vertexData.normals = normals;
  25660. vertexData.uvs = uvs;
  25661. return vertexData;
  25662. };
  25663. /**
  25664. * Creates the VertexData of the Cylinder or Cone.
  25665. */
  25666. VertexData.CreateCylinder = function (options) {
  25667. var height = options.height || 2;
  25668. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25669. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25670. var tessellation = options.tessellation || 24;
  25671. var subdivisions = options.subdivisions || 1;
  25672. var hasRings = options.hasRings;
  25673. var enclose = options.enclose;
  25674. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25675. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25676. var faceUV = options.faceUV || new Array(3);
  25677. var faceColors = options.faceColors;
  25678. // default face colors and UV if undefined
  25679. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25680. var ringNb = (hasRings) ? subdivisions : 1;
  25681. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25682. var f;
  25683. for (f = 0; f < surfaceNb; f++) {
  25684. if (faceColors && faceColors[f] === undefined) {
  25685. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25686. }
  25687. }
  25688. for (f = 0; f < surfaceNb; f++) {
  25689. if (faceUV && faceUV[f] === undefined) {
  25690. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25691. }
  25692. }
  25693. var indices = [];
  25694. var positions = [];
  25695. var normals = [];
  25696. var uvs = [];
  25697. var colors = [];
  25698. var angle_step = Math.PI * 2 * arc / tessellation;
  25699. var angle;
  25700. var h;
  25701. var radius;
  25702. var tan = (diameterBottom - diameterTop) / 2 / height;
  25703. var ringVertex = BABYLON.Vector3.Zero();
  25704. var ringNormal = BABYLON.Vector3.Zero();
  25705. var ringFirstVertex = BABYLON.Vector3.Zero();
  25706. var ringFirstNormal = BABYLON.Vector3.Zero();
  25707. var quadNormal = BABYLON.Vector3.Zero();
  25708. var Y = BABYLON.Axis.Y;
  25709. // positions, normals, uvs
  25710. var i;
  25711. var j;
  25712. var r;
  25713. var ringIdx = 1;
  25714. var s = 1; // surface index
  25715. var cs = 0;
  25716. var v = 0;
  25717. for (i = 0; i <= subdivisions; i++) {
  25718. h = i / subdivisions;
  25719. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25720. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25721. for (r = 0; r < ringIdx; r++) {
  25722. if (hasRings) {
  25723. s += r;
  25724. }
  25725. if (enclose) {
  25726. s += 2 * r;
  25727. }
  25728. for (j = 0; j <= tessellation; j++) {
  25729. angle = j * angle_step;
  25730. // position
  25731. ringVertex.x = Math.cos(-angle) * radius;
  25732. ringVertex.y = -height / 2 + h * height;
  25733. ringVertex.z = Math.sin(-angle) * radius;
  25734. // normal
  25735. if (diameterTop === 0 && i === subdivisions) {
  25736. // if no top cap, reuse former normals
  25737. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25738. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25739. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25740. }
  25741. else {
  25742. ringNormal.x = ringVertex.x;
  25743. ringNormal.z = ringVertex.z;
  25744. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25745. ringNormal.normalize();
  25746. }
  25747. // keep first ring vertex values for enclose
  25748. if (j === 0) {
  25749. ringFirstVertex.copyFrom(ringVertex);
  25750. ringFirstNormal.copyFrom(ringNormal);
  25751. }
  25752. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25753. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25754. if (hasRings) {
  25755. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25756. }
  25757. else {
  25758. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25759. }
  25760. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25761. if (faceColors) {
  25762. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25763. }
  25764. }
  25765. // if enclose, add four vertices and their dedicated normals
  25766. if (arc !== 1 && enclose) {
  25767. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25768. positions.push(0, ringVertex.y, 0);
  25769. positions.push(0, ringVertex.y, 0);
  25770. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25771. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25772. quadNormal.normalize();
  25773. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25774. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25775. quadNormal.normalize();
  25776. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25777. if (hasRings) {
  25778. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25779. }
  25780. else {
  25781. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25782. }
  25783. uvs.push(faceUV[s + 1].x, v);
  25784. uvs.push(faceUV[s + 1].z, v);
  25785. if (hasRings) {
  25786. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25787. }
  25788. else {
  25789. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25790. }
  25791. uvs.push(faceUV[s + 2].x, v);
  25792. uvs.push(faceUV[s + 2].z, v);
  25793. if (faceColors) {
  25794. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25795. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25796. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25797. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25798. }
  25799. }
  25800. if (cs !== s) {
  25801. cs = s;
  25802. }
  25803. }
  25804. }
  25805. // indices
  25806. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25807. var s;
  25808. i = 0;
  25809. for (s = 0; s < subdivisions; s++) {
  25810. for (j = 0; j < tessellation; j++) {
  25811. var i0 = i * (e + 1) + j;
  25812. var i1 = (i + 1) * (e + 1) + j;
  25813. var i2 = i * (e + 1) + (j + 1);
  25814. var i3 = (i + 1) * (e + 1) + (j + 1);
  25815. indices.push(i0, i1, i2);
  25816. indices.push(i3, i2, i1);
  25817. }
  25818. if (arc !== 1 && enclose) {
  25819. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25820. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25821. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25822. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25823. }
  25824. i = (hasRings) ? (i + 2) : (i + 1);
  25825. }
  25826. // Caps
  25827. var createCylinderCap = function (isTop) {
  25828. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25829. if (radius === 0) {
  25830. return;
  25831. }
  25832. // Cap positions, normals & uvs
  25833. var angle;
  25834. var circleVector;
  25835. var i;
  25836. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25837. var c;
  25838. if (faceColors) {
  25839. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25840. }
  25841. // cap center
  25842. var vbase = positions.length / 3;
  25843. var offset = isTop ? height / 2 : -height / 2;
  25844. var center = new BABYLON.Vector3(0, offset, 0);
  25845. positions.push(center.x, center.y, center.z);
  25846. normals.push(0, isTop ? 1 : -1, 0);
  25847. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25848. if (faceColors) {
  25849. colors.push(c.r, c.g, c.b, c.a);
  25850. }
  25851. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25852. for (i = 0; i <= tessellation; i++) {
  25853. angle = Math.PI * 2 * i * arc / tessellation;
  25854. var cos = Math.cos(-angle);
  25855. var sin = Math.sin(-angle);
  25856. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25857. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25858. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25859. normals.push(0, isTop ? 1 : -1, 0);
  25860. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25861. if (faceColors) {
  25862. colors.push(c.r, c.g, c.b, c.a);
  25863. }
  25864. }
  25865. // Cap indices
  25866. for (i = 0; i < tessellation; i++) {
  25867. if (!isTop) {
  25868. indices.push(vbase);
  25869. indices.push(vbase + (i + 1));
  25870. indices.push(vbase + (i + 2));
  25871. }
  25872. else {
  25873. indices.push(vbase);
  25874. indices.push(vbase + (i + 2));
  25875. indices.push(vbase + (i + 1));
  25876. }
  25877. }
  25878. };
  25879. // add caps to geometry
  25880. createCylinderCap(false);
  25881. createCylinderCap(true);
  25882. // Sides
  25883. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25884. var vertexData = new VertexData();
  25885. vertexData.indices = indices;
  25886. vertexData.positions = positions;
  25887. vertexData.normals = normals;
  25888. vertexData.uvs = uvs;
  25889. if (faceColors) {
  25890. vertexData.colors = colors;
  25891. }
  25892. return vertexData;
  25893. };
  25894. /**
  25895. * Creates the VertexData of the Torus.
  25896. */
  25897. VertexData.CreateTorus = function (options) {
  25898. var indices = [];
  25899. var positions = [];
  25900. var normals = [];
  25901. var uvs = [];
  25902. var diameter = options.diameter || 1;
  25903. var thickness = options.thickness || 0.5;
  25904. var tessellation = options.tessellation || 16;
  25905. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25906. var stride = tessellation + 1;
  25907. for (var i = 0; i <= tessellation; i++) {
  25908. var u = i / tessellation;
  25909. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25910. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25911. for (var j = 0; j <= tessellation; j++) {
  25912. var v = 1 - j / tessellation;
  25913. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25914. var dx = Math.cos(innerAngle);
  25915. var dy = Math.sin(innerAngle);
  25916. // Create a vertex.
  25917. var normal = new BABYLON.Vector3(dx, dy, 0);
  25918. var position = normal.scale(thickness / 2);
  25919. var textureCoordinate = new BABYLON.Vector2(u, v);
  25920. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25921. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25922. positions.push(position.x, position.y, position.z);
  25923. normals.push(normal.x, normal.y, normal.z);
  25924. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25925. // And create indices for two triangles.
  25926. var nextI = (i + 1) % stride;
  25927. var nextJ = (j + 1) % stride;
  25928. indices.push(i * stride + j);
  25929. indices.push(i * stride + nextJ);
  25930. indices.push(nextI * stride + j);
  25931. indices.push(i * stride + nextJ);
  25932. indices.push(nextI * stride + nextJ);
  25933. indices.push(nextI * stride + j);
  25934. }
  25935. }
  25936. // Sides
  25937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25938. // Result
  25939. var vertexData = new VertexData();
  25940. vertexData.indices = indices;
  25941. vertexData.positions = positions;
  25942. vertexData.normals = normals;
  25943. vertexData.uvs = uvs;
  25944. return vertexData;
  25945. };
  25946. /**
  25947. * Creates the VertexData of the LineSystem.
  25948. */
  25949. VertexData.CreateLineSystem = function (options) {
  25950. var indices = [];
  25951. var positions = [];
  25952. var lines = options.lines;
  25953. var idx = 0;
  25954. for (var l = 0; l < lines.length; l++) {
  25955. var points = lines[l];
  25956. for (var index = 0; index < points.length; index++) {
  25957. positions.push(points[index].x, points[index].y, points[index].z);
  25958. if (index > 0) {
  25959. indices.push(idx - 1);
  25960. indices.push(idx);
  25961. }
  25962. idx++;
  25963. }
  25964. }
  25965. var vertexData = new VertexData();
  25966. vertexData.indices = indices;
  25967. vertexData.positions = positions;
  25968. return vertexData;
  25969. };
  25970. /**
  25971. * Create the VertexData of the DashedLines.
  25972. */
  25973. VertexData.CreateDashedLines = function (options) {
  25974. var dashSize = options.dashSize || 3;
  25975. var gapSize = options.gapSize || 1;
  25976. var dashNb = options.dashNb || 200;
  25977. var points = options.points;
  25978. var positions = new Array();
  25979. var indices = new Array();
  25980. var curvect = BABYLON.Vector3.Zero();
  25981. var lg = 0;
  25982. var nb = 0;
  25983. var shft = 0;
  25984. var dashshft = 0;
  25985. var curshft = 0;
  25986. var idx = 0;
  25987. var i = 0;
  25988. for (i = 0; i < points.length - 1; i++) {
  25989. points[i + 1].subtractToRef(points[i], curvect);
  25990. lg += curvect.length();
  25991. }
  25992. shft = lg / dashNb;
  25993. dashshft = dashSize * shft / (dashSize + gapSize);
  25994. for (i = 0; i < points.length - 1; i++) {
  25995. points[i + 1].subtractToRef(points[i], curvect);
  25996. nb = Math.floor(curvect.length() / shft);
  25997. curvect.normalize();
  25998. for (var j = 0; j < nb; j++) {
  25999. curshft = shft * j;
  26000. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26001. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26002. indices.push(idx, idx + 1);
  26003. idx += 2;
  26004. }
  26005. }
  26006. // Result
  26007. var vertexData = new VertexData();
  26008. vertexData.positions = positions;
  26009. vertexData.indices = indices;
  26010. return vertexData;
  26011. };
  26012. /**
  26013. * Creates the VertexData of the Ground.
  26014. */
  26015. VertexData.CreateGround = function (options) {
  26016. var indices = [];
  26017. var positions = [];
  26018. var normals = [];
  26019. var uvs = [];
  26020. var row, col;
  26021. var width = options.width || 1;
  26022. var height = options.height || 1;
  26023. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26024. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26025. for (row = 0; row <= subdivisionsY; row++) {
  26026. for (col = 0; col <= subdivisionsX; col++) {
  26027. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26028. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26029. positions.push(position.x, position.y, position.z);
  26030. normals.push(normal.x, normal.y, normal.z);
  26031. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26032. }
  26033. }
  26034. for (row = 0; row < subdivisionsY; row++) {
  26035. for (col = 0; col < subdivisionsX; col++) {
  26036. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26037. indices.push(col + 1 + row * (subdivisionsX + 1));
  26038. indices.push(col + row * (subdivisionsX + 1));
  26039. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26040. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26041. indices.push(col + row * (subdivisionsX + 1));
  26042. }
  26043. }
  26044. // Result
  26045. var vertexData = new VertexData();
  26046. vertexData.indices = indices;
  26047. vertexData.positions = positions;
  26048. vertexData.normals = normals;
  26049. vertexData.uvs = uvs;
  26050. return vertexData;
  26051. };
  26052. /**
  26053. * Creates the VertexData of the TiledGround.
  26054. */
  26055. VertexData.CreateTiledGround = function (options) {
  26056. var xmin = options.xmin || -1.0;
  26057. var zmin = options.zmin || -1.0;
  26058. var xmax = options.xmax || 1.0;
  26059. var zmax = options.zmax || 1.0;
  26060. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26061. var precision = options.precision || { w: 1, h: 1 };
  26062. var indices = [];
  26063. var positions = [];
  26064. var normals = [];
  26065. var uvs = [];
  26066. var row, col, tileRow, tileCol;
  26067. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26068. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26069. precision.w = (precision.w < 1) ? 1 : precision.w;
  26070. precision.h = (precision.h < 1) ? 1 : precision.h;
  26071. var tileSize = {
  26072. 'w': (xmax - xmin) / subdivisions.w,
  26073. 'h': (zmax - zmin) / subdivisions.h
  26074. };
  26075. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26076. // Indices
  26077. var base = positions.length / 3;
  26078. var rowLength = precision.w + 1;
  26079. for (row = 0; row < precision.h; row++) {
  26080. for (col = 0; col < precision.w; col++) {
  26081. var square = [
  26082. base + col + row * rowLength,
  26083. base + (col + 1) + row * rowLength,
  26084. base + (col + 1) + (row + 1) * rowLength,
  26085. base + col + (row + 1) * rowLength
  26086. ];
  26087. indices.push(square[1]);
  26088. indices.push(square[2]);
  26089. indices.push(square[3]);
  26090. indices.push(square[0]);
  26091. indices.push(square[1]);
  26092. indices.push(square[3]);
  26093. }
  26094. }
  26095. // Position, normals and uvs
  26096. var position = BABYLON.Vector3.Zero();
  26097. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26098. for (row = 0; row <= precision.h; row++) {
  26099. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26100. for (col = 0; col <= precision.w; col++) {
  26101. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26102. position.y = 0;
  26103. positions.push(position.x, position.y, position.z);
  26104. normals.push(normal.x, normal.y, normal.z);
  26105. uvs.push(col / precision.w, row / precision.h);
  26106. }
  26107. }
  26108. }
  26109. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26110. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26111. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26112. }
  26113. }
  26114. // Result
  26115. var vertexData = new VertexData();
  26116. vertexData.indices = indices;
  26117. vertexData.positions = positions;
  26118. vertexData.normals = normals;
  26119. vertexData.uvs = uvs;
  26120. return vertexData;
  26121. };
  26122. /**
  26123. * Creates the VertexData of the Ground designed from a heightmap.
  26124. */
  26125. VertexData.CreateGroundFromHeightMap = function (options) {
  26126. var indices = [];
  26127. var positions = [];
  26128. var normals = [];
  26129. var uvs = [];
  26130. var row, col;
  26131. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26132. // Vertices
  26133. for (row = 0; row <= options.subdivisions; row++) {
  26134. for (col = 0; col <= options.subdivisions; col++) {
  26135. 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));
  26136. // Compute height
  26137. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26138. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26139. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26140. var r = options.buffer[pos] / 255.0;
  26141. var g = options.buffer[pos + 1] / 255.0;
  26142. var b = options.buffer[pos + 2] / 255.0;
  26143. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26144. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26145. // Add vertex
  26146. positions.push(position.x, position.y, position.z);
  26147. normals.push(0, 0, 0);
  26148. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26149. }
  26150. }
  26151. // Indices
  26152. for (row = 0; row < options.subdivisions; row++) {
  26153. for (col = 0; col < options.subdivisions; col++) {
  26154. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26155. indices.push(col + 1 + row * (options.subdivisions + 1));
  26156. indices.push(col + row * (options.subdivisions + 1));
  26157. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26158. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26159. indices.push(col + row * (options.subdivisions + 1));
  26160. }
  26161. }
  26162. // Normals
  26163. VertexData.ComputeNormals(positions, indices, normals);
  26164. // Result
  26165. var vertexData = new VertexData();
  26166. vertexData.indices = indices;
  26167. vertexData.positions = positions;
  26168. vertexData.normals = normals;
  26169. vertexData.uvs = uvs;
  26170. return vertexData;
  26171. };
  26172. /**
  26173. * Creates the VertexData of the Plane.
  26174. */
  26175. VertexData.CreatePlane = function (options) {
  26176. var indices = [];
  26177. var positions = [];
  26178. var normals = [];
  26179. var uvs = [];
  26180. var width = options.width || options.size || 1;
  26181. var height = options.height || options.size || 1;
  26182. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26183. // Vertices
  26184. var halfWidth = width / 2.0;
  26185. var halfHeight = height / 2.0;
  26186. positions.push(-halfWidth, -halfHeight, 0);
  26187. normals.push(0, 0, -1.0);
  26188. uvs.push(0.0, 0.0);
  26189. positions.push(halfWidth, -halfHeight, 0);
  26190. normals.push(0, 0, -1.0);
  26191. uvs.push(1.0, 0.0);
  26192. positions.push(halfWidth, halfHeight, 0);
  26193. normals.push(0, 0, -1.0);
  26194. uvs.push(1.0, 1.0);
  26195. positions.push(-halfWidth, halfHeight, 0);
  26196. normals.push(0, 0, -1.0);
  26197. uvs.push(0.0, 1.0);
  26198. // Indices
  26199. indices.push(0);
  26200. indices.push(1);
  26201. indices.push(2);
  26202. indices.push(0);
  26203. indices.push(2);
  26204. indices.push(3);
  26205. // Sides
  26206. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26207. // Result
  26208. var vertexData = new VertexData();
  26209. vertexData.indices = indices;
  26210. vertexData.positions = positions;
  26211. vertexData.normals = normals;
  26212. vertexData.uvs = uvs;
  26213. return vertexData;
  26214. };
  26215. /**
  26216. * Creates the VertexData of the Disc or regular Polygon.
  26217. */
  26218. VertexData.CreateDisc = function (options) {
  26219. var positions = [];
  26220. var indices = [];
  26221. var normals = [];
  26222. var uvs = [];
  26223. var radius = options.radius || 0.5;
  26224. var tessellation = options.tessellation || 64;
  26225. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26226. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26227. // positions and uvs
  26228. positions.push(0, 0, 0); // disc center first
  26229. uvs.push(0.5, 0.5);
  26230. var theta = Math.PI * 2 * arc;
  26231. var step = theta / tessellation;
  26232. for (var a = 0; a < theta; a += step) {
  26233. var x = Math.cos(a);
  26234. var y = Math.sin(a);
  26235. var u = (x + 1) / 2;
  26236. var v = (1 - y) / 2;
  26237. positions.push(radius * x, radius * y, 0);
  26238. uvs.push(u, v);
  26239. }
  26240. if (arc === 1) {
  26241. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26242. uvs.push(uvs[2], uvs[3]);
  26243. }
  26244. //indices
  26245. var vertexNb = positions.length / 3;
  26246. for (var i = 1; i < vertexNb - 1; i++) {
  26247. indices.push(i + 1, 0, i);
  26248. }
  26249. // result
  26250. VertexData.ComputeNormals(positions, indices, normals);
  26251. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26252. var vertexData = new VertexData();
  26253. vertexData.indices = indices;
  26254. vertexData.positions = positions;
  26255. vertexData.normals = normals;
  26256. vertexData.uvs = uvs;
  26257. return vertexData;
  26258. };
  26259. /**
  26260. * Re-creates the VertexData of the Polygon for sideOrientation.
  26261. */
  26262. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26263. var faceUV = fUV || new Array(3);
  26264. var faceColors = fColors;
  26265. var colors = [];
  26266. // default face colors and UV if undefined
  26267. for (var f = 0; f < 3; f++) {
  26268. if (faceUV[f] === undefined) {
  26269. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26270. }
  26271. if (faceColors && faceColors[f] === undefined) {
  26272. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26273. }
  26274. }
  26275. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26276. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26277. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26278. var indices = polygon.getIndices();
  26279. // set face colours and textures
  26280. var idx = 0;
  26281. var face = 0;
  26282. for (var index = 0; index < normals.length; index += 3) {
  26283. //Edge Face no. 1
  26284. if (Math.abs(normals[index + 1]) == 0) {
  26285. face = 1;
  26286. }
  26287. //Top Face no. 0
  26288. if (normals[index + 1] == 1) {
  26289. face = 0;
  26290. }
  26291. //Bottom Face no. 2
  26292. if (normals[index + 1] == -1) {
  26293. face = 2;
  26294. }
  26295. idx = index / 3;
  26296. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26297. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26298. if (faceColors) {
  26299. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26300. }
  26301. }
  26302. // sides
  26303. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26304. // Result
  26305. var vertexData = new VertexData();
  26306. vertexData.indices = indices;
  26307. vertexData.positions = positions;
  26308. vertexData.normals = normals;
  26309. vertexData.uvs = uvs;
  26310. if (faceColors) {
  26311. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26312. vertexData.colors = totalColors;
  26313. }
  26314. return vertexData;
  26315. };
  26316. /**
  26317. * Creates the VertexData of the IcoSphere.
  26318. */
  26319. VertexData.CreateIcoSphere = function (options) {
  26320. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26321. var radius = options.radius || 1;
  26322. var flat = (options.flat === undefined) ? true : options.flat;
  26323. var subdivisions = options.subdivisions || 4;
  26324. var radiusX = options.radiusX || radius;
  26325. var radiusY = options.radiusY || radius;
  26326. var radiusZ = options.radiusZ || radius;
  26327. var t = (1 + Math.sqrt(5)) / 2;
  26328. // 12 vertex x,y,z
  26329. var ico_vertices = [
  26330. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26331. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26332. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26333. ];
  26334. // index of 3 vertex makes a face of icopshere
  26335. var ico_indices = [
  26336. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26337. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26338. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26339. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26340. ];
  26341. // vertex for uv have aliased position, not for UV
  26342. var vertices_unalias_id = [
  26343. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26344. // vertex alias
  26345. 0,
  26346. 2,
  26347. 3,
  26348. 3,
  26349. 3,
  26350. 4,
  26351. 7,
  26352. 8,
  26353. 9,
  26354. 9,
  26355. 10,
  26356. 11 // 23: B + 12
  26357. ];
  26358. // uv as integer step (not pixels !)
  26359. var ico_vertexuv = [
  26360. 5, 1, 3, 1, 6, 4, 0, 0,
  26361. 5, 3, 4, 2, 2, 2, 4, 0,
  26362. 2, 0, 1, 1, 6, 0, 6, 2,
  26363. // vertex alias (for same vertex on different faces)
  26364. 0, 4,
  26365. 3, 3,
  26366. 4, 4,
  26367. 3, 1,
  26368. 4, 2,
  26369. 4, 4,
  26370. 0, 2,
  26371. 1, 1,
  26372. 2, 2,
  26373. 3, 3,
  26374. 1, 3,
  26375. 2, 4 // 23: B + 12
  26376. ];
  26377. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26378. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26379. // First island of uv mapping
  26380. // v = 4h 3+ 2
  26381. // v = 3h 9+ 4
  26382. // v = 2h 9+ 5 B
  26383. // v = 1h 9 1 0
  26384. // v = 0h 3 8 7 A
  26385. // u = 0 1 2 3 4 5 6 *a
  26386. // Second island of uv mapping
  26387. // v = 4h 0+ B+ 4+
  26388. // v = 3h A+ 2+
  26389. // v = 2h 7+ 6 3+
  26390. // v = 1h 8+ 3+
  26391. // v = 0h
  26392. // u = 0 1 2 3 4 5 6 *a
  26393. // Face layout on texture UV mapping
  26394. // ============
  26395. // \ 4 /\ 16 / ======
  26396. // \ / \ / /\ 11 /
  26397. // \/ 7 \/ / \ /
  26398. // ======= / 10 \/
  26399. // /\ 17 /\ =======
  26400. // / \ / \ \ 15 /\
  26401. // / 8 \/ 12 \ \ / \
  26402. // ============ \/ 6 \
  26403. // \ 18 /\ ============
  26404. // \ / \ \ 5 /\ 0 /
  26405. // \/ 13 \ \ / \ /
  26406. // ======= \/ 1 \/
  26407. // =============
  26408. // /\ 19 /\ 2 /\
  26409. // / \ / \ / \
  26410. // / 14 \/ 9 \/ 3 \
  26411. // ===================
  26412. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26413. var ustep = 138 / 1024;
  26414. var vstep = 239 / 1024;
  26415. var uoffset = 60 / 1024;
  26416. var voffset = 26 / 1024;
  26417. // Second island should have margin, not to touch the first island
  26418. // avoid any borderline artefact in pixel rounding
  26419. var island_u_offset = -40 / 1024;
  26420. var island_v_offset = +20 / 1024;
  26421. // face is either island 0 or 1 :
  26422. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26423. var island = [
  26424. 0, 0, 0, 0, 1,
  26425. 0, 0, 1, 1, 0,
  26426. 0, 0, 1, 1, 0,
  26427. 0, 1, 1, 1, 0 // 15 - 19
  26428. ];
  26429. var indices = [];
  26430. var positions = [];
  26431. var normals = [];
  26432. var uvs = [];
  26433. var current_indice = 0;
  26434. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26435. var face_vertex_pos = new Array(3);
  26436. var face_vertex_uv = new Array(3);
  26437. var v012;
  26438. for (v012 = 0; v012 < 3; v012++) {
  26439. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26440. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26441. }
  26442. // create all with normals
  26443. for (var face = 0; face < 20; face++) {
  26444. // 3 vertex per face
  26445. for (v012 = 0; v012 < 3; v012++) {
  26446. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26447. var v_id = ico_indices[3 * face + v012];
  26448. // vertex have 3D position (x,y,z)
  26449. 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]);
  26450. // Normalize to get normal, then scale to radius
  26451. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26452. // uv Coordinates from vertex ID
  26453. 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);
  26454. }
  26455. // Subdivide the face (interpolate pos, norm, uv)
  26456. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26457. // - norm is linear interpolation of vertex corner normal
  26458. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26459. // - uv is linear interpolation
  26460. //
  26461. // Topology is as below for sub-divide by 2
  26462. // vertex shown as v0,v1,v2
  26463. // interp index is i1 to progress in range [v0,v1[
  26464. // interp index is i2 to progress in range [v0,v2[
  26465. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26466. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26467. //
  26468. //
  26469. // i2 v2
  26470. // ^ ^
  26471. // / / \
  26472. // / / \
  26473. // / / \
  26474. // / / (0,1) \
  26475. // / #---------\
  26476. // / / \ (0,0)'/ \
  26477. // / / \ / \
  26478. // / / \ / \
  26479. // / / (0,0) \ / (1,0) \
  26480. // / #---------#---------\
  26481. // v0 v1
  26482. //
  26483. // --------------------> i1
  26484. //
  26485. // interp of (i1,i2):
  26486. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26487. // along i1 : lerp(x0,x1, i1/(S-i2))
  26488. //
  26489. // centroid of triangle is needed to get help normal computation
  26490. // (c1,c2) are used for centroid location
  26491. var interp_vertex = function (i1, i2, c1, c2) {
  26492. // vertex is interpolated from
  26493. // - face_vertex_pos[0..2]
  26494. // - face_vertex_uv[0..2]
  26495. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26496. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26497. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26498. pos_interp.normalize();
  26499. var vertex_normal;
  26500. if (flat) {
  26501. // in flat mode, recalculate normal as face centroid normal
  26502. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26503. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26504. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26505. }
  26506. else {
  26507. // in smooth mode, recalculate normal from each single vertex position
  26508. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26509. }
  26510. // Vertex normal need correction due to X,Y,Z radius scaling
  26511. vertex_normal.x /= radiusX;
  26512. vertex_normal.y /= radiusY;
  26513. vertex_normal.z /= radiusZ;
  26514. vertex_normal.normalize();
  26515. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26516. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26517. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26518. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26519. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26520. uvs.push(uv_interp.x, uv_interp.y);
  26521. // push each vertex has member of a face
  26522. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26523. indices.push(current_indice);
  26524. current_indice++;
  26525. };
  26526. for (var i2 = 0; i2 < subdivisions; i2++) {
  26527. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26528. // face : (i1,i2) for /\ :
  26529. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26530. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26531. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26532. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26533. if (i1 + i2 + 1 < subdivisions) {
  26534. // face : (i1,i2)' for \/ :
  26535. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26536. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26537. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26538. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26539. }
  26540. }
  26541. }
  26542. }
  26543. // Sides
  26544. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26545. // Result
  26546. var vertexData = new VertexData();
  26547. vertexData.indices = indices;
  26548. vertexData.positions = positions;
  26549. vertexData.normals = normals;
  26550. vertexData.uvs = uvs;
  26551. return vertexData;
  26552. };
  26553. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26554. /**
  26555. * Creates the VertexData of the Polyhedron.
  26556. */
  26557. VertexData.CreatePolyhedron = function (options) {
  26558. // provided polyhedron types :
  26559. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26560. // 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)
  26561. var polyhedra = [];
  26562. 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]] };
  26563. 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]] };
  26564. polyhedra[2] = {
  26565. 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]],
  26566. 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]]
  26567. };
  26568. polyhedra[3] = {
  26569. 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]],
  26570. 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]]
  26571. };
  26572. polyhedra[4] = {
  26573. 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]],
  26574. 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]]
  26575. };
  26576. 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]] };
  26577. 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]] };
  26578. 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]] };
  26579. 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]] };
  26580. 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]] };
  26581. 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]] };
  26582. 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]] };
  26583. 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]] };
  26584. 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]] };
  26585. polyhedra[14] = {
  26586. 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]],
  26587. 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]]
  26588. };
  26589. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26590. var size = options.size;
  26591. var sizeX = options.sizeX || size || 1;
  26592. var sizeY = options.sizeY || size || 1;
  26593. var sizeZ = options.sizeZ || size || 1;
  26594. var data = options.custom || polyhedra[type];
  26595. var nbfaces = data.face.length;
  26596. var faceUV = options.faceUV || new Array(nbfaces);
  26597. var faceColors = options.faceColors;
  26598. var flat = (options.flat === undefined) ? true : options.flat;
  26599. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26600. var positions = [];
  26601. var indices = [];
  26602. var normals = [];
  26603. var uvs = [];
  26604. var colors = [];
  26605. var index = 0;
  26606. var faceIdx = 0; // face cursor in the array "indexes"
  26607. var indexes = [];
  26608. var i = 0;
  26609. var f = 0;
  26610. var u, v, ang, x, y, tmp;
  26611. // default face colors and UV if undefined
  26612. if (flat) {
  26613. for (f = 0; f < nbfaces; f++) {
  26614. if (faceColors && faceColors[f] === undefined) {
  26615. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26616. }
  26617. if (faceUV && faceUV[f] === undefined) {
  26618. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26619. }
  26620. }
  26621. }
  26622. if (!flat) {
  26623. for (i = 0; i < data.vertex.length; i++) {
  26624. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26625. uvs.push(0, 0);
  26626. }
  26627. for (f = 0; f < nbfaces; f++) {
  26628. for (i = 0; i < data.face[f].length - 2; i++) {
  26629. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26630. }
  26631. }
  26632. }
  26633. else {
  26634. for (f = 0; f < nbfaces; f++) {
  26635. var fl = data.face[f].length; // number of vertices of the current face
  26636. ang = 2 * Math.PI / fl;
  26637. x = 0.5 * Math.tan(ang / 2);
  26638. y = 0.5;
  26639. // positions, uvs, colors
  26640. for (i = 0; i < fl; i++) {
  26641. // positions
  26642. 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);
  26643. indexes.push(index);
  26644. index++;
  26645. // uvs
  26646. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26647. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26648. uvs.push(u, v);
  26649. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26650. y = x * Math.sin(ang) + y * Math.cos(ang);
  26651. x = tmp;
  26652. // colors
  26653. if (faceColors) {
  26654. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26655. }
  26656. }
  26657. // indices from indexes
  26658. for (i = 0; i < fl - 2; i++) {
  26659. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26660. }
  26661. faceIdx += fl;
  26662. }
  26663. }
  26664. VertexData.ComputeNormals(positions, indices, normals);
  26665. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26666. var vertexData = new VertexData();
  26667. vertexData.positions = positions;
  26668. vertexData.indices = indices;
  26669. vertexData.normals = normals;
  26670. vertexData.uvs = uvs;
  26671. if (faceColors && flat) {
  26672. vertexData.colors = colors;
  26673. }
  26674. return vertexData;
  26675. };
  26676. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26677. /**
  26678. * Creates the VertexData of the Torus Knot.
  26679. */
  26680. VertexData.CreateTorusKnot = function (options) {
  26681. var indices = [];
  26682. var positions = [];
  26683. var normals = [];
  26684. var uvs = [];
  26685. var radius = options.radius || 2;
  26686. var tube = options.tube || 0.5;
  26687. var radialSegments = options.radialSegments || 32;
  26688. var tubularSegments = options.tubularSegments || 32;
  26689. var p = options.p || 2;
  26690. var q = options.q || 3;
  26691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26692. // Helper
  26693. var getPos = function (angle) {
  26694. var cu = Math.cos(angle);
  26695. var su = Math.sin(angle);
  26696. var quOverP = q / p * angle;
  26697. var cs = Math.cos(quOverP);
  26698. var tx = radius * (2 + cs) * 0.5 * cu;
  26699. var ty = radius * (2 + cs) * su * 0.5;
  26700. var tz = radius * Math.sin(quOverP) * 0.5;
  26701. return new BABYLON.Vector3(tx, ty, tz);
  26702. };
  26703. // Vertices
  26704. var i;
  26705. var j;
  26706. for (i = 0; i <= radialSegments; i++) {
  26707. var modI = i % radialSegments;
  26708. var u = modI / radialSegments * 2 * p * Math.PI;
  26709. var p1 = getPos(u);
  26710. var p2 = getPos(u + 0.01);
  26711. var tang = p2.subtract(p1);
  26712. var n = p2.add(p1);
  26713. var bitan = BABYLON.Vector3.Cross(tang, n);
  26714. n = BABYLON.Vector3.Cross(bitan, tang);
  26715. bitan.normalize();
  26716. n.normalize();
  26717. for (j = 0; j < tubularSegments; j++) {
  26718. var modJ = j % tubularSegments;
  26719. var v = modJ / tubularSegments * 2 * Math.PI;
  26720. var cx = -tube * Math.cos(v);
  26721. var cy = tube * Math.sin(v);
  26722. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26723. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26724. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26725. uvs.push(i / radialSegments);
  26726. uvs.push(j / tubularSegments);
  26727. }
  26728. }
  26729. for (i = 0; i < radialSegments; i++) {
  26730. for (j = 0; j < tubularSegments; j++) {
  26731. var jNext = (j + 1) % tubularSegments;
  26732. var a = i * tubularSegments + j;
  26733. var b = (i + 1) * tubularSegments + j;
  26734. var c = (i + 1) * tubularSegments + jNext;
  26735. var d = i * tubularSegments + jNext;
  26736. indices.push(d);
  26737. indices.push(b);
  26738. indices.push(a);
  26739. indices.push(d);
  26740. indices.push(c);
  26741. indices.push(b);
  26742. }
  26743. }
  26744. // Normals
  26745. VertexData.ComputeNormals(positions, indices, normals);
  26746. // Sides
  26747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26748. // Result
  26749. var vertexData = new VertexData();
  26750. vertexData.indices = indices;
  26751. vertexData.positions = positions;
  26752. vertexData.normals = normals;
  26753. vertexData.uvs = uvs;
  26754. return vertexData;
  26755. };
  26756. // Tools
  26757. /**
  26758. * @param {any} - positions (number[] or Float32Array)
  26759. * @param {any} - indices (number[] or Uint16Array)
  26760. * @param {any} - normals (number[] or Float32Array)
  26761. * options (optional) :
  26762. * facetPositions : optional array of facet positions (vector3)
  26763. * facetNormals : optional array of facet normals (vector3)
  26764. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26765. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26766. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26767. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26768. * bInfo : optional bounding info, required for facetPartitioning computation
  26769. */
  26770. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26771. // temporary scalar variables
  26772. var index = 0; // facet index
  26773. var p1p2x = 0.0; // p1p2 vector x coordinate
  26774. var p1p2y = 0.0; // p1p2 vector y coordinate
  26775. var p1p2z = 0.0; // p1p2 vector z coordinate
  26776. var p3p2x = 0.0; // p3p2 vector x coordinate
  26777. var p3p2y = 0.0; // p3p2 vector y coordinate
  26778. var p3p2z = 0.0; // p3p2 vector z coordinate
  26779. var faceNormalx = 0.0; // facet normal x coordinate
  26780. var faceNormaly = 0.0; // facet normal y coordinate
  26781. var faceNormalz = 0.0; // facet normal z coordinate
  26782. var length = 0.0; // facet normal length before normalization
  26783. var v1x = 0; // vector1 x index in the positions array
  26784. var v1y = 0; // vector1 y index in the positions array
  26785. var v1z = 0; // vector1 z index in the positions array
  26786. var v2x = 0; // vector2 x index in the positions array
  26787. var v2y = 0; // vector2 y index in the positions array
  26788. var v2z = 0; // vector2 z index in the positions array
  26789. var v3x = 0; // vector3 x index in the positions array
  26790. var v3y = 0; // vector3 y index in the positions array
  26791. var v3z = 0; // vector3 z index in the positions array
  26792. var computeFacetNormals = false;
  26793. var computeFacetPositions = false;
  26794. var computeFacetPartitioning = false;
  26795. var faceNormalSign = 1;
  26796. if (options) {
  26797. computeFacetNormals = (options.facetNormals) ? true : false;
  26798. computeFacetPositions = (options.facetPositions) ? true : false;
  26799. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26800. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26801. }
  26802. // facetPartitioning reinit if needed
  26803. if (computeFacetPartitioning) {
  26804. var ox = 0; // X partitioning index for facet position
  26805. var oy = 0; // Y partinioning index for facet position
  26806. var oz = 0; // Z partinioning index for facet position
  26807. var b1x = 0; // X partitioning index for facet v1 vertex
  26808. var b1y = 0; // Y partitioning index for facet v1 vertex
  26809. var b1z = 0; // z partitioning index for facet v1 vertex
  26810. var b2x = 0; // X partitioning index for facet v2 vertex
  26811. var b2y = 0; // Y partitioning index for facet v2 vertex
  26812. var b2z = 0; // Z partitioning index for facet v2 vertex
  26813. var b3x = 0; // X partitioning index for facet v3 vertex
  26814. var b3y = 0; // Y partitioning index for facet v3 vertex
  26815. var b3z = 0; // Z partitioning index for facet v3 vertex
  26816. var block_idx_o = 0; // facet barycenter block index
  26817. var block_idx_v1 = 0; // v1 vertex block index
  26818. var block_idx_v2 = 0; // v2 vertex block index
  26819. var block_idx_v3 = 0; // v3 vertex block index
  26820. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26821. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26822. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26823. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26824. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26825. var subSq = options.subDiv.max * options.subDiv.max;
  26826. options.facetPartitioning.length = 0;
  26827. }
  26828. // reset the normals
  26829. for (index = 0; index < positions.length; index++) {
  26830. normals[index] = 0.0;
  26831. }
  26832. // Loop : 1 indice triplet = 1 facet
  26833. var nbFaces = indices.length / 3;
  26834. for (index = 0; index < nbFaces; index++) {
  26835. // get the indexes of the coordinates of each vertex of the facet
  26836. v1x = indices[index * 3] * 3;
  26837. v1y = v1x + 1;
  26838. v1z = v1x + 2;
  26839. v2x = indices[index * 3 + 1] * 3;
  26840. v2y = v2x + 1;
  26841. v2z = v2x + 2;
  26842. v3x = indices[index * 3 + 2] * 3;
  26843. v3y = v3x + 1;
  26844. v3z = v3x + 2;
  26845. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26846. p1p2y = positions[v1y] - positions[v2y];
  26847. p1p2z = positions[v1z] - positions[v2z];
  26848. p3p2x = positions[v3x] - positions[v2x];
  26849. p3p2y = positions[v3y] - positions[v2y];
  26850. p3p2z = positions[v3z] - positions[v2z];
  26851. // compute the face normal with the cross product
  26852. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26853. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26854. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26855. // normalize this normal and store it in the array facetData
  26856. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26857. length = (length === 0) ? 1.0 : length;
  26858. faceNormalx /= length;
  26859. faceNormaly /= length;
  26860. faceNormalz /= length;
  26861. if (computeFacetNormals) {
  26862. options.facetNormals[index].x = faceNormalx;
  26863. options.facetNormals[index].y = faceNormaly;
  26864. options.facetNormals[index].z = faceNormalz;
  26865. }
  26866. if (computeFacetPositions) {
  26867. // compute and the facet barycenter coordinates in the array facetPositions
  26868. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26869. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26870. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26871. }
  26872. if (computeFacetPartitioning) {
  26873. // store the facet indexes in arrays in the main facetPartitioning array :
  26874. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26875. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26876. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26877. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26878. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26879. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26880. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26881. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26882. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26883. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26884. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26885. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26886. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26887. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26888. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26889. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26890. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26891. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26892. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26893. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26894. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26895. // push each facet index in each block containing the vertex
  26896. options.facetPartitioning[block_idx_v1].push(index);
  26897. if (block_idx_v2 != block_idx_v1) {
  26898. options.facetPartitioning[block_idx_v2].push(index);
  26899. }
  26900. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26901. options.facetPartitioning[block_idx_v3].push(index);
  26902. }
  26903. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26904. options.facetPartitioning[block_idx_o].push(index);
  26905. }
  26906. }
  26907. // compute the normals anyway
  26908. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26909. normals[v1y] += faceNormaly;
  26910. normals[v1z] += faceNormalz;
  26911. normals[v2x] += faceNormalx;
  26912. normals[v2y] += faceNormaly;
  26913. normals[v2z] += faceNormalz;
  26914. normals[v3x] += faceNormalx;
  26915. normals[v3y] += faceNormaly;
  26916. normals[v3z] += faceNormalz;
  26917. }
  26918. // last normalization of each normal
  26919. for (index = 0; index < normals.length / 3; index++) {
  26920. faceNormalx = normals[index * 3];
  26921. faceNormaly = normals[index * 3 + 1];
  26922. faceNormalz = normals[index * 3 + 2];
  26923. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26924. length = (length === 0) ? 1.0 : length;
  26925. faceNormalx /= length;
  26926. faceNormaly /= length;
  26927. faceNormalz /= length;
  26928. normals[index * 3] = faceNormalx;
  26929. normals[index * 3 + 1] = faceNormaly;
  26930. normals[index * 3 + 2] = faceNormalz;
  26931. }
  26932. };
  26933. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26934. var li = indices.length;
  26935. var ln = normals.length;
  26936. var i;
  26937. var n;
  26938. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26939. switch (sideOrientation) {
  26940. case BABYLON.Mesh.FRONTSIDE:
  26941. // nothing changed
  26942. break;
  26943. case BABYLON.Mesh.BACKSIDE:
  26944. var tmp;
  26945. // indices
  26946. for (i = 0; i < li; i += 3) {
  26947. tmp = indices[i];
  26948. indices[i] = indices[i + 2];
  26949. indices[i + 2] = tmp;
  26950. }
  26951. // normals
  26952. for (n = 0; n < ln; n++) {
  26953. normals[n] = -normals[n];
  26954. }
  26955. break;
  26956. case BABYLON.Mesh.DOUBLESIDE:
  26957. // positions
  26958. var lp = positions.length;
  26959. var l = lp / 3;
  26960. for (var p = 0; p < lp; p++) {
  26961. positions[lp + p] = positions[p];
  26962. }
  26963. // indices
  26964. for (i = 0; i < li; i += 3) {
  26965. indices[i + li] = indices[i + 2] + l;
  26966. indices[i + 1 + li] = indices[i + 1] + l;
  26967. indices[i + 2 + li] = indices[i] + l;
  26968. }
  26969. // normals
  26970. for (n = 0; n < ln; n++) {
  26971. normals[ln + n] = -normals[n];
  26972. }
  26973. // uvs
  26974. var lu = uvs.length;
  26975. var u = 0;
  26976. for (u = 0; u < lu; u++) {
  26977. uvs[u + lu] = uvs[u];
  26978. }
  26979. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26980. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26981. u = 0;
  26982. for (i = 0; i < lu / 2; i++) {
  26983. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26984. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26985. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26986. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26987. u += 2;
  26988. }
  26989. break;
  26990. }
  26991. };
  26992. /**
  26993. * Creates a new VertexData from the imported parameters.
  26994. */
  26995. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26996. var vertexData = new VertexData();
  26997. // positions
  26998. var positions = parsedVertexData.positions;
  26999. if (positions) {
  27000. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27001. }
  27002. // normals
  27003. var normals = parsedVertexData.normals;
  27004. if (normals) {
  27005. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27006. }
  27007. // tangents
  27008. var tangents = parsedVertexData.tangents;
  27009. if (tangents) {
  27010. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27011. }
  27012. // uvs
  27013. var uvs = parsedVertexData.uvs;
  27014. if (uvs) {
  27015. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27016. }
  27017. // uv2s
  27018. var uv2s = parsedVertexData.uv2s;
  27019. if (uv2s) {
  27020. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27021. }
  27022. // uv3s
  27023. var uv3s = parsedVertexData.uv3s;
  27024. if (uv3s) {
  27025. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27026. }
  27027. // uv4s
  27028. var uv4s = parsedVertexData.uv4s;
  27029. if (uv4s) {
  27030. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27031. }
  27032. // uv5s
  27033. var uv5s = parsedVertexData.uv5s;
  27034. if (uv5s) {
  27035. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27036. }
  27037. // uv6s
  27038. var uv6s = parsedVertexData.uv6s;
  27039. if (uv6s) {
  27040. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27041. }
  27042. // colors
  27043. var colors = parsedVertexData.colors;
  27044. if (colors) {
  27045. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27046. }
  27047. // matricesIndices
  27048. var matricesIndices = parsedVertexData.matricesIndices;
  27049. if (matricesIndices) {
  27050. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27051. }
  27052. // matricesWeights
  27053. var matricesWeights = parsedVertexData.matricesWeights;
  27054. if (matricesWeights) {
  27055. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27056. }
  27057. // indices
  27058. var indices = parsedVertexData.indices;
  27059. if (indices) {
  27060. vertexData.indices = indices;
  27061. }
  27062. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27063. };
  27064. return VertexData;
  27065. }());
  27066. BABYLON.VertexData = VertexData;
  27067. })(BABYLON || (BABYLON = {}));
  27068. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27069. var BABYLON;
  27070. (function (BABYLON) {
  27071. var Geometry = (function () {
  27072. function Geometry(id, scene, vertexData, updatable, mesh) {
  27073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27074. this._totalVertices = 0;
  27075. this._isDisposed = false;
  27076. this.id = id;
  27077. this._engine = scene.getEngine();
  27078. this._meshes = [];
  27079. this._scene = scene;
  27080. //Init vertex buffer cache
  27081. this._vertexBuffers = {};
  27082. this._indices = [];
  27083. // vertexData
  27084. if (vertexData) {
  27085. this.setAllVerticesData(vertexData, updatable);
  27086. }
  27087. else {
  27088. this._totalVertices = 0;
  27089. this._indices = [];
  27090. }
  27091. if (this._engine.getCaps().vertexArrayObject) {
  27092. this._vertexArrayObjects = {};
  27093. }
  27094. // applyToMesh
  27095. if (mesh) {
  27096. if (mesh.getClassName() === "LinesMesh") {
  27097. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27098. this.updateExtend();
  27099. }
  27100. this.applyToMesh(mesh);
  27101. mesh.computeWorldMatrix(true);
  27102. }
  27103. }
  27104. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27105. /**
  27106. * 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
  27107. * @returns The Bias Vector
  27108. */
  27109. get: function () {
  27110. return this._boundingBias;
  27111. },
  27112. set: function (value) {
  27113. if (this._boundingBias && this._boundingBias.equals(value)) {
  27114. return;
  27115. }
  27116. this._boundingBias = value.clone();
  27117. this.updateBoundingInfo(true, null);
  27118. },
  27119. enumerable: true,
  27120. configurable: true
  27121. });
  27122. Object.defineProperty(Geometry.prototype, "extend", {
  27123. get: function () {
  27124. return this._extend;
  27125. },
  27126. enumerable: true,
  27127. configurable: true
  27128. });
  27129. Geometry.prototype.getScene = function () {
  27130. return this._scene;
  27131. };
  27132. Geometry.prototype.getEngine = function () {
  27133. return this._engine;
  27134. };
  27135. Geometry.prototype.isReady = function () {
  27136. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27137. };
  27138. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27139. get: function () {
  27140. for (var index = 0; index < this._meshes.length; index++) {
  27141. if (!this._meshes[index].doNotSerialize) {
  27142. return false;
  27143. }
  27144. }
  27145. return true;
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27151. vertexData.applyToGeometry(this, updatable);
  27152. this.notifyUpdate();
  27153. };
  27154. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27155. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27156. this.setVerticesBuffer(buffer);
  27157. };
  27158. Geometry.prototype.removeVerticesData = function (kind) {
  27159. if (this._vertexBuffers[kind]) {
  27160. this._vertexBuffers[kind].dispose();
  27161. delete this._vertexBuffers[kind];
  27162. }
  27163. };
  27164. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27165. var kind = buffer.getKind();
  27166. if (this._vertexBuffers[kind]) {
  27167. this._vertexBuffers[kind].dispose();
  27168. }
  27169. this._vertexBuffers[kind] = buffer;
  27170. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27171. var data = buffer.getData();
  27172. var stride = buffer.getStrideSize();
  27173. this._totalVertices = data.length / stride;
  27174. this.updateExtend(data, stride);
  27175. this._resetPointsArrayCache();
  27176. var meshes = this._meshes;
  27177. var numOfMeshes = meshes.length;
  27178. for (var index = 0; index < numOfMeshes; index++) {
  27179. var mesh = meshes[index];
  27180. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27181. mesh._createGlobalSubMesh();
  27182. mesh.computeWorldMatrix(true);
  27183. }
  27184. }
  27185. this.notifyUpdate(kind);
  27186. if (this._vertexArrayObjects) {
  27187. this._disposeVertexArrayObjects();
  27188. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27189. }
  27190. };
  27191. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27192. var vertexBuffer = this.getVertexBuffer(kind);
  27193. if (!vertexBuffer) {
  27194. return;
  27195. }
  27196. vertexBuffer.updateDirectly(data, offset);
  27197. this.notifyUpdate(kind);
  27198. };
  27199. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27200. var vertexBuffer = this.getVertexBuffer(kind);
  27201. if (!vertexBuffer) {
  27202. return;
  27203. }
  27204. vertexBuffer.update(data);
  27205. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27206. var stride = vertexBuffer.getStrideSize();
  27207. this._totalVertices = data.length / stride;
  27208. this.updateBoundingInfo(updateExtends, data);
  27209. }
  27210. this.notifyUpdate(kind);
  27211. };
  27212. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27213. if (updateExtends) {
  27214. this.updateExtend(data);
  27215. }
  27216. var meshes = this._meshes;
  27217. var numOfMeshes = meshes.length;
  27218. this._resetPointsArrayCache();
  27219. for (var index = 0; index < numOfMeshes; index++) {
  27220. var mesh = meshes[index];
  27221. if (updateExtends) {
  27222. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27223. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27224. var subMesh = mesh.subMeshes[subIndex];
  27225. subMesh.refreshBoundingInfo();
  27226. }
  27227. }
  27228. }
  27229. };
  27230. Geometry.prototype._bind = function (effect, indexToBind) {
  27231. if (indexToBind === void 0) { indexToBind = undefined; }
  27232. if (indexToBind === undefined) {
  27233. indexToBind = this._indexBuffer;
  27234. }
  27235. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27236. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27237. return;
  27238. }
  27239. // Using VAO
  27240. if (!this._vertexArrayObjects[effect.key]) {
  27241. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27242. }
  27243. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27244. };
  27245. Geometry.prototype.getTotalVertices = function () {
  27246. if (!this.isReady()) {
  27247. return 0;
  27248. }
  27249. return this._totalVertices;
  27250. };
  27251. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27252. var vertexBuffer = this.getVertexBuffer(kind);
  27253. if (!vertexBuffer) {
  27254. return null;
  27255. }
  27256. var orig = vertexBuffer.getData();
  27257. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27258. return orig;
  27259. }
  27260. else {
  27261. var len = orig.length;
  27262. var copy = [];
  27263. for (var i = 0; i < len; i++) {
  27264. copy.push(orig[i]);
  27265. }
  27266. return copy;
  27267. }
  27268. };
  27269. Geometry.prototype.getVertexBuffer = function (kind) {
  27270. if (!this.isReady()) {
  27271. return null;
  27272. }
  27273. return this._vertexBuffers[kind];
  27274. };
  27275. Geometry.prototype.getVertexBuffers = function () {
  27276. if (!this.isReady()) {
  27277. return null;
  27278. }
  27279. return this._vertexBuffers;
  27280. };
  27281. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27282. if (!this._vertexBuffers) {
  27283. if (this._delayInfo) {
  27284. return this._delayInfo.indexOf(kind) !== -1;
  27285. }
  27286. return false;
  27287. }
  27288. return this._vertexBuffers[kind] !== undefined;
  27289. };
  27290. Geometry.prototype.getVerticesDataKinds = function () {
  27291. var result = [];
  27292. var kind;
  27293. if (!this._vertexBuffers && this._delayInfo) {
  27294. for (kind in this._delayInfo) {
  27295. result.push(kind);
  27296. }
  27297. }
  27298. else {
  27299. for (kind in this._vertexBuffers) {
  27300. result.push(kind);
  27301. }
  27302. }
  27303. return result;
  27304. };
  27305. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27306. if (this._indexBuffer) {
  27307. this._engine._releaseBuffer(this._indexBuffer);
  27308. }
  27309. this._disposeVertexArrayObjects();
  27310. this._indices = indices;
  27311. if (this._meshes.length !== 0 && this._indices) {
  27312. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27313. }
  27314. if (totalVertices !== undefined) {
  27315. this._totalVertices = totalVertices;
  27316. }
  27317. var meshes = this._meshes;
  27318. var numOfMeshes = meshes.length;
  27319. for (var index = 0; index < numOfMeshes; index++) {
  27320. meshes[index]._createGlobalSubMesh();
  27321. }
  27322. this.notifyUpdate();
  27323. };
  27324. Geometry.prototype.getTotalIndices = function () {
  27325. if (!this.isReady()) {
  27326. return 0;
  27327. }
  27328. return this._indices.length;
  27329. };
  27330. Geometry.prototype.getIndices = function (copyWhenShared) {
  27331. if (!this.isReady()) {
  27332. return null;
  27333. }
  27334. var orig = this._indices;
  27335. if (!copyWhenShared || this._meshes.length === 1) {
  27336. return orig;
  27337. }
  27338. else {
  27339. var len = orig.length;
  27340. var copy = [];
  27341. for (var i = 0; i < len; i++) {
  27342. copy.push(orig[i]);
  27343. }
  27344. return copy;
  27345. }
  27346. };
  27347. Geometry.prototype.getIndexBuffer = function () {
  27348. if (!this.isReady()) {
  27349. return null;
  27350. }
  27351. return this._indexBuffer;
  27352. };
  27353. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27354. if (!effect || !this._vertexArrayObjects) {
  27355. return;
  27356. }
  27357. if (this._vertexArrayObjects[effect.key]) {
  27358. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27359. delete this._vertexArrayObjects[effect.key];
  27360. }
  27361. };
  27362. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27363. var meshes = this._meshes;
  27364. var index = meshes.indexOf(mesh);
  27365. if (index === -1) {
  27366. return;
  27367. }
  27368. meshes.splice(index, 1);
  27369. mesh._geometry = null;
  27370. if (meshes.length === 0 && shouldDispose) {
  27371. this.dispose();
  27372. }
  27373. };
  27374. Geometry.prototype.applyToMesh = function (mesh) {
  27375. if (mesh._geometry === this) {
  27376. return;
  27377. }
  27378. var previousGeometry = mesh._geometry;
  27379. if (previousGeometry) {
  27380. previousGeometry.releaseForMesh(mesh);
  27381. }
  27382. var meshes = this._meshes;
  27383. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27384. mesh._geometry = this;
  27385. this._scene.pushGeometry(this);
  27386. meshes.push(mesh);
  27387. if (this.isReady()) {
  27388. this._applyToMesh(mesh);
  27389. }
  27390. else {
  27391. mesh._boundingInfo = this._boundingInfo;
  27392. }
  27393. };
  27394. Geometry.prototype.updateExtend = function (data, stride) {
  27395. if (data === void 0) { data = null; }
  27396. if (!data) {
  27397. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27398. }
  27399. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27400. };
  27401. Geometry.prototype._applyToMesh = function (mesh) {
  27402. var numOfMeshes = this._meshes.length;
  27403. // vertexBuffers
  27404. for (var kind in this._vertexBuffers) {
  27405. if (numOfMeshes === 1) {
  27406. this._vertexBuffers[kind].create();
  27407. }
  27408. var buffer = this._vertexBuffers[kind].getBuffer();
  27409. if (buffer)
  27410. buffer.references = numOfMeshes;
  27411. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27412. if (!this._extend) {
  27413. this.updateExtend(this._vertexBuffers[kind].getData());
  27414. }
  27415. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27416. mesh._createGlobalSubMesh();
  27417. //bounding info was just created again, world matrix should be applied again.
  27418. mesh._updateBoundingInfo();
  27419. }
  27420. }
  27421. // indexBuffer
  27422. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27423. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27424. }
  27425. if (this._indexBuffer) {
  27426. this._indexBuffer.references = numOfMeshes;
  27427. }
  27428. };
  27429. Geometry.prototype.notifyUpdate = function (kind) {
  27430. if (this.onGeometryUpdated) {
  27431. this.onGeometryUpdated(this, kind);
  27432. }
  27433. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27434. var mesh = _a[_i];
  27435. mesh._markSubMeshesAsAttributesDirty();
  27436. }
  27437. };
  27438. Geometry.prototype.load = function (scene, onLoaded) {
  27439. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27440. return;
  27441. }
  27442. if (this.isReady()) {
  27443. if (onLoaded) {
  27444. onLoaded();
  27445. }
  27446. return;
  27447. }
  27448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27449. this._queueLoad(scene, onLoaded);
  27450. };
  27451. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27452. var _this = this;
  27453. scene._addPendingData(this);
  27454. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27455. _this._delayLoadingFunction(JSON.parse(data), _this);
  27456. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27457. _this._delayInfo = [];
  27458. scene._removePendingData(_this);
  27459. var meshes = _this._meshes;
  27460. var numOfMeshes = meshes.length;
  27461. for (var index = 0; index < numOfMeshes; index++) {
  27462. _this._applyToMesh(meshes[index]);
  27463. }
  27464. if (onLoaded) {
  27465. onLoaded();
  27466. }
  27467. }, function () { }, scene.database);
  27468. };
  27469. /**
  27470. * Invert the geometry to move from a right handed system to a left handed one.
  27471. */
  27472. Geometry.prototype.toLeftHanded = function () {
  27473. // Flip faces
  27474. var tIndices = this.getIndices(false);
  27475. if (tIndices != null && tIndices.length > 0) {
  27476. for (var i = 0; i < tIndices.length; i += 3) {
  27477. var tTemp = tIndices[i + 0];
  27478. tIndices[i + 0] = tIndices[i + 2];
  27479. tIndices[i + 2] = tTemp;
  27480. }
  27481. this.setIndices(tIndices);
  27482. }
  27483. // Negate position.z
  27484. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27485. if (tPositions != null && tPositions.length > 0) {
  27486. for (var i = 0; i < tPositions.length; i += 3) {
  27487. tPositions[i + 2] = -tPositions[i + 2];
  27488. }
  27489. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27490. }
  27491. // Negate normal.z
  27492. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27493. if (tNormals != null && tNormals.length > 0) {
  27494. for (var i = 0; i < tNormals.length; i += 3) {
  27495. tNormals[i + 2] = -tNormals[i + 2];
  27496. }
  27497. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27498. }
  27499. };
  27500. // Cache
  27501. Geometry.prototype._resetPointsArrayCache = function () {
  27502. this._positions = null;
  27503. };
  27504. Geometry.prototype._generatePointsArray = function () {
  27505. if (this._positions)
  27506. return true;
  27507. this._positions = [];
  27508. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27509. if (!data) {
  27510. return false;
  27511. }
  27512. for (var index = 0; index < data.length; index += 3) {
  27513. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27514. }
  27515. return true;
  27516. };
  27517. Geometry.prototype.isDisposed = function () {
  27518. return this._isDisposed;
  27519. };
  27520. Geometry.prototype._disposeVertexArrayObjects = function () {
  27521. if (this._vertexArrayObjects) {
  27522. for (var kind in this._vertexArrayObjects) {
  27523. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27524. }
  27525. this._vertexArrayObjects = {};
  27526. }
  27527. };
  27528. Geometry.prototype.dispose = function () {
  27529. var meshes = this._meshes;
  27530. var numOfMeshes = meshes.length;
  27531. var index;
  27532. for (index = 0; index < numOfMeshes; index++) {
  27533. this.releaseForMesh(meshes[index]);
  27534. }
  27535. this._meshes = [];
  27536. this._disposeVertexArrayObjects();
  27537. for (var kind in this._vertexBuffers) {
  27538. this._vertexBuffers[kind].dispose();
  27539. }
  27540. this._vertexBuffers = {};
  27541. this._totalVertices = 0;
  27542. if (this._indexBuffer) {
  27543. this._engine._releaseBuffer(this._indexBuffer);
  27544. }
  27545. this._indexBuffer = null;
  27546. this._indices = [];
  27547. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27548. this.delayLoadingFile = null;
  27549. this._delayLoadingFunction = null;
  27550. this._delayInfo = [];
  27551. this._boundingInfo = null;
  27552. this._scene.removeGeometry(this);
  27553. this._isDisposed = true;
  27554. };
  27555. Geometry.prototype.copy = function (id) {
  27556. var vertexData = new BABYLON.VertexData();
  27557. vertexData.indices = [];
  27558. var indices = this.getIndices();
  27559. for (var index = 0; index < indices.length; index++) {
  27560. vertexData.indices.push(indices[index]);
  27561. }
  27562. var updatable = false;
  27563. var stopChecking = false;
  27564. var kind;
  27565. for (kind in this._vertexBuffers) {
  27566. // using slice() to make a copy of the array and not just reference it
  27567. var data = this.getVerticesData(kind);
  27568. if (data instanceof Float32Array) {
  27569. vertexData.set(new Float32Array(data), kind);
  27570. }
  27571. else {
  27572. vertexData.set(data.slice(0), kind);
  27573. }
  27574. if (!stopChecking) {
  27575. updatable = this.getVertexBuffer(kind).isUpdatable();
  27576. stopChecking = !updatable;
  27577. }
  27578. }
  27579. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27580. geometry.delayLoadState = this.delayLoadState;
  27581. geometry.delayLoadingFile = this.delayLoadingFile;
  27582. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27583. for (kind in this._delayInfo) {
  27584. geometry._delayInfo = geometry._delayInfo || [];
  27585. geometry._delayInfo.push(kind);
  27586. }
  27587. // Bounding info
  27588. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27589. return geometry;
  27590. };
  27591. Geometry.prototype.serialize = function () {
  27592. var serializationObject = {};
  27593. serializationObject.id = this.id;
  27594. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27595. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27596. }
  27597. return serializationObject;
  27598. };
  27599. Geometry.prototype.toNumberArray = function (origin) {
  27600. if (Array.isArray(origin)) {
  27601. return origin;
  27602. }
  27603. else {
  27604. return Array.prototype.slice.call(origin);
  27605. }
  27606. };
  27607. Geometry.prototype.serializeVerticeData = function () {
  27608. var serializationObject = this.serialize();
  27609. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27610. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27611. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27612. serializationObject.positions._updatable = true;
  27613. }
  27614. }
  27615. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27616. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27617. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27618. serializationObject.normals._updatable = true;
  27619. }
  27620. }
  27621. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27622. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27623. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27624. serializationObject.uvs._updatable = true;
  27625. }
  27626. }
  27627. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27628. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27629. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27630. serializationObject.uv2s._updatable = true;
  27631. }
  27632. }
  27633. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27634. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27635. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27636. serializationObject.uv3s._updatable = true;
  27637. }
  27638. }
  27639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27640. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27641. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27642. serializationObject.uv4s._updatable = true;
  27643. }
  27644. }
  27645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27646. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27647. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27648. serializationObject.uv5s._updatable = true;
  27649. }
  27650. }
  27651. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27652. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27653. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27654. serializationObject.uv6s._updatable = true;
  27655. }
  27656. }
  27657. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27658. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27659. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27660. serializationObject.colors._updatable = true;
  27661. }
  27662. }
  27663. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27664. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27665. serializationObject.matricesIndices._isExpanded = true;
  27666. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27667. serializationObject.matricesIndices._updatable = true;
  27668. }
  27669. }
  27670. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27671. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27672. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27673. serializationObject.matricesWeights._updatable = true;
  27674. }
  27675. }
  27676. serializationObject.indices = this.toNumberArray(this.getIndices());
  27677. return serializationObject;
  27678. };
  27679. // Statics
  27680. Geometry.ExtractFromMesh = function (mesh, id) {
  27681. var geometry = mesh._geometry;
  27682. if (!geometry) {
  27683. return null;
  27684. }
  27685. return geometry.copy(id);
  27686. };
  27687. /**
  27688. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27689. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27690. * Be aware Math.random() could cause collisions, but:
  27691. * "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"
  27692. */
  27693. Geometry.RandomId = function () {
  27694. return BABYLON.Tools.RandomId();
  27695. };
  27696. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27697. var scene = mesh.getScene();
  27698. // Geometry
  27699. var geometryId = parsedGeometry.geometryId;
  27700. if (geometryId) {
  27701. var geometry = scene.getGeometryByID(geometryId);
  27702. if (geometry) {
  27703. geometry.applyToMesh(mesh);
  27704. }
  27705. }
  27706. else if (parsedGeometry instanceof ArrayBuffer) {
  27707. var binaryInfo = mesh._binaryInfo;
  27708. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27709. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27710. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27711. }
  27712. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27713. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27714. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27715. }
  27716. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27717. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27718. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27719. }
  27720. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27721. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27722. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27723. }
  27724. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27725. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27726. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27727. }
  27728. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27729. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27730. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27731. }
  27732. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27733. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27734. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27735. }
  27736. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27737. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27738. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27739. }
  27740. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27741. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27742. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27743. }
  27744. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27745. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27746. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27747. }
  27748. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27749. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27750. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27751. }
  27752. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27753. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27754. mesh.setIndices(indicesData);
  27755. }
  27756. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27757. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27758. mesh.subMeshes = [];
  27759. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27760. var materialIndex = subMeshesData[(i * 5) + 0];
  27761. var verticesStart = subMeshesData[(i * 5) + 1];
  27762. var verticesCount = subMeshesData[(i * 5) + 2];
  27763. var indexStart = subMeshesData[(i * 5) + 3];
  27764. var indexCount = subMeshesData[(i * 5) + 4];
  27765. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27766. }
  27767. }
  27768. }
  27769. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27770. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27771. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27772. if (parsedGeometry.uvs) {
  27773. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27774. }
  27775. if (parsedGeometry.uvs2) {
  27776. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27777. }
  27778. if (parsedGeometry.uvs3) {
  27779. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27780. }
  27781. if (parsedGeometry.uvs4) {
  27782. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27783. }
  27784. if (parsedGeometry.uvs5) {
  27785. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27786. }
  27787. if (parsedGeometry.uvs6) {
  27788. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27789. }
  27790. if (parsedGeometry.colors) {
  27791. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27792. }
  27793. if (parsedGeometry.matricesIndices) {
  27794. if (!parsedGeometry.matricesIndices._isExpanded) {
  27795. var floatIndices = [];
  27796. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27797. var matricesIndex = parsedGeometry.matricesIndices[i];
  27798. floatIndices.push(matricesIndex & 0x000000FF);
  27799. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27800. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27801. floatIndices.push(matricesIndex >> 24);
  27802. }
  27803. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27804. }
  27805. else {
  27806. delete parsedGeometry.matricesIndices._isExpanded;
  27807. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27808. }
  27809. }
  27810. if (parsedGeometry.matricesIndicesExtra) {
  27811. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27812. var floatIndices = [];
  27813. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27814. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27815. floatIndices.push(matricesIndex & 0x000000FF);
  27816. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27817. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27818. floatIndices.push(matricesIndex >> 24);
  27819. }
  27820. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27821. }
  27822. else {
  27823. delete parsedGeometry.matricesIndices._isExpanded;
  27824. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27825. }
  27826. }
  27827. if (parsedGeometry.matricesWeights) {
  27828. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27829. }
  27830. if (parsedGeometry.matricesWeightsExtra) {
  27831. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27832. }
  27833. mesh.setIndices(parsedGeometry.indices);
  27834. }
  27835. // SubMeshes
  27836. if (parsedGeometry.subMeshes) {
  27837. mesh.subMeshes = [];
  27838. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27839. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27840. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27841. }
  27842. }
  27843. // Flat shading
  27844. if (mesh._shouldGenerateFlatShading) {
  27845. mesh.convertToFlatShadedMesh();
  27846. delete mesh._shouldGenerateFlatShading;
  27847. }
  27848. // Update
  27849. mesh.computeWorldMatrix(true);
  27850. // Octree
  27851. if (scene['_selectionOctree']) {
  27852. scene['_selectionOctree'].addMesh(mesh);
  27853. }
  27854. };
  27855. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27856. if (scene.getGeometryByID(parsedVertexData.id)) {
  27857. return null; // null since geometry could be something else than a box...
  27858. }
  27859. var geometry = new Geometry(parsedVertexData.id, scene);
  27860. if (BABYLON.Tags) {
  27861. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27862. }
  27863. if (parsedVertexData.delayLoadingFile) {
  27864. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27865. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27866. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27867. geometry._delayInfo = [];
  27868. if (parsedVertexData.hasUVs) {
  27869. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27870. }
  27871. if (parsedVertexData.hasUVs2) {
  27872. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27873. }
  27874. if (parsedVertexData.hasUVs3) {
  27875. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27876. }
  27877. if (parsedVertexData.hasUVs4) {
  27878. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27879. }
  27880. if (parsedVertexData.hasUVs5) {
  27881. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27882. }
  27883. if (parsedVertexData.hasUVs6) {
  27884. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27885. }
  27886. if (parsedVertexData.hasColors) {
  27887. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27888. }
  27889. if (parsedVertexData.hasMatricesIndices) {
  27890. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27891. }
  27892. if (parsedVertexData.hasMatricesWeights) {
  27893. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27894. }
  27895. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27896. }
  27897. else {
  27898. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27899. }
  27900. scene.pushGeometry(geometry, true);
  27901. return geometry;
  27902. };
  27903. return Geometry;
  27904. }());
  27905. BABYLON.Geometry = Geometry;
  27906. /////// Primitives //////////////////////////////////////////////
  27907. (function (Geometry) {
  27908. var Primitives;
  27909. (function (Primitives) {
  27910. /// Abstract class
  27911. var _Primitive = (function (_super) {
  27912. __extends(_Primitive, _super);
  27913. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27914. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27915. _this._canBeRegenerated = _canBeRegenerated;
  27916. _this._beingRegenerated = true;
  27917. _this.regenerate();
  27918. _this._beingRegenerated = false;
  27919. return _this;
  27920. }
  27921. _Primitive.prototype.canBeRegenerated = function () {
  27922. return this._canBeRegenerated;
  27923. };
  27924. _Primitive.prototype.regenerate = function () {
  27925. if (!this._canBeRegenerated) {
  27926. return;
  27927. }
  27928. this._beingRegenerated = true;
  27929. this.setAllVerticesData(this._regenerateVertexData(), false);
  27930. this._beingRegenerated = false;
  27931. };
  27932. _Primitive.prototype.asNewGeometry = function (id) {
  27933. return _super.prototype.copy.call(this, id);
  27934. };
  27935. // overrides
  27936. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27937. if (!this._beingRegenerated) {
  27938. return;
  27939. }
  27940. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27941. };
  27942. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27943. if (!this._beingRegenerated) {
  27944. return;
  27945. }
  27946. _super.prototype.setVerticesData.call(this, kind, data, false);
  27947. };
  27948. // to override
  27949. // protected
  27950. _Primitive.prototype._regenerateVertexData = function () {
  27951. throw new Error("Abstract method");
  27952. };
  27953. _Primitive.prototype.copy = function (id) {
  27954. throw new Error("Must be overriden in sub-classes.");
  27955. };
  27956. _Primitive.prototype.serialize = function () {
  27957. var serializationObject = _super.prototype.serialize.call(this);
  27958. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27959. return serializationObject;
  27960. };
  27961. return _Primitive;
  27962. }(Geometry));
  27963. Primitives._Primitive = _Primitive;
  27964. var Ribbon = (function (_super) {
  27965. __extends(Ribbon, _super);
  27966. // Members
  27967. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27968. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27969. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27970. _this.pathArray = pathArray;
  27971. _this.closeArray = closeArray;
  27972. _this.closePath = closePath;
  27973. _this.offset = offset;
  27974. _this.side = side;
  27975. return _this;
  27976. }
  27977. Ribbon.prototype._regenerateVertexData = function () {
  27978. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27979. };
  27980. Ribbon.prototype.copy = function (id) {
  27981. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27982. };
  27983. return Ribbon;
  27984. }(_Primitive));
  27985. Primitives.Ribbon = Ribbon;
  27986. var Box = (function (_super) {
  27987. __extends(Box, _super);
  27988. // Members
  27989. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27990. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27991. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27992. _this.size = size;
  27993. _this.side = side;
  27994. return _this;
  27995. }
  27996. Box.prototype._regenerateVertexData = function () {
  27997. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27998. };
  27999. Box.prototype.copy = function (id) {
  28000. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28001. };
  28002. Box.prototype.serialize = function () {
  28003. var serializationObject = _super.prototype.serialize.call(this);
  28004. serializationObject.size = this.size;
  28005. return serializationObject;
  28006. };
  28007. Box.Parse = function (parsedBox, scene) {
  28008. if (scene.getGeometryByID(parsedBox.id)) {
  28009. return null; // null since geometry could be something else than a box...
  28010. }
  28011. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28012. if (BABYLON.Tags) {
  28013. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28014. }
  28015. scene.pushGeometry(box, true);
  28016. return box;
  28017. };
  28018. return Box;
  28019. }(_Primitive));
  28020. Primitives.Box = Box;
  28021. var Sphere = (function (_super) {
  28022. __extends(Sphere, _super);
  28023. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28024. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28025. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28026. _this.segments = segments;
  28027. _this.diameter = diameter;
  28028. _this.side = side;
  28029. return _this;
  28030. }
  28031. Sphere.prototype._regenerateVertexData = function () {
  28032. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28033. };
  28034. Sphere.prototype.copy = function (id) {
  28035. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28036. };
  28037. Sphere.prototype.serialize = function () {
  28038. var serializationObject = _super.prototype.serialize.call(this);
  28039. serializationObject.segments = this.segments;
  28040. serializationObject.diameter = this.diameter;
  28041. return serializationObject;
  28042. };
  28043. Sphere.Parse = function (parsedSphere, scene) {
  28044. if (scene.getGeometryByID(parsedSphere.id)) {
  28045. return null; // null since geometry could be something else than a sphere...
  28046. }
  28047. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28048. if (BABYLON.Tags) {
  28049. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28050. }
  28051. scene.pushGeometry(sphere, true);
  28052. return sphere;
  28053. };
  28054. return Sphere;
  28055. }(_Primitive));
  28056. Primitives.Sphere = Sphere;
  28057. var Disc = (function (_super) {
  28058. __extends(Disc, _super);
  28059. // Members
  28060. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28063. _this.radius = radius;
  28064. _this.tessellation = tessellation;
  28065. _this.side = side;
  28066. return _this;
  28067. }
  28068. Disc.prototype._regenerateVertexData = function () {
  28069. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28070. };
  28071. Disc.prototype.copy = function (id) {
  28072. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28073. };
  28074. return Disc;
  28075. }(_Primitive));
  28076. Primitives.Disc = Disc;
  28077. var Cylinder = (function (_super) {
  28078. __extends(Cylinder, _super);
  28079. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28080. if (subdivisions === void 0) { subdivisions = 1; }
  28081. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28082. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28083. _this.height = height;
  28084. _this.diameterTop = diameterTop;
  28085. _this.diameterBottom = diameterBottom;
  28086. _this.tessellation = tessellation;
  28087. _this.subdivisions = subdivisions;
  28088. _this.side = side;
  28089. return _this;
  28090. }
  28091. Cylinder.prototype._regenerateVertexData = function () {
  28092. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28093. };
  28094. Cylinder.prototype.copy = function (id) {
  28095. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28096. };
  28097. Cylinder.prototype.serialize = function () {
  28098. var serializationObject = _super.prototype.serialize.call(this);
  28099. serializationObject.height = this.height;
  28100. serializationObject.diameterTop = this.diameterTop;
  28101. serializationObject.diameterBottom = this.diameterBottom;
  28102. serializationObject.tessellation = this.tessellation;
  28103. return serializationObject;
  28104. };
  28105. Cylinder.Parse = function (parsedCylinder, scene) {
  28106. if (scene.getGeometryByID(parsedCylinder.id)) {
  28107. return null; // null since geometry could be something else than a cylinder...
  28108. }
  28109. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28110. if (BABYLON.Tags) {
  28111. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28112. }
  28113. scene.pushGeometry(cylinder, true);
  28114. return cylinder;
  28115. };
  28116. return Cylinder;
  28117. }(_Primitive));
  28118. Primitives.Cylinder = Cylinder;
  28119. var Torus = (function (_super) {
  28120. __extends(Torus, _super);
  28121. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28122. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28123. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28124. _this.diameter = diameter;
  28125. _this.thickness = thickness;
  28126. _this.tessellation = tessellation;
  28127. _this.side = side;
  28128. return _this;
  28129. }
  28130. Torus.prototype._regenerateVertexData = function () {
  28131. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28132. };
  28133. Torus.prototype.copy = function (id) {
  28134. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28135. };
  28136. Torus.prototype.serialize = function () {
  28137. var serializationObject = _super.prototype.serialize.call(this);
  28138. serializationObject.diameter = this.diameter;
  28139. serializationObject.thickness = this.thickness;
  28140. serializationObject.tessellation = this.tessellation;
  28141. return serializationObject;
  28142. };
  28143. Torus.Parse = function (parsedTorus, scene) {
  28144. if (scene.getGeometryByID(parsedTorus.id)) {
  28145. return null; // null since geometry could be something else than a torus...
  28146. }
  28147. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28148. if (BABYLON.Tags) {
  28149. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28150. }
  28151. scene.pushGeometry(torus, true);
  28152. return torus;
  28153. };
  28154. return Torus;
  28155. }(_Primitive));
  28156. Primitives.Torus = Torus;
  28157. var Ground = (function (_super) {
  28158. __extends(Ground, _super);
  28159. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28160. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28161. _this.width = width;
  28162. _this.height = height;
  28163. _this.subdivisions = subdivisions;
  28164. return _this;
  28165. }
  28166. Ground.prototype._regenerateVertexData = function () {
  28167. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28168. };
  28169. Ground.prototype.copy = function (id) {
  28170. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28171. };
  28172. Ground.prototype.serialize = function () {
  28173. var serializationObject = _super.prototype.serialize.call(this);
  28174. serializationObject.width = this.width;
  28175. serializationObject.height = this.height;
  28176. serializationObject.subdivisions = this.subdivisions;
  28177. return serializationObject;
  28178. };
  28179. Ground.Parse = function (parsedGround, scene) {
  28180. if (scene.getGeometryByID(parsedGround.id)) {
  28181. return null; // null since geometry could be something else than a ground...
  28182. }
  28183. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28184. if (BABYLON.Tags) {
  28185. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28186. }
  28187. scene.pushGeometry(ground, true);
  28188. return ground;
  28189. };
  28190. return Ground;
  28191. }(_Primitive));
  28192. Primitives.Ground = Ground;
  28193. var TiledGround = (function (_super) {
  28194. __extends(TiledGround, _super);
  28195. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28196. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28197. _this.xmin = xmin;
  28198. _this.zmin = zmin;
  28199. _this.xmax = xmax;
  28200. _this.zmax = zmax;
  28201. _this.subdivisions = subdivisions;
  28202. _this.precision = precision;
  28203. return _this;
  28204. }
  28205. TiledGround.prototype._regenerateVertexData = function () {
  28206. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28207. };
  28208. TiledGround.prototype.copy = function (id) {
  28209. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28210. };
  28211. return TiledGround;
  28212. }(_Primitive));
  28213. Primitives.TiledGround = TiledGround;
  28214. var Plane = (function (_super) {
  28215. __extends(Plane, _super);
  28216. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28217. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28218. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28219. _this.size = size;
  28220. _this.side = side;
  28221. return _this;
  28222. }
  28223. Plane.prototype._regenerateVertexData = function () {
  28224. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28225. };
  28226. Plane.prototype.copy = function (id) {
  28227. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28228. };
  28229. Plane.prototype.serialize = function () {
  28230. var serializationObject = _super.prototype.serialize.call(this);
  28231. serializationObject.size = this.size;
  28232. return serializationObject;
  28233. };
  28234. Plane.Parse = function (parsedPlane, scene) {
  28235. if (scene.getGeometryByID(parsedPlane.id)) {
  28236. return null; // null since geometry could be something else than a ground...
  28237. }
  28238. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28239. if (BABYLON.Tags) {
  28240. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28241. }
  28242. scene.pushGeometry(plane, true);
  28243. return plane;
  28244. };
  28245. return Plane;
  28246. }(_Primitive));
  28247. Primitives.Plane = Plane;
  28248. var TorusKnot = (function (_super) {
  28249. __extends(TorusKnot, _super);
  28250. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28251. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28252. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28253. _this.radius = radius;
  28254. _this.tube = tube;
  28255. _this.radialSegments = radialSegments;
  28256. _this.tubularSegments = tubularSegments;
  28257. _this.p = p;
  28258. _this.q = q;
  28259. _this.side = side;
  28260. return _this;
  28261. }
  28262. TorusKnot.prototype._regenerateVertexData = function () {
  28263. 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 });
  28264. };
  28265. TorusKnot.prototype.copy = function (id) {
  28266. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28267. };
  28268. TorusKnot.prototype.serialize = function () {
  28269. var serializationObject = _super.prototype.serialize.call(this);
  28270. serializationObject.radius = this.radius;
  28271. serializationObject.tube = this.tube;
  28272. serializationObject.radialSegments = this.radialSegments;
  28273. serializationObject.tubularSegments = this.tubularSegments;
  28274. serializationObject.p = this.p;
  28275. serializationObject.q = this.q;
  28276. return serializationObject;
  28277. };
  28278. ;
  28279. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28280. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28281. return null; // null since geometry could be something else than a ground...
  28282. }
  28283. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28284. if (BABYLON.Tags) {
  28285. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28286. }
  28287. scene.pushGeometry(torusKnot, true);
  28288. return torusKnot;
  28289. };
  28290. return TorusKnot;
  28291. }(_Primitive));
  28292. Primitives.TorusKnot = TorusKnot;
  28293. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28294. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28295. })(BABYLON || (BABYLON = {}));
  28296. //# sourceMappingURL=babylon.geometry.js.map
  28297. var BABYLON;
  28298. (function (BABYLON) {
  28299. var PostProcessManager = (function () {
  28300. function PostProcessManager(scene) {
  28301. this._vertexBuffers = {};
  28302. this._scene = scene;
  28303. }
  28304. PostProcessManager.prototype._prepareBuffers = function () {
  28305. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28306. return;
  28307. }
  28308. // VBO
  28309. var vertices = [];
  28310. vertices.push(1, 1);
  28311. vertices.push(-1, 1);
  28312. vertices.push(-1, -1);
  28313. vertices.push(1, -1);
  28314. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28315. // Indices
  28316. var indices = [];
  28317. indices.push(0);
  28318. indices.push(1);
  28319. indices.push(2);
  28320. indices.push(0);
  28321. indices.push(2);
  28322. indices.push(3);
  28323. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28324. };
  28325. // Methods
  28326. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28327. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28328. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28329. return false;
  28330. }
  28331. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28332. return true;
  28333. };
  28334. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28335. var engine = this._scene.getEngine();
  28336. for (var index = 0; index < postProcesses.length; index++) {
  28337. if (index < postProcesses.length - 1) {
  28338. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28339. }
  28340. else {
  28341. if (targetTexture) {
  28342. engine.bindFramebuffer(targetTexture);
  28343. }
  28344. else {
  28345. engine.restoreDefaultFramebuffer();
  28346. }
  28347. }
  28348. var pp = postProcesses[index];
  28349. var effect = pp.apply();
  28350. if (effect) {
  28351. pp.onBeforeRenderObservable.notifyObservers(effect);
  28352. // VBOs
  28353. this._prepareBuffers();
  28354. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28355. // Draw order
  28356. engine.draw(true, 0, 6);
  28357. pp.onAfterRenderObservable.notifyObservers(effect);
  28358. }
  28359. }
  28360. // Restore depth buffer
  28361. engine.setDepthBuffer(true);
  28362. engine.setDepthWrite(true);
  28363. };
  28364. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28365. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28366. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28367. return;
  28368. }
  28369. var engine = this._scene.getEngine();
  28370. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28371. if (index < len - 1) {
  28372. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28373. }
  28374. else {
  28375. if (targetTexture) {
  28376. engine.bindFramebuffer(targetTexture, faceIndex);
  28377. }
  28378. else {
  28379. engine.restoreDefaultFramebuffer();
  28380. }
  28381. }
  28382. if (doNotPresent) {
  28383. break;
  28384. }
  28385. var pp = postProcesses[index];
  28386. var effect = pp.apply();
  28387. if (effect) {
  28388. pp.onBeforeRenderObservable.notifyObservers(effect);
  28389. // VBOs
  28390. this._prepareBuffers();
  28391. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28392. // Draw order
  28393. engine.draw(true, 0, 6);
  28394. pp.onAfterRenderObservable.notifyObservers(effect);
  28395. }
  28396. }
  28397. // Restore states
  28398. engine.setDepthBuffer(true);
  28399. engine.setDepthWrite(true);
  28400. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28401. };
  28402. PostProcessManager.prototype.dispose = function () {
  28403. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28404. if (buffer) {
  28405. buffer.dispose();
  28406. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28407. }
  28408. if (this._indexBuffer) {
  28409. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28410. this._indexBuffer = null;
  28411. }
  28412. };
  28413. return PostProcessManager;
  28414. }());
  28415. BABYLON.PostProcessManager = PostProcessManager;
  28416. })(BABYLON || (BABYLON = {}));
  28417. //# sourceMappingURL=babylon.postProcessManager.js.map
  28418. var BABYLON;
  28419. (function (BABYLON) {
  28420. var AnimationRange = (function () {
  28421. function AnimationRange(name, from, to) {
  28422. this.name = name;
  28423. this.from = from;
  28424. this.to = to;
  28425. }
  28426. AnimationRange.prototype.clone = function () {
  28427. return new AnimationRange(this.name, this.from, this.to);
  28428. };
  28429. return AnimationRange;
  28430. }());
  28431. BABYLON.AnimationRange = AnimationRange;
  28432. /**
  28433. * Composed of a frame, and an action function
  28434. */
  28435. var AnimationEvent = (function () {
  28436. function AnimationEvent(frame, action, onlyOnce) {
  28437. this.frame = frame;
  28438. this.action = action;
  28439. this.onlyOnce = onlyOnce;
  28440. this.isDone = false;
  28441. }
  28442. return AnimationEvent;
  28443. }());
  28444. BABYLON.AnimationEvent = AnimationEvent;
  28445. var PathCursor = (function () {
  28446. function PathCursor(path) {
  28447. this.path = path;
  28448. this._onchange = new Array();
  28449. this.value = 0;
  28450. this.animations = new Array();
  28451. }
  28452. PathCursor.prototype.getPoint = function () {
  28453. var point = this.path.getPointAtLengthPosition(this.value);
  28454. return new BABYLON.Vector3(point.x, 0, point.y);
  28455. };
  28456. PathCursor.prototype.moveAhead = function (step) {
  28457. if (step === void 0) { step = 0.002; }
  28458. this.move(step);
  28459. return this;
  28460. };
  28461. PathCursor.prototype.moveBack = function (step) {
  28462. if (step === void 0) { step = 0.002; }
  28463. this.move(-step);
  28464. return this;
  28465. };
  28466. PathCursor.prototype.move = function (step) {
  28467. if (Math.abs(step) > 1) {
  28468. throw "step size should be less than 1.";
  28469. }
  28470. this.value += step;
  28471. this.ensureLimits();
  28472. this.raiseOnChange();
  28473. return this;
  28474. };
  28475. PathCursor.prototype.ensureLimits = function () {
  28476. while (this.value > 1) {
  28477. this.value -= 1;
  28478. }
  28479. while (this.value < 0) {
  28480. this.value += 1;
  28481. }
  28482. return this;
  28483. };
  28484. // used by animation engine
  28485. PathCursor.prototype.markAsDirty = function (propertyName) {
  28486. this.ensureLimits();
  28487. this.raiseOnChange();
  28488. return this;
  28489. };
  28490. PathCursor.prototype.raiseOnChange = function () {
  28491. var _this = this;
  28492. this._onchange.forEach(function (f) { return f(_this); });
  28493. return this;
  28494. };
  28495. PathCursor.prototype.onchange = function (f) {
  28496. this._onchange.push(f);
  28497. return this;
  28498. };
  28499. return PathCursor;
  28500. }());
  28501. BABYLON.PathCursor = PathCursor;
  28502. var Animation = (function () {
  28503. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28504. this.name = name;
  28505. this.targetProperty = targetProperty;
  28506. this.framePerSecond = framePerSecond;
  28507. this.dataType = dataType;
  28508. this.loopMode = loopMode;
  28509. this.enableBlending = enableBlending;
  28510. this._offsetsCache = {};
  28511. this._highLimitsCache = {};
  28512. this._stopped = false;
  28513. this._blendingFactor = 0;
  28514. // The set of event that will be linked to this animation
  28515. this._events = new Array();
  28516. this.allowMatricesInterpolation = false;
  28517. this.blendingSpeed = 0.01;
  28518. this._ranges = {};
  28519. this.targetPropertyPath = targetProperty.split(".");
  28520. this.dataType = dataType;
  28521. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28522. }
  28523. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28524. var dataType = undefined;
  28525. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28526. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28527. }
  28528. else if (from instanceof BABYLON.Quaternion) {
  28529. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28530. }
  28531. else if (from instanceof BABYLON.Vector3) {
  28532. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28533. }
  28534. else if (from instanceof BABYLON.Vector2) {
  28535. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28536. }
  28537. else if (from instanceof BABYLON.Color3) {
  28538. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28539. }
  28540. else if (from instanceof BABYLON.Size) {
  28541. dataType = Animation.ANIMATIONTYPE_SIZE;
  28542. }
  28543. if (dataType == undefined) {
  28544. return null;
  28545. }
  28546. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28547. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28548. animation.setKeys(keys);
  28549. if (easingFunction !== undefined) {
  28550. animation.setEasingFunction(easingFunction);
  28551. }
  28552. return animation;
  28553. };
  28554. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28555. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28556. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28557. };
  28558. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28559. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28560. node.animations.push(animation);
  28561. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28562. };
  28563. // Methods
  28564. /**
  28565. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28566. */
  28567. Animation.prototype.toString = function (fullDetails) {
  28568. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28569. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28570. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28571. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28572. if (fullDetails) {
  28573. ret += ", Ranges: {";
  28574. var first = true;
  28575. for (var name in this._ranges) {
  28576. if (first) {
  28577. ret += ", ";
  28578. first = false;
  28579. }
  28580. ret += name;
  28581. }
  28582. ret += "}";
  28583. }
  28584. return ret;
  28585. };
  28586. /**
  28587. * Add an event to this animation.
  28588. */
  28589. Animation.prototype.addEvent = function (event) {
  28590. this._events.push(event);
  28591. };
  28592. /**
  28593. * Remove all events found at the given frame
  28594. * @param frame
  28595. */
  28596. Animation.prototype.removeEvents = function (frame) {
  28597. for (var index = 0; index < this._events.length; index++) {
  28598. if (this._events[index].frame === frame) {
  28599. this._events.splice(index, 1);
  28600. index--;
  28601. }
  28602. }
  28603. };
  28604. Animation.prototype.createRange = function (name, from, to) {
  28605. // check name not already in use; could happen for bones after serialized
  28606. if (!this._ranges[name]) {
  28607. this._ranges[name] = new AnimationRange(name, from, to);
  28608. }
  28609. };
  28610. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28611. if (deleteFrames === void 0) { deleteFrames = true; }
  28612. if (this._ranges[name]) {
  28613. if (deleteFrames) {
  28614. var from = this._ranges[name].from;
  28615. var to = this._ranges[name].to;
  28616. // this loop MUST go high to low for multiple splices to work
  28617. for (var key = this._keys.length - 1; key >= 0; key--) {
  28618. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28619. this._keys.splice(key, 1);
  28620. }
  28621. }
  28622. }
  28623. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28624. }
  28625. };
  28626. Animation.prototype.getRange = function (name) {
  28627. return this._ranges[name];
  28628. };
  28629. Animation.prototype.reset = function () {
  28630. this._offsetsCache = {};
  28631. this._highLimitsCache = {};
  28632. this.currentFrame = 0;
  28633. this._blendingFactor = 0;
  28634. this._originalBlendValue = null;
  28635. };
  28636. Animation.prototype.isStopped = function () {
  28637. return this._stopped;
  28638. };
  28639. Animation.prototype.getKeys = function () {
  28640. return this._keys;
  28641. };
  28642. Animation.prototype.getHighestFrame = function () {
  28643. var ret = 0;
  28644. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28645. if (ret < this._keys[key].frame) {
  28646. ret = this._keys[key].frame;
  28647. }
  28648. }
  28649. return ret;
  28650. };
  28651. Animation.prototype.getEasingFunction = function () {
  28652. return this._easingFunction;
  28653. };
  28654. Animation.prototype.setEasingFunction = function (easingFunction) {
  28655. this._easingFunction = easingFunction;
  28656. };
  28657. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28658. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28659. };
  28660. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28661. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28662. };
  28663. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28664. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28665. };
  28666. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28667. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28668. };
  28669. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28670. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28671. };
  28672. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28673. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28674. };
  28675. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28676. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28677. };
  28678. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28679. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28680. };
  28681. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28682. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28683. };
  28684. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28685. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28686. };
  28687. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28688. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28689. };
  28690. Animation.prototype.clone = function () {
  28691. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28692. clone.enableBlending = this.enableBlending;
  28693. clone.blendingSpeed = this.blendingSpeed;
  28694. if (this._keys) {
  28695. clone.setKeys(this._keys);
  28696. }
  28697. if (this._ranges) {
  28698. clone._ranges = {};
  28699. for (var name in this._ranges) {
  28700. clone._ranges[name] = this._ranges[name].clone();
  28701. }
  28702. }
  28703. return clone;
  28704. };
  28705. Animation.prototype.setKeys = function (values) {
  28706. this._keys = values.slice(0);
  28707. this._offsetsCache = {};
  28708. this._highLimitsCache = {};
  28709. };
  28710. Animation.prototype._getKeyValue = function (value) {
  28711. if (typeof value === "function") {
  28712. return value();
  28713. }
  28714. return value;
  28715. };
  28716. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28717. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28718. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28719. }
  28720. this.currentFrame = currentFrame;
  28721. // Try to get a hash to find the right key
  28722. 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));
  28723. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28724. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28725. startKeyIndex--;
  28726. }
  28727. }
  28728. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28729. var endKey = this._keys[key + 1];
  28730. if (endKey.frame >= currentFrame) {
  28731. var startKey = this._keys[key];
  28732. var startValue = this._getKeyValue(startKey.value);
  28733. var endValue = this._getKeyValue(endKey.value);
  28734. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28735. var frameDelta = endKey.frame - startKey.frame;
  28736. // gradient : percent of currentFrame between the frame inf and the frame sup
  28737. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28738. // check for easingFunction and correction of gradient
  28739. if (this._easingFunction != null) {
  28740. gradient = this._easingFunction.ease(gradient);
  28741. }
  28742. switch (this.dataType) {
  28743. // Float
  28744. case Animation.ANIMATIONTYPE_FLOAT:
  28745. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28746. switch (loopMode) {
  28747. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28748. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28749. return floatValue;
  28750. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28751. return offsetValue * repeatCount + floatValue;
  28752. }
  28753. break;
  28754. // Quaternion
  28755. case Animation.ANIMATIONTYPE_QUATERNION:
  28756. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28757. switch (loopMode) {
  28758. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28759. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28760. return quatValue;
  28761. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28762. return quatValue.add(offsetValue.scale(repeatCount));
  28763. }
  28764. return quatValue;
  28765. // Vector3
  28766. case Animation.ANIMATIONTYPE_VECTOR3:
  28767. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28768. switch (loopMode) {
  28769. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28770. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28771. return vec3Value;
  28772. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28773. return vec3Value.add(offsetValue.scale(repeatCount));
  28774. }
  28775. // Vector2
  28776. case Animation.ANIMATIONTYPE_VECTOR2:
  28777. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28778. switch (loopMode) {
  28779. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28780. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28781. return vec2Value;
  28782. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28783. return vec2Value.add(offsetValue.scale(repeatCount));
  28784. }
  28785. // Size
  28786. case Animation.ANIMATIONTYPE_SIZE:
  28787. switch (loopMode) {
  28788. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28789. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28790. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28791. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28792. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28793. }
  28794. // Color3
  28795. case Animation.ANIMATIONTYPE_COLOR3:
  28796. switch (loopMode) {
  28797. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28798. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28799. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28800. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28801. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28802. }
  28803. // Matrix
  28804. case Animation.ANIMATIONTYPE_MATRIX:
  28805. switch (loopMode) {
  28806. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28807. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28808. if (this.allowMatricesInterpolation) {
  28809. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28810. }
  28811. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28812. return startValue;
  28813. }
  28814. default:
  28815. break;
  28816. }
  28817. break;
  28818. }
  28819. }
  28820. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28821. };
  28822. Animation.prototype.setValue = function (currentValue, blend) {
  28823. if (blend === void 0) { blend = false; }
  28824. // Set value
  28825. var path;
  28826. var destination;
  28827. if (this.targetPropertyPath.length > 1) {
  28828. var property = this._target[this.targetPropertyPath[0]];
  28829. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28830. property = property[this.targetPropertyPath[index]];
  28831. }
  28832. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28833. destination = property;
  28834. }
  28835. else {
  28836. path = this.targetPropertyPath[0];
  28837. destination = this._target;
  28838. }
  28839. // Blending
  28840. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28841. if (!this._originalBlendValue) {
  28842. if (destination[path].clone) {
  28843. this._originalBlendValue = destination[path].clone();
  28844. }
  28845. else {
  28846. this._originalBlendValue = destination[path];
  28847. }
  28848. }
  28849. if (this._originalBlendValue.prototype) {
  28850. if (this._originalBlendValue.prototype.Lerp) {
  28851. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28852. }
  28853. else {
  28854. destination[path] = currentValue;
  28855. }
  28856. }
  28857. else if (this._originalBlendValue.m) {
  28858. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28859. }
  28860. else {
  28861. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28862. }
  28863. this._blendingFactor += this.blendingSpeed;
  28864. }
  28865. else {
  28866. destination[path] = currentValue;
  28867. }
  28868. if (this._target.markAsDirty) {
  28869. this._target.markAsDirty(this.targetProperty);
  28870. }
  28871. };
  28872. Animation.prototype.goToFrame = function (frame) {
  28873. if (frame < this._keys[0].frame) {
  28874. frame = this._keys[0].frame;
  28875. }
  28876. else if (frame > this._keys[this._keys.length - 1].frame) {
  28877. frame = this._keys[this._keys.length - 1].frame;
  28878. }
  28879. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28880. this.setValue(currentValue);
  28881. };
  28882. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28883. if (blend === void 0) { blend = false; }
  28884. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28885. this._stopped = true;
  28886. return false;
  28887. }
  28888. var returnValue = true;
  28889. // Adding a start key at frame 0 if missing
  28890. if (this._keys[0].frame !== 0) {
  28891. var newKey = { frame: 0, value: this._keys[0].value };
  28892. this._keys.splice(0, 0, newKey);
  28893. }
  28894. // Check limits
  28895. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28896. from = this._keys[0].frame;
  28897. }
  28898. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28899. to = this._keys[this._keys.length - 1].frame;
  28900. }
  28901. //to and from cannot be the same key
  28902. if (from === to) {
  28903. from++;
  28904. }
  28905. // Compute ratio
  28906. var range = to - from;
  28907. var offsetValue;
  28908. // ratio represents the frame delta between from and to
  28909. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28910. var highLimitValue = 0;
  28911. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  28912. returnValue = false;
  28913. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28914. }
  28915. else {
  28916. // Get max value if required
  28917. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28918. var keyOffset = to.toString() + from.toString();
  28919. if (!this._offsetsCache[keyOffset]) {
  28920. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28921. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28922. switch (this.dataType) {
  28923. // Float
  28924. case Animation.ANIMATIONTYPE_FLOAT:
  28925. this._offsetsCache[keyOffset] = toValue - fromValue;
  28926. break;
  28927. // Quaternion
  28928. case Animation.ANIMATIONTYPE_QUATERNION:
  28929. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28930. break;
  28931. // Vector3
  28932. case Animation.ANIMATIONTYPE_VECTOR3:
  28933. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28934. // Vector2
  28935. case Animation.ANIMATIONTYPE_VECTOR2:
  28936. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28937. // Size
  28938. case Animation.ANIMATIONTYPE_SIZE:
  28939. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28940. // Color3
  28941. case Animation.ANIMATIONTYPE_COLOR3:
  28942. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28943. default:
  28944. break;
  28945. }
  28946. this._highLimitsCache[keyOffset] = toValue;
  28947. }
  28948. highLimitValue = this._highLimitsCache[keyOffset];
  28949. offsetValue = this._offsetsCache[keyOffset];
  28950. }
  28951. }
  28952. if (offsetValue === undefined) {
  28953. switch (this.dataType) {
  28954. // Float
  28955. case Animation.ANIMATIONTYPE_FLOAT:
  28956. offsetValue = 0;
  28957. break;
  28958. // Quaternion
  28959. case Animation.ANIMATIONTYPE_QUATERNION:
  28960. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28961. break;
  28962. // Vector3
  28963. case Animation.ANIMATIONTYPE_VECTOR3:
  28964. offsetValue = BABYLON.Vector3.Zero();
  28965. break;
  28966. // Vector2
  28967. case Animation.ANIMATIONTYPE_VECTOR2:
  28968. offsetValue = BABYLON.Vector2.Zero();
  28969. break;
  28970. // Size
  28971. case Animation.ANIMATIONTYPE_SIZE:
  28972. offsetValue = BABYLON.Size.Zero();
  28973. break;
  28974. // Color3
  28975. case Animation.ANIMATIONTYPE_COLOR3:
  28976. offsetValue = BABYLON.Color3.Black();
  28977. }
  28978. }
  28979. // Compute value
  28980. var repeatCount = (ratio / range) >> 0;
  28981. var currentFrame = returnValue ? from + ratio % range : to;
  28982. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28983. // Set value
  28984. this.setValue(currentValue);
  28985. // Check events
  28986. for (var index = 0; index < this._events.length; index++) {
  28987. if (currentFrame >= this._events[index].frame) {
  28988. var event = this._events[index];
  28989. if (!event.isDone) {
  28990. // If event should be done only once, remove it.
  28991. if (event.onlyOnce) {
  28992. this._events.splice(index, 1);
  28993. index--;
  28994. }
  28995. event.isDone = true;
  28996. event.action();
  28997. } // Don't do anything if the event has already be done.
  28998. }
  28999. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29000. // reset event, the animation is looping
  29001. this._events[index].isDone = false;
  29002. }
  29003. }
  29004. if (!returnValue) {
  29005. this._stopped = true;
  29006. }
  29007. return returnValue;
  29008. };
  29009. Animation.prototype.serialize = function () {
  29010. var serializationObject = {};
  29011. serializationObject.name = this.name;
  29012. serializationObject.property = this.targetProperty;
  29013. serializationObject.framePerSecond = this.framePerSecond;
  29014. serializationObject.dataType = this.dataType;
  29015. serializationObject.loopBehavior = this.loopMode;
  29016. serializationObject.enableBlending = this.enableBlending;
  29017. serializationObject.blendingSpeed = this.blendingSpeed;
  29018. var dataType = this.dataType;
  29019. serializationObject.keys = [];
  29020. var keys = this.getKeys();
  29021. for (var index = 0; index < keys.length; index++) {
  29022. var animationKey = keys[index];
  29023. var key = {};
  29024. key.frame = animationKey.frame;
  29025. switch (dataType) {
  29026. case Animation.ANIMATIONTYPE_FLOAT:
  29027. key.values = [animationKey.value];
  29028. break;
  29029. case Animation.ANIMATIONTYPE_QUATERNION:
  29030. case Animation.ANIMATIONTYPE_MATRIX:
  29031. case Animation.ANIMATIONTYPE_VECTOR3:
  29032. case Animation.ANIMATIONTYPE_COLOR3:
  29033. key.values = animationKey.value.asArray();
  29034. break;
  29035. }
  29036. serializationObject.keys.push(key);
  29037. }
  29038. serializationObject.ranges = [];
  29039. for (var name in this._ranges) {
  29040. var range = {};
  29041. range.name = name;
  29042. range.from = this._ranges[name].from;
  29043. range.to = this._ranges[name].to;
  29044. serializationObject.ranges.push(range);
  29045. }
  29046. return serializationObject;
  29047. };
  29048. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29049. get: function () {
  29050. return Animation._ANIMATIONTYPE_FLOAT;
  29051. },
  29052. enumerable: true,
  29053. configurable: true
  29054. });
  29055. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29056. get: function () {
  29057. return Animation._ANIMATIONTYPE_VECTOR3;
  29058. },
  29059. enumerable: true,
  29060. configurable: true
  29061. });
  29062. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29063. get: function () {
  29064. return Animation._ANIMATIONTYPE_VECTOR2;
  29065. },
  29066. enumerable: true,
  29067. configurable: true
  29068. });
  29069. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29070. get: function () {
  29071. return Animation._ANIMATIONTYPE_SIZE;
  29072. },
  29073. enumerable: true,
  29074. configurable: true
  29075. });
  29076. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29077. get: function () {
  29078. return Animation._ANIMATIONTYPE_QUATERNION;
  29079. },
  29080. enumerable: true,
  29081. configurable: true
  29082. });
  29083. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29084. get: function () {
  29085. return Animation._ANIMATIONTYPE_MATRIX;
  29086. },
  29087. enumerable: true,
  29088. configurable: true
  29089. });
  29090. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29091. get: function () {
  29092. return Animation._ANIMATIONTYPE_COLOR3;
  29093. },
  29094. enumerable: true,
  29095. configurable: true
  29096. });
  29097. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29098. get: function () {
  29099. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29100. },
  29101. enumerable: true,
  29102. configurable: true
  29103. });
  29104. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29105. get: function () {
  29106. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29107. },
  29108. enumerable: true,
  29109. configurable: true
  29110. });
  29111. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29112. get: function () {
  29113. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29114. },
  29115. enumerable: true,
  29116. configurable: true
  29117. });
  29118. Animation.Parse = function (parsedAnimation) {
  29119. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29120. var dataType = parsedAnimation.dataType;
  29121. var keys = [];
  29122. var data;
  29123. var index;
  29124. if (parsedAnimation.enableBlending) {
  29125. animation.enableBlending = parsedAnimation.enableBlending;
  29126. }
  29127. if (parsedAnimation.blendingSpeed) {
  29128. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  29129. }
  29130. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29131. var key = parsedAnimation.keys[index];
  29132. switch (dataType) {
  29133. case Animation.ANIMATIONTYPE_FLOAT:
  29134. data = key.values[0];
  29135. break;
  29136. case Animation.ANIMATIONTYPE_QUATERNION:
  29137. data = BABYLON.Quaternion.FromArray(key.values);
  29138. break;
  29139. case Animation.ANIMATIONTYPE_MATRIX:
  29140. data = BABYLON.Matrix.FromArray(key.values);
  29141. break;
  29142. case Animation.ANIMATIONTYPE_COLOR3:
  29143. data = BABYLON.Color3.FromArray(key.values);
  29144. break;
  29145. case Animation.ANIMATIONTYPE_VECTOR3:
  29146. default:
  29147. data = BABYLON.Vector3.FromArray(key.values);
  29148. break;
  29149. }
  29150. keys.push({
  29151. frame: key.frame,
  29152. value: data
  29153. });
  29154. }
  29155. animation.setKeys(keys);
  29156. if (parsedAnimation.ranges) {
  29157. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29158. data = parsedAnimation.ranges[index];
  29159. animation.createRange(data.name, data.from, data.to);
  29160. }
  29161. }
  29162. return animation;
  29163. };
  29164. Animation.AppendSerializedAnimations = function (source, destination) {
  29165. if (source.animations) {
  29166. destination.animations = [];
  29167. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29168. var animation = source.animations[animationIndex];
  29169. destination.animations.push(animation.serialize());
  29170. }
  29171. }
  29172. };
  29173. return Animation;
  29174. }());
  29175. // Statics
  29176. Animation._ANIMATIONTYPE_FLOAT = 0;
  29177. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29178. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29179. Animation._ANIMATIONTYPE_MATRIX = 3;
  29180. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29181. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29182. Animation._ANIMATIONTYPE_SIZE = 6;
  29183. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29184. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29185. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29186. BABYLON.Animation = Animation;
  29187. })(BABYLON || (BABYLON = {}));
  29188. //# sourceMappingURL=babylon.animation.js.map
  29189. var BABYLON;
  29190. (function (BABYLON) {
  29191. var Animatable = (function () {
  29192. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29193. if (fromFrame === void 0) { fromFrame = 0; }
  29194. if (toFrame === void 0) { toFrame = 100; }
  29195. if (loopAnimation === void 0) { loopAnimation = false; }
  29196. if (speedRatio === void 0) { speedRatio = 1.0; }
  29197. this.target = target;
  29198. this.fromFrame = fromFrame;
  29199. this.toFrame = toFrame;
  29200. this.loopAnimation = loopAnimation;
  29201. this.speedRatio = speedRatio;
  29202. this.onAnimationEnd = onAnimationEnd;
  29203. this._localDelayOffset = null;
  29204. this._pausedDelay = null;
  29205. this._animations = new Array();
  29206. this._paused = false;
  29207. this.animationStarted = false;
  29208. if (animations) {
  29209. this.appendAnimations(target, animations);
  29210. }
  29211. this._scene = scene;
  29212. scene._activeAnimatables.push(this);
  29213. }
  29214. // Methods
  29215. Animatable.prototype.getAnimations = function () {
  29216. return this._animations;
  29217. };
  29218. Animatable.prototype.appendAnimations = function (target, animations) {
  29219. for (var index = 0; index < animations.length; index++) {
  29220. var animation = animations[index];
  29221. animation._target = target;
  29222. this._animations.push(animation);
  29223. }
  29224. };
  29225. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29226. var animations = this._animations;
  29227. for (var index = 0; index < animations.length; index++) {
  29228. if (animations[index].targetProperty === property) {
  29229. return animations[index];
  29230. }
  29231. }
  29232. return null;
  29233. };
  29234. Animatable.prototype.reset = function () {
  29235. var animations = this._animations;
  29236. for (var index = 0; index < animations.length; index++) {
  29237. animations[index].reset();
  29238. }
  29239. this._localDelayOffset = null;
  29240. this._pausedDelay = null;
  29241. };
  29242. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29243. var animations = this._animations;
  29244. for (var index = 0; index < animations.length; index++) {
  29245. animations[index].enableBlending = true;
  29246. animations[index].blendingSpeed = blendingSpeed;
  29247. }
  29248. };
  29249. Animatable.prototype.disableBlending = function () {
  29250. var animations = this._animations;
  29251. for (var index = 0; index < animations.length; index++) {
  29252. animations[index].enableBlending = false;
  29253. }
  29254. };
  29255. Animatable.prototype.goToFrame = function (frame) {
  29256. var animations = this._animations;
  29257. if (animations[0]) {
  29258. var fps = animations[0].framePerSecond;
  29259. var currentFrame = animations[0].currentFrame;
  29260. var adjustTime = frame - currentFrame;
  29261. var delay = adjustTime * 1000 / fps;
  29262. this._localDelayOffset -= delay;
  29263. }
  29264. for (var index = 0; index < animations.length; index++) {
  29265. animations[index].goToFrame(frame);
  29266. }
  29267. };
  29268. Animatable.prototype.pause = function () {
  29269. if (this._paused) {
  29270. return;
  29271. }
  29272. this._paused = true;
  29273. };
  29274. Animatable.prototype.restart = function () {
  29275. this._paused = false;
  29276. };
  29277. Animatable.prototype.stop = function (animationName) {
  29278. if (animationName) {
  29279. var idx = this._scene._activeAnimatables.indexOf(this);
  29280. if (idx > -1) {
  29281. var animations = this._animations;
  29282. for (var index = animations.length - 1; index >= 0; index--) {
  29283. if (typeof animationName === "string" && animations[index].name != animationName) {
  29284. continue;
  29285. }
  29286. animations[index].reset();
  29287. animations.splice(index, 1);
  29288. }
  29289. if (animations.length == 0) {
  29290. this._scene._activeAnimatables.splice(idx, 1);
  29291. if (this.onAnimationEnd) {
  29292. this.onAnimationEnd();
  29293. }
  29294. }
  29295. }
  29296. }
  29297. else {
  29298. var index = this._scene._activeAnimatables.indexOf(this);
  29299. if (index > -1) {
  29300. this._scene._activeAnimatables.splice(index, 1);
  29301. var animations = this._animations;
  29302. for (var index = 0; index < animations.length; index++) {
  29303. animations[index].reset();
  29304. }
  29305. if (this.onAnimationEnd) {
  29306. this.onAnimationEnd();
  29307. }
  29308. }
  29309. }
  29310. };
  29311. Animatable.prototype._animate = function (delay) {
  29312. if (this._paused) {
  29313. this.animationStarted = false;
  29314. if (this._pausedDelay === null) {
  29315. this._pausedDelay = delay;
  29316. }
  29317. return true;
  29318. }
  29319. if (this._localDelayOffset === null) {
  29320. this._localDelayOffset = delay;
  29321. }
  29322. else if (this._pausedDelay !== null) {
  29323. this._localDelayOffset += delay - this._pausedDelay;
  29324. this._pausedDelay = null;
  29325. }
  29326. // Animating
  29327. var running = false;
  29328. var animations = this._animations;
  29329. var index;
  29330. for (index = 0; index < animations.length; index++) {
  29331. var animation = animations[index];
  29332. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29333. running = running || isRunning;
  29334. }
  29335. this.animationStarted = running;
  29336. if (!running) {
  29337. // Remove from active animatables
  29338. index = this._scene._activeAnimatables.indexOf(this);
  29339. this._scene._activeAnimatables.splice(index, 1);
  29340. }
  29341. if (!running && this.onAnimationEnd) {
  29342. this.onAnimationEnd();
  29343. this.onAnimationEnd = null;
  29344. }
  29345. return running;
  29346. };
  29347. return Animatable;
  29348. }());
  29349. BABYLON.Animatable = Animatable;
  29350. })(BABYLON || (BABYLON = {}));
  29351. //# sourceMappingURL=babylon.animatable.js.map
  29352. var BABYLON;
  29353. (function (BABYLON) {
  29354. var EasingFunction = (function () {
  29355. function EasingFunction() {
  29356. // Properties
  29357. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29358. }
  29359. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29360. get: function () {
  29361. return EasingFunction._EASINGMODE_EASEIN;
  29362. },
  29363. enumerable: true,
  29364. configurable: true
  29365. });
  29366. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29367. get: function () {
  29368. return EasingFunction._EASINGMODE_EASEOUT;
  29369. },
  29370. enumerable: true,
  29371. configurable: true
  29372. });
  29373. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29374. get: function () {
  29375. return EasingFunction._EASINGMODE_EASEINOUT;
  29376. },
  29377. enumerable: true,
  29378. configurable: true
  29379. });
  29380. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29381. var n = Math.min(Math.max(easingMode, 0), 2);
  29382. this._easingMode = n;
  29383. };
  29384. EasingFunction.prototype.getEasingMode = function () {
  29385. return this._easingMode;
  29386. };
  29387. EasingFunction.prototype.easeInCore = function (gradient) {
  29388. throw new Error('You must implement this method');
  29389. };
  29390. EasingFunction.prototype.ease = function (gradient) {
  29391. switch (this._easingMode) {
  29392. case EasingFunction.EASINGMODE_EASEIN:
  29393. return this.easeInCore(gradient);
  29394. case EasingFunction.EASINGMODE_EASEOUT:
  29395. return (1 - this.easeInCore(1 - gradient));
  29396. }
  29397. if (gradient >= 0.5) {
  29398. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29399. }
  29400. return (this.easeInCore(gradient * 2) * 0.5);
  29401. };
  29402. return EasingFunction;
  29403. }());
  29404. //Statics
  29405. EasingFunction._EASINGMODE_EASEIN = 0;
  29406. EasingFunction._EASINGMODE_EASEOUT = 1;
  29407. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29408. BABYLON.EasingFunction = EasingFunction;
  29409. var CircleEase = (function (_super) {
  29410. __extends(CircleEase, _super);
  29411. function CircleEase() {
  29412. return _super !== null && _super.apply(this, arguments) || this;
  29413. }
  29414. CircleEase.prototype.easeInCore = function (gradient) {
  29415. gradient = Math.max(0, Math.min(1, gradient));
  29416. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29417. };
  29418. return CircleEase;
  29419. }(EasingFunction));
  29420. BABYLON.CircleEase = CircleEase;
  29421. var BackEase = (function (_super) {
  29422. __extends(BackEase, _super);
  29423. function BackEase(amplitude) {
  29424. if (amplitude === void 0) { amplitude = 1; }
  29425. var _this = _super.call(this) || this;
  29426. _this.amplitude = amplitude;
  29427. return _this;
  29428. }
  29429. BackEase.prototype.easeInCore = function (gradient) {
  29430. var num = Math.max(0, this.amplitude);
  29431. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29432. };
  29433. return BackEase;
  29434. }(EasingFunction));
  29435. BABYLON.BackEase = BackEase;
  29436. var BounceEase = (function (_super) {
  29437. __extends(BounceEase, _super);
  29438. function BounceEase(bounces, bounciness) {
  29439. if (bounces === void 0) { bounces = 3; }
  29440. if (bounciness === void 0) { bounciness = 2; }
  29441. var _this = _super.call(this) || this;
  29442. _this.bounces = bounces;
  29443. _this.bounciness = bounciness;
  29444. return _this;
  29445. }
  29446. BounceEase.prototype.easeInCore = function (gradient) {
  29447. var y = Math.max(0.0, this.bounces);
  29448. var bounciness = this.bounciness;
  29449. if (bounciness <= 1.0) {
  29450. bounciness = 1.001;
  29451. }
  29452. var num9 = Math.pow(bounciness, y);
  29453. var num5 = 1.0 - bounciness;
  29454. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29455. var num15 = gradient * num4;
  29456. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29457. var num3 = Math.floor(num65);
  29458. var num13 = num3 + 1.0;
  29459. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29460. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29461. var num7 = (num8 + num12) * 0.5;
  29462. var num6 = gradient - num7;
  29463. var num2 = num7 - num8;
  29464. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29465. };
  29466. return BounceEase;
  29467. }(EasingFunction));
  29468. BABYLON.BounceEase = BounceEase;
  29469. var CubicEase = (function (_super) {
  29470. __extends(CubicEase, _super);
  29471. function CubicEase() {
  29472. return _super !== null && _super.apply(this, arguments) || this;
  29473. }
  29474. CubicEase.prototype.easeInCore = function (gradient) {
  29475. return (gradient * gradient * gradient);
  29476. };
  29477. return CubicEase;
  29478. }(EasingFunction));
  29479. BABYLON.CubicEase = CubicEase;
  29480. var ElasticEase = (function (_super) {
  29481. __extends(ElasticEase, _super);
  29482. function ElasticEase(oscillations, springiness) {
  29483. if (oscillations === void 0) { oscillations = 3; }
  29484. if (springiness === void 0) { springiness = 3; }
  29485. var _this = _super.call(this) || this;
  29486. _this.oscillations = oscillations;
  29487. _this.springiness = springiness;
  29488. return _this;
  29489. }
  29490. ElasticEase.prototype.easeInCore = function (gradient) {
  29491. var num2;
  29492. var num3 = Math.max(0.0, this.oscillations);
  29493. var num = Math.max(0.0, this.springiness);
  29494. if (num == 0) {
  29495. num2 = gradient;
  29496. }
  29497. else {
  29498. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29499. }
  29500. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29501. };
  29502. return ElasticEase;
  29503. }(EasingFunction));
  29504. BABYLON.ElasticEase = ElasticEase;
  29505. var ExponentialEase = (function (_super) {
  29506. __extends(ExponentialEase, _super);
  29507. function ExponentialEase(exponent) {
  29508. if (exponent === void 0) { exponent = 2; }
  29509. var _this = _super.call(this) || this;
  29510. _this.exponent = exponent;
  29511. return _this;
  29512. }
  29513. ExponentialEase.prototype.easeInCore = function (gradient) {
  29514. if (this.exponent <= 0) {
  29515. return gradient;
  29516. }
  29517. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29518. };
  29519. return ExponentialEase;
  29520. }(EasingFunction));
  29521. BABYLON.ExponentialEase = ExponentialEase;
  29522. var PowerEase = (function (_super) {
  29523. __extends(PowerEase, _super);
  29524. function PowerEase(power) {
  29525. if (power === void 0) { power = 2; }
  29526. var _this = _super.call(this) || this;
  29527. _this.power = power;
  29528. return _this;
  29529. }
  29530. PowerEase.prototype.easeInCore = function (gradient) {
  29531. var y = Math.max(0.0, this.power);
  29532. return Math.pow(gradient, y);
  29533. };
  29534. return PowerEase;
  29535. }(EasingFunction));
  29536. BABYLON.PowerEase = PowerEase;
  29537. var QuadraticEase = (function (_super) {
  29538. __extends(QuadraticEase, _super);
  29539. function QuadraticEase() {
  29540. return _super !== null && _super.apply(this, arguments) || this;
  29541. }
  29542. QuadraticEase.prototype.easeInCore = function (gradient) {
  29543. return (gradient * gradient);
  29544. };
  29545. return QuadraticEase;
  29546. }(EasingFunction));
  29547. BABYLON.QuadraticEase = QuadraticEase;
  29548. var QuarticEase = (function (_super) {
  29549. __extends(QuarticEase, _super);
  29550. function QuarticEase() {
  29551. return _super !== null && _super.apply(this, arguments) || this;
  29552. }
  29553. QuarticEase.prototype.easeInCore = function (gradient) {
  29554. return (gradient * gradient * gradient * gradient);
  29555. };
  29556. return QuarticEase;
  29557. }(EasingFunction));
  29558. BABYLON.QuarticEase = QuarticEase;
  29559. var QuinticEase = (function (_super) {
  29560. __extends(QuinticEase, _super);
  29561. function QuinticEase() {
  29562. return _super !== null && _super.apply(this, arguments) || this;
  29563. }
  29564. QuinticEase.prototype.easeInCore = function (gradient) {
  29565. return (gradient * gradient * gradient * gradient * gradient);
  29566. };
  29567. return QuinticEase;
  29568. }(EasingFunction));
  29569. BABYLON.QuinticEase = QuinticEase;
  29570. var SineEase = (function (_super) {
  29571. __extends(SineEase, _super);
  29572. function SineEase() {
  29573. return _super !== null && _super.apply(this, arguments) || this;
  29574. }
  29575. SineEase.prototype.easeInCore = function (gradient) {
  29576. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29577. };
  29578. return SineEase;
  29579. }(EasingFunction));
  29580. BABYLON.SineEase = SineEase;
  29581. var BezierCurveEase = (function (_super) {
  29582. __extends(BezierCurveEase, _super);
  29583. function BezierCurveEase(x1, y1, x2, y2) {
  29584. if (x1 === void 0) { x1 = 0; }
  29585. if (y1 === void 0) { y1 = 0; }
  29586. if (x2 === void 0) { x2 = 1; }
  29587. if (y2 === void 0) { y2 = 1; }
  29588. var _this = _super.call(this) || this;
  29589. _this.x1 = x1;
  29590. _this.y1 = y1;
  29591. _this.x2 = x2;
  29592. _this.y2 = y2;
  29593. return _this;
  29594. }
  29595. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29596. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29597. };
  29598. return BezierCurveEase;
  29599. }(EasingFunction));
  29600. BABYLON.BezierCurveEase = BezierCurveEase;
  29601. })(BABYLON || (BABYLON = {}));
  29602. //# sourceMappingURL=babylon.easing.js.map
  29603. var BABYLON;
  29604. (function (BABYLON) {
  29605. BABYLON.CameraInputTypes = {};
  29606. var CameraInputsManager = (function () {
  29607. function CameraInputsManager(camera) {
  29608. this.attached = {};
  29609. this.camera = camera;
  29610. this.checkInputs = function () { };
  29611. }
  29612. CameraInputsManager.prototype.add = function (input) {
  29613. var type = input.getSimpleName();
  29614. if (this.attached[type]) {
  29615. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29616. return;
  29617. }
  29618. this.attached[type] = input;
  29619. input.camera = this.camera;
  29620. //for checkInputs, we are dynamically creating a function
  29621. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29622. if (input.checkInputs) {
  29623. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29624. }
  29625. if (this.attachedElement) {
  29626. input.attachControl(this.attachedElement);
  29627. }
  29628. };
  29629. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29630. for (var cam in this.attached) {
  29631. var input = this.attached[cam];
  29632. if (input === inputToRemove) {
  29633. input.detachControl(this.attachedElement);
  29634. delete this.attached[cam];
  29635. this.rebuildInputCheck();
  29636. }
  29637. }
  29638. };
  29639. CameraInputsManager.prototype.removeByType = function (inputType) {
  29640. for (var cam in this.attached) {
  29641. var input = this.attached[cam];
  29642. if (input.getTypeName() === inputType) {
  29643. input.detachControl(this.attachedElement);
  29644. delete this.attached[cam];
  29645. this.rebuildInputCheck();
  29646. }
  29647. }
  29648. };
  29649. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29650. var current = this.checkInputs;
  29651. return function () {
  29652. current();
  29653. fn();
  29654. };
  29655. };
  29656. CameraInputsManager.prototype.attachInput = function (input) {
  29657. input.attachControl(this.attachedElement, this.noPreventDefault);
  29658. };
  29659. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29660. if (this.attachedElement) {
  29661. return;
  29662. }
  29663. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29664. this.attachedElement = element;
  29665. this.noPreventDefault = noPreventDefault;
  29666. for (var cam in this.attached) {
  29667. var input = this.attached[cam];
  29668. this.attached[cam].attachControl(element, noPreventDefault);
  29669. }
  29670. };
  29671. CameraInputsManager.prototype.detachElement = function (element) {
  29672. if (this.attachedElement !== element) {
  29673. return;
  29674. }
  29675. for (var cam in this.attached) {
  29676. var input = this.attached[cam];
  29677. this.attached[cam].detachControl(element);
  29678. }
  29679. this.attachedElement = null;
  29680. };
  29681. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29682. this.checkInputs = function () { };
  29683. for (var cam in this.attached) {
  29684. var input = this.attached[cam];
  29685. if (input.checkInputs) {
  29686. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29687. }
  29688. }
  29689. };
  29690. CameraInputsManager.prototype.clear = function () {
  29691. if (this.attachedElement) {
  29692. this.detachElement(this.attachedElement);
  29693. }
  29694. this.attached = {};
  29695. this.attachedElement = null;
  29696. this.checkInputs = function () { };
  29697. };
  29698. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29699. var inputs = {};
  29700. for (var cam in this.attached) {
  29701. var input = this.attached[cam];
  29702. var res = BABYLON.SerializationHelper.Serialize(input);
  29703. inputs[input.getTypeName()] = res;
  29704. }
  29705. serializedCamera.inputsmgr = inputs;
  29706. };
  29707. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29708. var parsedInputs = parsedCamera.inputsmgr;
  29709. if (parsedInputs) {
  29710. this.clear();
  29711. for (var n in parsedInputs) {
  29712. var construct = BABYLON.CameraInputTypes[n];
  29713. if (construct) {
  29714. var parsedinput = parsedInputs[n];
  29715. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29716. this.add(input);
  29717. }
  29718. }
  29719. }
  29720. else {
  29721. //2016-03-08 this part is for managing backward compatibility
  29722. for (var n in this.attached) {
  29723. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29724. if (construct) {
  29725. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29726. this.remove(this.attached[n]);
  29727. this.add(input);
  29728. }
  29729. }
  29730. }
  29731. };
  29732. return CameraInputsManager;
  29733. }());
  29734. BABYLON.CameraInputsManager = CameraInputsManager;
  29735. })(BABYLON || (BABYLON = {}));
  29736. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29737. /// <reference path="babylon.camera.ts" />
  29738. var BABYLON;
  29739. (function (BABYLON) {
  29740. var TargetCamera = (function (_super) {
  29741. __extends(TargetCamera, _super);
  29742. function TargetCamera(name, position, scene) {
  29743. var _this = _super.call(this, name, position, scene) || this;
  29744. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29745. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29746. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29747. _this.speed = 2.0;
  29748. _this.noRotationConstraint = false;
  29749. _this.lockedTarget = null;
  29750. _this._currentTarget = BABYLON.Vector3.Zero();
  29751. _this._viewMatrix = BABYLON.Matrix.Zero();
  29752. _this._camMatrix = BABYLON.Matrix.Zero();
  29753. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29754. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29755. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29756. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29757. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29758. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29759. _this._tempMatrix = BABYLON.Matrix.Zero();
  29760. return _this;
  29761. }
  29762. TargetCamera.prototype.getFrontPosition = function (distance) {
  29763. var direction = this.getTarget().subtract(this.position);
  29764. direction.normalize();
  29765. direction.scaleInPlace(distance);
  29766. return this.globalPosition.add(direction);
  29767. };
  29768. TargetCamera.prototype._getLockedTargetPosition = function () {
  29769. if (!this.lockedTarget) {
  29770. return null;
  29771. }
  29772. if (this.lockedTarget.absolutePosition) {
  29773. this.lockedTarget.computeWorldMatrix();
  29774. }
  29775. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29776. };
  29777. // Cache
  29778. TargetCamera.prototype._initCache = function () {
  29779. _super.prototype._initCache.call(this);
  29780. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29781. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29782. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29783. };
  29784. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29785. if (!ignoreParentClass) {
  29786. _super.prototype._updateCache.call(this);
  29787. }
  29788. var lockedTargetPosition = this._getLockedTargetPosition();
  29789. if (!lockedTargetPosition) {
  29790. this._cache.lockedTarget = null;
  29791. }
  29792. else {
  29793. if (!this._cache.lockedTarget) {
  29794. this._cache.lockedTarget = lockedTargetPosition.clone();
  29795. }
  29796. else {
  29797. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29798. }
  29799. }
  29800. this._cache.rotation.copyFrom(this.rotation);
  29801. if (this.rotationQuaternion)
  29802. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29803. };
  29804. // Synchronized
  29805. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29806. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29807. return false;
  29808. }
  29809. var lockedTargetPosition = this._getLockedTargetPosition();
  29810. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29811. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29812. };
  29813. // Methods
  29814. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29815. var engine = this.getEngine();
  29816. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29817. };
  29818. // Target
  29819. TargetCamera.prototype.setTarget = function (target) {
  29820. this.upVector.normalize();
  29821. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29822. this._camMatrix.invert();
  29823. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29824. var vDir = target.subtract(this.position);
  29825. if (vDir.x >= 0.0) {
  29826. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29827. }
  29828. else {
  29829. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29830. }
  29831. this.rotation.z = 0;
  29832. if (isNaN(this.rotation.x)) {
  29833. this.rotation.x = 0;
  29834. }
  29835. if (isNaN(this.rotation.y)) {
  29836. this.rotation.y = 0;
  29837. }
  29838. if (isNaN(this.rotation.z)) {
  29839. this.rotation.z = 0;
  29840. }
  29841. if (this.rotationQuaternion) {
  29842. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29843. }
  29844. };
  29845. /**
  29846. * Return the current target position of the camera. This value is expressed in local space.
  29847. */
  29848. TargetCamera.prototype.getTarget = function () {
  29849. return this._currentTarget;
  29850. };
  29851. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29852. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29853. };
  29854. TargetCamera.prototype._updatePosition = function () {
  29855. if (this.parent) {
  29856. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29857. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29858. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29859. return;
  29860. }
  29861. this.position.addInPlace(this.cameraDirection);
  29862. };
  29863. TargetCamera.prototype._checkInputs = function () {
  29864. var needToMove = this._decideIfNeedsToMove();
  29865. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29866. // Move
  29867. if (needToMove) {
  29868. this._updatePosition();
  29869. }
  29870. // Rotate
  29871. if (needToRotate) {
  29872. this.rotation.x += this.cameraRotation.x;
  29873. this.rotation.y += this.cameraRotation.y;
  29874. //rotate, if quaternion is set and rotation was used
  29875. if (this.rotationQuaternion) {
  29876. var len = this.rotation.lengthSquared();
  29877. if (len) {
  29878. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29879. }
  29880. }
  29881. if (!this.noRotationConstraint) {
  29882. var limit = (Math.PI / 2) * 0.95;
  29883. if (this.rotation.x > limit)
  29884. this.rotation.x = limit;
  29885. if (this.rotation.x < -limit)
  29886. this.rotation.x = -limit;
  29887. }
  29888. }
  29889. // Inertia
  29890. if (needToMove) {
  29891. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  29892. this.cameraDirection.x = 0;
  29893. }
  29894. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  29895. this.cameraDirection.y = 0;
  29896. }
  29897. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  29898. this.cameraDirection.z = 0;
  29899. }
  29900. this.cameraDirection.scaleInPlace(this.inertia);
  29901. }
  29902. if (needToRotate) {
  29903. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  29904. this.cameraRotation.x = 0;
  29905. }
  29906. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  29907. this.cameraRotation.y = 0;
  29908. }
  29909. this.cameraRotation.scaleInPlace(this.inertia);
  29910. }
  29911. _super.prototype._checkInputs.call(this);
  29912. };
  29913. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29914. if (this.rotationQuaternion) {
  29915. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29916. //update the up vector!
  29917. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29918. }
  29919. else {
  29920. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29921. }
  29922. };
  29923. TargetCamera.prototype._getViewMatrix = function () {
  29924. if (!this.lockedTarget) {
  29925. // Compute
  29926. this._updateCameraRotationMatrix();
  29927. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29928. // Computing target and final matrix
  29929. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29930. }
  29931. else {
  29932. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29933. }
  29934. if (this.getScene().useRightHandedSystem) {
  29935. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29936. }
  29937. else {
  29938. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29939. }
  29940. return this._viewMatrix;
  29941. };
  29942. /**
  29943. * @override
  29944. * Override Camera.createRigCamera
  29945. */
  29946. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29947. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29948. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29949. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29950. if (!this.rotationQuaternion) {
  29951. this.rotationQuaternion = new BABYLON.Quaternion();
  29952. }
  29953. rigCamera._cameraRigParams = {};
  29954. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29955. }
  29956. return rigCamera;
  29957. }
  29958. return null;
  29959. };
  29960. /**
  29961. * @override
  29962. * Override Camera._updateRigCameras
  29963. */
  29964. TargetCamera.prototype._updateRigCameras = function () {
  29965. var camLeft = this._rigCameras[0];
  29966. var camRight = this._rigCameras[1];
  29967. switch (this.cameraRigMode) {
  29968. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29969. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29970. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29971. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29972. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29973. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29974. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29975. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29976. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29977. camLeft.setTarget(this.getTarget());
  29978. camRight.setTarget(this.getTarget());
  29979. break;
  29980. case BABYLON.Camera.RIG_MODE_VR:
  29981. if (camLeft.rotationQuaternion) {
  29982. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29983. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29984. }
  29985. else {
  29986. camLeft.rotation.copyFrom(this.rotation);
  29987. camRight.rotation.copyFrom(this.rotation);
  29988. }
  29989. camLeft.position.copyFrom(this.position);
  29990. camRight.position.copyFrom(this.position);
  29991. break;
  29992. }
  29993. _super.prototype._updateRigCameras.call(this);
  29994. };
  29995. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  29996. if (!this._rigCamTransformMatrix) {
  29997. this._rigCamTransformMatrix = new BABYLON.Matrix();
  29998. }
  29999. var target = this.getTarget();
  30000. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30001. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30002. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30003. };
  30004. TargetCamera.prototype.getClassName = function () {
  30005. return "TargetCamera";
  30006. };
  30007. return TargetCamera;
  30008. }(BABYLON.Camera));
  30009. __decorate([
  30010. BABYLON.serializeAsVector3()
  30011. ], TargetCamera.prototype, "rotation", void 0);
  30012. __decorate([
  30013. BABYLON.serialize()
  30014. ], TargetCamera.prototype, "speed", void 0);
  30015. __decorate([
  30016. BABYLON.serializeAsMeshReference("lockedTargetId")
  30017. ], TargetCamera.prototype, "lockedTarget", void 0);
  30018. BABYLON.TargetCamera = TargetCamera;
  30019. })(BABYLON || (BABYLON = {}));
  30020. //# sourceMappingURL=babylon.targetCamera.js.map
  30021. var BABYLON;
  30022. (function (BABYLON) {
  30023. var ArcRotateCameraKeyboardMoveInput = (function () {
  30024. function ArcRotateCameraKeyboardMoveInput() {
  30025. this._keys = [];
  30026. this.keysUp = [38];
  30027. this.keysDown = [40];
  30028. this.keysLeft = [37];
  30029. this.keysRight = [39];
  30030. }
  30031. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30032. var _this = this;
  30033. element.tabIndex = 1;
  30034. this._onKeyDown = function (evt) {
  30035. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30036. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30037. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30038. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30039. var index = _this._keys.indexOf(evt.keyCode);
  30040. if (index === -1) {
  30041. _this._keys.push(evt.keyCode);
  30042. }
  30043. if (evt.preventDefault) {
  30044. if (!noPreventDefault) {
  30045. evt.preventDefault();
  30046. }
  30047. }
  30048. }
  30049. };
  30050. this._onKeyUp = function (evt) {
  30051. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30052. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30053. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30054. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30055. var index = _this._keys.indexOf(evt.keyCode);
  30056. if (index >= 0) {
  30057. _this._keys.splice(index, 1);
  30058. }
  30059. if (evt.preventDefault) {
  30060. if (!noPreventDefault) {
  30061. evt.preventDefault();
  30062. }
  30063. }
  30064. }
  30065. };
  30066. this._onLostFocus = function () {
  30067. _this._keys = [];
  30068. };
  30069. element.addEventListener("keydown", this._onKeyDown, false);
  30070. element.addEventListener("keyup", this._onKeyUp, false);
  30071. BABYLON.Tools.RegisterTopRootEvents([
  30072. { name: "blur", handler: this._onLostFocus }
  30073. ]);
  30074. };
  30075. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30076. if (element) {
  30077. element.removeEventListener("keydown", this._onKeyDown);
  30078. element.removeEventListener("keyup", this._onKeyUp);
  30079. }
  30080. BABYLON.Tools.UnregisterTopRootEvents([
  30081. { name: "blur", handler: this._onLostFocus }
  30082. ]);
  30083. this._keys = [];
  30084. this._onKeyDown = null;
  30085. this._onKeyUp = null;
  30086. this._onLostFocus = null;
  30087. };
  30088. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30089. if (this._onKeyDown) {
  30090. var camera = this.camera;
  30091. for (var index = 0; index < this._keys.length; index++) {
  30092. var keyCode = this._keys[index];
  30093. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30094. camera.inertialAlphaOffset -= 0.01;
  30095. }
  30096. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30097. camera.inertialBetaOffset -= 0.01;
  30098. }
  30099. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30100. camera.inertialAlphaOffset += 0.01;
  30101. }
  30102. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30103. camera.inertialBetaOffset += 0.01;
  30104. }
  30105. }
  30106. }
  30107. };
  30108. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30109. return "ArcRotateCameraKeyboardMoveInput";
  30110. };
  30111. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30112. return "keyboard";
  30113. };
  30114. return ArcRotateCameraKeyboardMoveInput;
  30115. }());
  30116. __decorate([
  30117. BABYLON.serialize()
  30118. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30119. __decorate([
  30120. BABYLON.serialize()
  30121. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30122. __decorate([
  30123. BABYLON.serialize()
  30124. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30125. __decorate([
  30126. BABYLON.serialize()
  30127. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30128. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30129. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30130. })(BABYLON || (BABYLON = {}));
  30131. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30132. var BABYLON;
  30133. (function (BABYLON) {
  30134. var ArcRotateCameraMouseWheelInput = (function () {
  30135. function ArcRotateCameraMouseWheelInput() {
  30136. this.wheelPrecision = 3.0;
  30137. }
  30138. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30139. var _this = this;
  30140. this._wheel = function (p, s) {
  30141. //sanity check - this should be a PointerWheel event.
  30142. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30143. return;
  30144. var event = p.event;
  30145. var delta = 0;
  30146. if (event.wheelDelta) {
  30147. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30148. }
  30149. else if (event.detail) {
  30150. delta = -event.detail / _this.wheelPrecision;
  30151. }
  30152. if (delta)
  30153. _this.camera.inertialRadiusOffset += delta;
  30154. if (event.preventDefault) {
  30155. if (!noPreventDefault) {
  30156. event.preventDefault();
  30157. }
  30158. }
  30159. };
  30160. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30161. };
  30162. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30163. if (this._observer && element) {
  30164. this.camera.getScene().onPointerObservable.remove(this._observer);
  30165. this._observer = null;
  30166. this._wheel = null;
  30167. }
  30168. };
  30169. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30170. return "ArcRotateCameraMouseWheelInput";
  30171. };
  30172. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30173. return "mousewheel";
  30174. };
  30175. return ArcRotateCameraMouseWheelInput;
  30176. }());
  30177. __decorate([
  30178. BABYLON.serialize()
  30179. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30180. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30181. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30182. })(BABYLON || (BABYLON = {}));
  30183. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30184. var BABYLON;
  30185. (function (BABYLON) {
  30186. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30187. var ArcRotateCameraPointersInput = (function () {
  30188. function ArcRotateCameraPointersInput() {
  30189. this.buttons = [0, 1, 2];
  30190. this.angularSensibilityX = 1000.0;
  30191. this.angularSensibilityY = 1000.0;
  30192. this.pinchPrecision = 6.0;
  30193. this.panningSensibility = 50.0;
  30194. this._isPanClick = false;
  30195. this.pinchInwards = true;
  30196. }
  30197. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30198. var _this = this;
  30199. var engine = this.camera.getEngine();
  30200. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30201. var pointA, pointB;
  30202. var previousPinchDistance = 0;
  30203. this._pointerInput = function (p, s) {
  30204. var evt = p.event;
  30205. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30206. return;
  30207. }
  30208. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30209. try {
  30210. evt.srcElement.setPointerCapture(evt.pointerId);
  30211. }
  30212. catch (e) {
  30213. //Nothing to do with the error. Execution will continue.
  30214. }
  30215. // Manage panning with pan button click
  30216. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30217. // manage pointers
  30218. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30219. if (pointA === undefined) {
  30220. pointA = cacheSoloPointer;
  30221. }
  30222. else if (pointB === undefined) {
  30223. pointB = cacheSoloPointer;
  30224. }
  30225. if (!noPreventDefault) {
  30226. evt.preventDefault();
  30227. element.focus();
  30228. }
  30229. }
  30230. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30231. try {
  30232. evt.srcElement.releasePointerCapture(evt.pointerId);
  30233. }
  30234. catch (e) {
  30235. //Nothing to do with the error.
  30236. }
  30237. cacheSoloPointer = null;
  30238. previousPinchDistance = 0;
  30239. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30240. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30241. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30242. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30243. pointA = pointB = undefined;
  30244. if (!noPreventDefault) {
  30245. evt.preventDefault();
  30246. }
  30247. }
  30248. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30249. if (!noPreventDefault) {
  30250. evt.preventDefault();
  30251. }
  30252. // One button down
  30253. if (pointA && pointB === undefined) {
  30254. if (_this.panningSensibility !== 0 &&
  30255. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30256. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30257. _this.camera
  30258. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30259. _this.camera
  30260. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30261. }
  30262. else {
  30263. var offsetX = evt.clientX - cacheSoloPointer.x;
  30264. var offsetY = evt.clientY - cacheSoloPointer.y;
  30265. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30266. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30267. }
  30268. cacheSoloPointer.x = evt.clientX;
  30269. cacheSoloPointer.y = evt.clientY;
  30270. }
  30271. else if (pointA && pointB) {
  30272. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30273. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30274. ed.x = evt.clientX;
  30275. ed.y = evt.clientY;
  30276. var direction = _this.pinchInwards ? 1 : -1;
  30277. var distX = pointA.x - pointB.x;
  30278. var distY = pointA.y - pointB.y;
  30279. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30280. if (previousPinchDistance === 0) {
  30281. previousPinchDistance = pinchSquaredDistance;
  30282. return;
  30283. }
  30284. if (pinchSquaredDistance !== previousPinchDistance) {
  30285. _this.camera
  30286. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30287. (_this.pinchPrecision *
  30288. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30289. direction);
  30290. previousPinchDistance = pinchSquaredDistance;
  30291. }
  30292. }
  30293. }
  30294. };
  30295. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30296. this._onContextMenu = function (evt) {
  30297. evt.preventDefault();
  30298. };
  30299. if (!this.camera._useCtrlForPanning) {
  30300. element.addEventListener("contextmenu", this._onContextMenu, false);
  30301. }
  30302. this._onLostFocus = function () {
  30303. //this._keys = [];
  30304. pointA = pointB = undefined;
  30305. previousPinchDistance = 0;
  30306. cacheSoloPointer = null;
  30307. };
  30308. this._onMouseMove = function (evt) {
  30309. if (!engine.isPointerLock) {
  30310. return;
  30311. }
  30312. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30313. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30314. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30315. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30316. if (!noPreventDefault) {
  30317. evt.preventDefault();
  30318. }
  30319. };
  30320. this._onGestureStart = function (e) {
  30321. if (window.MSGesture === undefined) {
  30322. return;
  30323. }
  30324. if (!_this._MSGestureHandler) {
  30325. _this._MSGestureHandler = new MSGesture();
  30326. _this._MSGestureHandler.target = element;
  30327. }
  30328. _this._MSGestureHandler.addPointer(e.pointerId);
  30329. };
  30330. this._onGesture = function (e) {
  30331. _this.camera.radius *= e.scale;
  30332. if (e.preventDefault) {
  30333. if (!noPreventDefault) {
  30334. e.stopPropagation();
  30335. e.preventDefault();
  30336. }
  30337. }
  30338. };
  30339. element.addEventListener("mousemove", this._onMouseMove, false);
  30340. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30341. element.addEventListener("MSGestureChange", this._onGesture, false);
  30342. BABYLON.Tools.RegisterTopRootEvents([
  30343. { name: "blur", handler: this._onLostFocus }
  30344. ]);
  30345. };
  30346. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30347. if (element && this._observer) {
  30348. this.camera.getScene().onPointerObservable.remove(this._observer);
  30349. this._observer = null;
  30350. element.removeEventListener("contextmenu", this._onContextMenu);
  30351. element.removeEventListener("mousemove", this._onMouseMove);
  30352. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30353. element.removeEventListener("MSGestureChange", this._onGesture);
  30354. this._isPanClick = false;
  30355. this.pinchInwards = true;
  30356. this._onMouseMove = null;
  30357. this._onGestureStart = null;
  30358. this._onGesture = null;
  30359. this._MSGestureHandler = null;
  30360. this._onLostFocus = null;
  30361. this._onContextMenu = null;
  30362. }
  30363. BABYLON.Tools.UnregisterTopRootEvents([
  30364. { name: "blur", handler: this._onLostFocus }
  30365. ]);
  30366. };
  30367. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30368. return "ArcRotateCameraPointersInput";
  30369. };
  30370. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30371. return "pointers";
  30372. };
  30373. return ArcRotateCameraPointersInput;
  30374. }());
  30375. __decorate([
  30376. BABYLON.serialize()
  30377. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30378. __decorate([
  30379. BABYLON.serialize()
  30380. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30381. __decorate([
  30382. BABYLON.serialize()
  30383. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30384. __decorate([
  30385. BABYLON.serialize()
  30386. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30387. __decorate([
  30388. BABYLON.serialize()
  30389. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30390. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30391. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30392. })(BABYLON || (BABYLON = {}));
  30393. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30394. /// <reference path="babylon.targetCamera.ts" />
  30395. /// <reference path="..\Tools\babylon.tools.ts" />
  30396. var BABYLON;
  30397. (function (BABYLON) {
  30398. var ArcRotateCamera = (function (_super) {
  30399. __extends(ArcRotateCamera, _super);
  30400. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30401. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30402. _this.inertialAlphaOffset = 0;
  30403. _this.inertialBetaOffset = 0;
  30404. _this.inertialRadiusOffset = 0;
  30405. _this.lowerAlphaLimit = null;
  30406. _this.upperAlphaLimit = null;
  30407. _this.lowerBetaLimit = 0.01;
  30408. _this.upperBetaLimit = Math.PI;
  30409. _this.lowerRadiusLimit = null;
  30410. _this.upperRadiusLimit = null;
  30411. _this.inertialPanningX = 0;
  30412. _this.inertialPanningY = 0;
  30413. _this.panningInertia = 0.9;
  30414. //-- end properties for backward compatibility for inputs
  30415. _this.zoomOnFactor = 1;
  30416. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30417. _this.allowUpsideDown = true;
  30418. _this._viewMatrix = new BABYLON.Matrix();
  30419. // Panning
  30420. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30421. _this.checkCollisions = false;
  30422. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30423. _this._previousPosition = BABYLON.Vector3.Zero();
  30424. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30425. _this._newPosition = BABYLON.Vector3.Zero();
  30426. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30427. if (collidedMesh === void 0) { collidedMesh = null; }
  30428. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30429. newPosition.multiplyInPlace(_this._collider.radius);
  30430. }
  30431. if (!collidedMesh) {
  30432. _this._previousPosition.copyFrom(_this.position);
  30433. }
  30434. else {
  30435. _this.setPosition(newPosition);
  30436. if (_this.onCollide) {
  30437. _this.onCollide(collidedMesh);
  30438. }
  30439. }
  30440. // Recompute because of constraints
  30441. var cosa = Math.cos(_this.alpha);
  30442. var sina = Math.sin(_this.alpha);
  30443. var cosb = Math.cos(_this.beta);
  30444. var sinb = Math.sin(_this.beta);
  30445. if (sinb === 0) {
  30446. sinb = 0.0001;
  30447. }
  30448. var target = _this._getTargetPosition();
  30449. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30450. _this.position.copyFrom(_this._newPosition);
  30451. var up = _this.upVector;
  30452. if (_this.allowUpsideDown && _this.beta < 0) {
  30453. up = up.clone();
  30454. up = up.negate();
  30455. }
  30456. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30457. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30458. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30459. _this._collisionTriggered = false;
  30460. };
  30461. _this._target = BABYLON.Vector3.Zero();
  30462. if (target) {
  30463. _this.setTarget(target);
  30464. }
  30465. _this.alpha = alpha;
  30466. _this.beta = beta;
  30467. _this.radius = radius;
  30468. _this.getViewMatrix();
  30469. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30470. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30471. return _this;
  30472. }
  30473. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30474. get: function () {
  30475. return this._target;
  30476. },
  30477. set: function (value) {
  30478. this.setTarget(value);
  30479. },
  30480. enumerable: true,
  30481. configurable: true
  30482. });
  30483. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30484. //-- begin properties for backward compatibility for inputs
  30485. get: function () {
  30486. var pointers = this.inputs.attached["pointers"];
  30487. if (pointers)
  30488. return pointers.angularSensibilityX;
  30489. },
  30490. set: function (value) {
  30491. var pointers = this.inputs.attached["pointers"];
  30492. if (pointers) {
  30493. pointers.angularSensibilityX = value;
  30494. }
  30495. },
  30496. enumerable: true,
  30497. configurable: true
  30498. });
  30499. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30500. get: function () {
  30501. var pointers = this.inputs.attached["pointers"];
  30502. if (pointers)
  30503. return pointers.angularSensibilityY;
  30504. },
  30505. set: function (value) {
  30506. var pointers = this.inputs.attached["pointers"];
  30507. if (pointers) {
  30508. pointers.angularSensibilityY = value;
  30509. }
  30510. },
  30511. enumerable: true,
  30512. configurable: true
  30513. });
  30514. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30515. get: function () {
  30516. var pointers = this.inputs.attached["pointers"];
  30517. if (pointers)
  30518. return pointers.pinchPrecision;
  30519. },
  30520. set: function (value) {
  30521. var pointers = this.inputs.attached["pointers"];
  30522. if (pointers) {
  30523. pointers.pinchPrecision = value;
  30524. }
  30525. },
  30526. enumerable: true,
  30527. configurable: true
  30528. });
  30529. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30530. get: function () {
  30531. var pointers = this.inputs.attached["pointers"];
  30532. if (pointers)
  30533. return pointers.panningSensibility;
  30534. },
  30535. set: function (value) {
  30536. var pointers = this.inputs.attached["pointers"];
  30537. if (pointers) {
  30538. pointers.panningSensibility = value;
  30539. }
  30540. },
  30541. enumerable: true,
  30542. configurable: true
  30543. });
  30544. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30545. get: function () {
  30546. var keyboard = this.inputs.attached["keyboard"];
  30547. if (keyboard)
  30548. return keyboard.keysUp;
  30549. },
  30550. set: function (value) {
  30551. var keyboard = this.inputs.attached["keyboard"];
  30552. if (keyboard)
  30553. keyboard.keysUp = value;
  30554. },
  30555. enumerable: true,
  30556. configurable: true
  30557. });
  30558. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30559. get: function () {
  30560. var keyboard = this.inputs.attached["keyboard"];
  30561. if (keyboard)
  30562. return keyboard.keysDown;
  30563. },
  30564. set: function (value) {
  30565. var keyboard = this.inputs.attached["keyboard"];
  30566. if (keyboard)
  30567. keyboard.keysDown = value;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30573. get: function () {
  30574. var keyboard = this.inputs.attached["keyboard"];
  30575. if (keyboard)
  30576. return keyboard.keysLeft;
  30577. },
  30578. set: function (value) {
  30579. var keyboard = this.inputs.attached["keyboard"];
  30580. if (keyboard)
  30581. keyboard.keysLeft = value;
  30582. },
  30583. enumerable: true,
  30584. configurable: true
  30585. });
  30586. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30587. get: function () {
  30588. var keyboard = this.inputs.attached["keyboard"];
  30589. if (keyboard)
  30590. return keyboard.keysRight;
  30591. },
  30592. set: function (value) {
  30593. var keyboard = this.inputs.attached["keyboard"];
  30594. if (keyboard)
  30595. keyboard.keysRight = value;
  30596. },
  30597. enumerable: true,
  30598. configurable: true
  30599. });
  30600. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30601. get: function () {
  30602. var mousewheel = this.inputs.attached["mousewheel"];
  30603. if (mousewheel)
  30604. return mousewheel.wheelPrecision;
  30605. },
  30606. set: function (value) {
  30607. var mousewheel = this.inputs.attached["mousewheel"];
  30608. if (mousewheel)
  30609. mousewheel.wheelPrecision = value;
  30610. },
  30611. enumerable: true,
  30612. configurable: true
  30613. });
  30614. // Cache
  30615. ArcRotateCamera.prototype._initCache = function () {
  30616. _super.prototype._initCache.call(this);
  30617. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30618. this._cache.alpha = undefined;
  30619. this._cache.beta = undefined;
  30620. this._cache.radius = undefined;
  30621. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30622. };
  30623. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30624. if (!ignoreParentClass) {
  30625. _super.prototype._updateCache.call(this);
  30626. }
  30627. this._cache._target.copyFrom(this._getTargetPosition());
  30628. this._cache.alpha = this.alpha;
  30629. this._cache.beta = this.beta;
  30630. this._cache.radius = this.radius;
  30631. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30632. };
  30633. ArcRotateCamera.prototype._getTargetPosition = function () {
  30634. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30635. var pos = this._targetHost.getAbsolutePosition();
  30636. if (this._targetBoundingCenter) {
  30637. pos.addToRef(this._targetBoundingCenter, this._target);
  30638. }
  30639. else {
  30640. this._target.copyFrom(pos);
  30641. }
  30642. }
  30643. var lockedTargetPosition = this._getLockedTargetPosition();
  30644. if (lockedTargetPosition) {
  30645. return lockedTargetPosition;
  30646. }
  30647. return this._target;
  30648. };
  30649. // Synchronized
  30650. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30651. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30652. return false;
  30653. return this._cache._target.equals(this._getTargetPosition())
  30654. && this._cache.alpha === this.alpha
  30655. && this._cache.beta === this.beta
  30656. && this._cache.radius === this.radius
  30657. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30658. };
  30659. // Methods
  30660. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30661. var _this = this;
  30662. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30663. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30664. this._useCtrlForPanning = useCtrlForPanning;
  30665. this._panningMouseButton = panningMouseButton;
  30666. this.inputs.attachElement(element, noPreventDefault);
  30667. this._reset = function () {
  30668. _this.inertialAlphaOffset = 0;
  30669. _this.inertialBetaOffset = 0;
  30670. _this.inertialRadiusOffset = 0;
  30671. };
  30672. };
  30673. ArcRotateCamera.prototype.detachControl = function (element) {
  30674. this.inputs.detachElement(element);
  30675. if (this._reset) {
  30676. this._reset();
  30677. }
  30678. };
  30679. ArcRotateCamera.prototype._checkInputs = function () {
  30680. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30681. if (this._collisionTriggered) {
  30682. return;
  30683. }
  30684. this.inputs.checkInputs();
  30685. // Inertia
  30686. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30687. if (this.getScene().useRightHandedSystem) {
  30688. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30689. }
  30690. else {
  30691. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30692. }
  30693. this.beta += this.inertialBetaOffset;
  30694. this.radius -= this.inertialRadiusOffset;
  30695. this.inertialAlphaOffset *= this.inertia;
  30696. this.inertialBetaOffset *= this.inertia;
  30697. this.inertialRadiusOffset *= this.inertia;
  30698. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30699. this.inertialAlphaOffset = 0;
  30700. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30701. this.inertialBetaOffset = 0;
  30702. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30703. this.inertialRadiusOffset = 0;
  30704. }
  30705. // Panning inertia
  30706. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30707. if (!this._localDirection) {
  30708. this._localDirection = BABYLON.Vector3.Zero();
  30709. this._transformedDirection = BABYLON.Vector3.Zero();
  30710. }
  30711. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30712. this._localDirection.multiplyInPlace(this.panningAxis);
  30713. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30714. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30715. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30716. if (!this.panningAxis.y) {
  30717. this._transformedDirection.y = 0;
  30718. }
  30719. if (!this._targetHost) {
  30720. this._target.addInPlace(this._transformedDirection);
  30721. }
  30722. this.inertialPanningX *= this.panningInertia;
  30723. this.inertialPanningY *= this.panningInertia;
  30724. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30725. this.inertialPanningX = 0;
  30726. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30727. this.inertialPanningY = 0;
  30728. }
  30729. // Limits
  30730. this._checkLimits();
  30731. _super.prototype._checkInputs.call(this);
  30732. };
  30733. ArcRotateCamera.prototype._checkLimits = function () {
  30734. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30735. if (this.allowUpsideDown && this.beta > Math.PI) {
  30736. this.beta = this.beta - (2 * Math.PI);
  30737. }
  30738. }
  30739. else {
  30740. if (this.beta < this.lowerBetaLimit) {
  30741. this.beta = this.lowerBetaLimit;
  30742. }
  30743. }
  30744. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30745. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30746. this.beta = this.beta + (2 * Math.PI);
  30747. }
  30748. }
  30749. else {
  30750. if (this.beta > this.upperBetaLimit) {
  30751. this.beta = this.upperBetaLimit;
  30752. }
  30753. }
  30754. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30755. this.alpha = this.lowerAlphaLimit;
  30756. }
  30757. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30758. this.alpha = this.upperAlphaLimit;
  30759. }
  30760. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30761. this.radius = this.lowerRadiusLimit;
  30762. }
  30763. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30764. this.radius = this.upperRadiusLimit;
  30765. }
  30766. };
  30767. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30768. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30769. this.radius = radiusv3.length();
  30770. // Alpha
  30771. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30772. if (radiusv3.z < 0) {
  30773. this.alpha = 2 * Math.PI - this.alpha;
  30774. }
  30775. // Beta
  30776. this.beta = Math.acos(radiusv3.y / this.radius);
  30777. this._checkLimits();
  30778. };
  30779. ArcRotateCamera.prototype.setPosition = function (position) {
  30780. if (this.position.equals(position)) {
  30781. return;
  30782. }
  30783. this.position.copyFrom(position);
  30784. this.rebuildAnglesAndRadius();
  30785. };
  30786. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30787. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30788. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30789. if (target.getBoundingInfo) {
  30790. if (toBoundingCenter) {
  30791. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30792. }
  30793. else {
  30794. this._targetBoundingCenter = null;
  30795. }
  30796. this._targetHost = target;
  30797. this._target = this._getTargetPosition();
  30798. }
  30799. else {
  30800. var newTarget = target;
  30801. var currentTarget = this._getTargetPosition();
  30802. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  30803. return;
  30804. }
  30805. this._target = newTarget;
  30806. this._targetBoundingCenter = null;
  30807. }
  30808. this.rebuildAnglesAndRadius();
  30809. };
  30810. ArcRotateCamera.prototype._getViewMatrix = function () {
  30811. // Compute
  30812. var cosa = Math.cos(this.alpha);
  30813. var sina = Math.sin(this.alpha);
  30814. var cosb = Math.cos(this.beta);
  30815. var sinb = Math.sin(this.beta);
  30816. if (sinb === 0) {
  30817. sinb = 0.0001;
  30818. }
  30819. var target = this._getTargetPosition();
  30820. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30821. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30822. if (!this._collider) {
  30823. this._collider = new BABYLON.Collider();
  30824. }
  30825. this._collider.radius = this.collisionRadius;
  30826. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30827. this._collisionTriggered = true;
  30828. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30829. }
  30830. else {
  30831. this.position.copyFrom(this._newPosition);
  30832. var up = this.upVector;
  30833. if (this.allowUpsideDown && sinb < 0) {
  30834. up = up.clone();
  30835. up = up.negate();
  30836. }
  30837. if (this.getScene().useRightHandedSystem) {
  30838. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30839. }
  30840. else {
  30841. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30842. }
  30843. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30844. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30845. }
  30846. this._currentTarget = target;
  30847. return this._viewMatrix;
  30848. };
  30849. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30850. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30851. meshes = meshes || this.getScene().meshes;
  30852. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30853. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30854. this.radius = distance * this.zoomOnFactor;
  30855. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30856. };
  30857. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30858. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30859. var meshesOrMinMaxVector;
  30860. var distance;
  30861. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30862. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30863. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30864. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30865. }
  30866. else {
  30867. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30868. distance = meshesOrMinMaxVectorAndDistance.distance;
  30869. }
  30870. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30871. if (!doNotUpdateMaxZ) {
  30872. this.maxZ = distance * 2;
  30873. }
  30874. };
  30875. /**
  30876. * @override
  30877. * Override Camera.createRigCamera
  30878. */
  30879. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30880. var alphaShift;
  30881. switch (this.cameraRigMode) {
  30882. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30883. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30884. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30885. case BABYLON.Camera.RIG_MODE_VR:
  30886. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30887. break;
  30888. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30889. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30890. break;
  30891. }
  30892. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  30893. rigCam._cameraRigParams = {};
  30894. return rigCam;
  30895. };
  30896. /**
  30897. * @override
  30898. * Override Camera._updateRigCameras
  30899. */
  30900. ArcRotateCamera.prototype._updateRigCameras = function () {
  30901. var camLeft = this._rigCameras[0];
  30902. var camRight = this._rigCameras[1];
  30903. camLeft.beta = camRight.beta = this.beta;
  30904. camLeft.radius = camRight.radius = this.radius;
  30905. switch (this.cameraRigMode) {
  30906. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30907. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30909. case BABYLON.Camera.RIG_MODE_VR:
  30910. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30911. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30912. break;
  30913. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30914. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30915. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30916. break;
  30917. }
  30918. _super.prototype._updateRigCameras.call(this);
  30919. };
  30920. ArcRotateCamera.prototype.dispose = function () {
  30921. this.inputs.clear();
  30922. _super.prototype.dispose.call(this);
  30923. };
  30924. ArcRotateCamera.prototype.getClassName = function () {
  30925. return "ArcRotateCamera";
  30926. };
  30927. return ArcRotateCamera;
  30928. }(BABYLON.TargetCamera));
  30929. __decorate([
  30930. BABYLON.serialize()
  30931. ], ArcRotateCamera.prototype, "alpha", void 0);
  30932. __decorate([
  30933. BABYLON.serialize()
  30934. ], ArcRotateCamera.prototype, "beta", void 0);
  30935. __decorate([
  30936. BABYLON.serialize()
  30937. ], ArcRotateCamera.prototype, "radius", void 0);
  30938. __decorate([
  30939. BABYLON.serializeAsVector3("target")
  30940. ], ArcRotateCamera.prototype, "_target", void 0);
  30941. __decorate([
  30942. BABYLON.serialize()
  30943. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30944. __decorate([
  30945. BABYLON.serialize()
  30946. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30947. __decorate([
  30948. BABYLON.serialize()
  30949. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30950. __decorate([
  30951. BABYLON.serialize()
  30952. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30953. __decorate([
  30954. BABYLON.serialize()
  30955. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30956. __decorate([
  30957. BABYLON.serialize()
  30958. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30959. __decorate([
  30960. BABYLON.serialize()
  30961. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30962. __decorate([
  30963. BABYLON.serialize()
  30964. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30965. __decorate([
  30966. BABYLON.serialize()
  30967. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30968. __decorate([
  30969. BABYLON.serialize()
  30970. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30971. __decorate([
  30972. BABYLON.serialize()
  30973. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30974. __decorate([
  30975. BABYLON.serialize()
  30976. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  30977. __decorate([
  30978. BABYLON.serialize()
  30979. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30980. __decorate([
  30981. BABYLON.serialize()
  30982. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30983. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30984. })(BABYLON || (BABYLON = {}));
  30985. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30986. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30987. var BABYLON;
  30988. (function (BABYLON) {
  30989. var ArcRotateCameraInputsManager = (function (_super) {
  30990. __extends(ArcRotateCameraInputsManager, _super);
  30991. function ArcRotateCameraInputsManager(camera) {
  30992. return _super.call(this, camera) || this;
  30993. }
  30994. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  30995. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  30996. return this;
  30997. };
  30998. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  30999. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31000. return this;
  31001. };
  31002. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31003. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31004. return this;
  31005. };
  31006. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31007. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31008. return this;
  31009. };
  31010. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31011. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31012. return this;
  31013. };
  31014. return ArcRotateCameraInputsManager;
  31015. }(BABYLON.CameraInputsManager));
  31016. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31017. })(BABYLON || (BABYLON = {}));
  31018. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31019. var BABYLON;
  31020. (function (BABYLON) {
  31021. var CubeTexture = (function (_super) {
  31022. __extends(CubeTexture, _super);
  31023. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  31024. if (onLoad === void 0) { onLoad = null; }
  31025. if (onError === void 0) { onError = null; }
  31026. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31027. var _this = _super.call(this, scene) || this;
  31028. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  31029. _this.name = rootUrl;
  31030. _this.url = rootUrl;
  31031. _this._noMipmap = noMipmap;
  31032. _this.hasAlpha = false;
  31033. _this._format = format;
  31034. if (!rootUrl && !files) {
  31035. return _this;
  31036. }
  31037. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  31038. if (!files) {
  31039. if (!extensions) {
  31040. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  31041. }
  31042. files = [];
  31043. for (var index = 0; index < extensions.length; index++) {
  31044. files.push(rootUrl + extensions[index]);
  31045. }
  31046. _this._extensions = extensions;
  31047. }
  31048. _this._files = files;
  31049. if (!_this._texture) {
  31050. if (!scene.useDelayedTextureLoading) {
  31051. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  31052. }
  31053. else {
  31054. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31055. }
  31056. }
  31057. else if (onLoad) {
  31058. if (_this._texture.isReady) {
  31059. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  31060. }
  31061. else {
  31062. _this._texture.onLoadedCallbacks.push(onLoad);
  31063. }
  31064. }
  31065. _this.isCube = true;
  31066. _this._textureMatrix = BABYLON.Matrix.Identity();
  31067. return _this;
  31068. }
  31069. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  31070. return new CubeTexture("", scene, null, noMipmap, files);
  31071. };
  31072. // Methods
  31073. CubeTexture.prototype.delayLoad = function () {
  31074. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31075. return;
  31076. }
  31077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31078. this._texture = this._getFromCache(this.url, this._noMipmap);
  31079. if (!this._texture) {
  31080. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  31081. }
  31082. };
  31083. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  31084. return this._textureMatrix;
  31085. };
  31086. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31087. var texture = BABYLON.SerializationHelper.Parse(function () {
  31088. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  31089. }, parsedTexture, scene);
  31090. // Animations
  31091. if (parsedTexture.animations) {
  31092. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31093. var parsedAnimation = parsedTexture.animations[animationIndex];
  31094. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31095. }
  31096. }
  31097. return texture;
  31098. };
  31099. CubeTexture.prototype.clone = function () {
  31100. var _this = this;
  31101. return BABYLON.SerializationHelper.Clone(function () {
  31102. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  31103. }, this);
  31104. };
  31105. return CubeTexture;
  31106. }(BABYLON.BaseTexture));
  31107. BABYLON.CubeTexture = CubeTexture;
  31108. })(BABYLON || (BABYLON = {}));
  31109. //# sourceMappingURL=babylon.cubeTexture.js.map
  31110. var BABYLON;
  31111. (function (BABYLON) {
  31112. var RenderTargetTexture = (function (_super) {
  31113. __extends(RenderTargetTexture, _super);
  31114. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  31115. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  31116. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31117. if (isCube === void 0) { isCube = false; }
  31118. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31119. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31120. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  31121. if (isMulti === void 0) { isMulti = false; }
  31122. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  31123. _this.isCube = isCube;
  31124. /**
  31125. * Use this list to define the list of mesh you want to render.
  31126. */
  31127. _this.renderList = new Array();
  31128. _this.renderParticles = true;
  31129. _this.renderSprites = false;
  31130. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  31131. // Events
  31132. /**
  31133. * An event triggered when the texture is unbind.
  31134. * @type {BABYLON.Observable}
  31135. */
  31136. _this.onAfterUnbindObservable = new BABYLON.Observable();
  31137. /**
  31138. * An event triggered before rendering the texture
  31139. * @type {BABYLON.Observable}
  31140. */
  31141. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31142. /**
  31143. * An event triggered after rendering the texture
  31144. * @type {BABYLON.Observable}
  31145. */
  31146. _this.onAfterRenderObservable = new BABYLON.Observable();
  31147. /**
  31148. * An event triggered after the texture clear
  31149. * @type {BABYLON.Observable}
  31150. */
  31151. _this.onClearObservable = new BABYLON.Observable();
  31152. _this._currentRefreshId = -1;
  31153. _this._refreshRate = 1;
  31154. _this._samples = 1;
  31155. scene = _this.getScene();
  31156. _this.name = name;
  31157. _this.isRenderTarget = true;
  31158. _this._size = size;
  31159. _this._generateMipMaps = generateMipMaps;
  31160. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  31161. // Rendering groups
  31162. _this._renderingManager = new BABYLON.RenderingManager(scene);
  31163. if (isMulti) {
  31164. return _this;
  31165. }
  31166. _this._renderTargetOptions = {
  31167. generateMipMaps: generateMipMaps,
  31168. type: type,
  31169. samplingMode: samplingMode,
  31170. generateDepthBuffer: generateDepthBuffer,
  31171. generateStencilBuffer: generateStencilBuffer
  31172. };
  31173. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31174. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31175. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31176. }
  31177. if (isCube) {
  31178. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  31179. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  31180. _this._textureMatrix = BABYLON.Matrix.Identity();
  31181. }
  31182. else {
  31183. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  31184. }
  31185. return _this;
  31186. }
  31187. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  31188. get: function () {
  31189. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  31195. get: function () {
  31196. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  31202. get: function () {
  31203. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  31204. },
  31205. enumerable: true,
  31206. configurable: true
  31207. });
  31208. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  31209. set: function (callback) {
  31210. if (this._onAfterUnbindObserver) {
  31211. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  31212. }
  31213. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  31219. set: function (callback) {
  31220. if (this._onBeforeRenderObserver) {
  31221. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31222. }
  31223. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  31229. set: function (callback) {
  31230. if (this._onAfterRenderObserver) {
  31231. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31232. }
  31233. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31239. set: function (callback) {
  31240. if (this._onClearObserver) {
  31241. this.onClearObservable.remove(this._onClearObserver);
  31242. }
  31243. this._onClearObserver = this.onClearObservable.add(callback);
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31249. get: function () {
  31250. return this._renderTargetOptions;
  31251. },
  31252. enumerable: true,
  31253. configurable: true
  31254. });
  31255. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31256. get: function () {
  31257. return this._samples;
  31258. },
  31259. set: function (value) {
  31260. if (this._samples === value) {
  31261. return;
  31262. }
  31263. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31264. },
  31265. enumerable: true,
  31266. configurable: true
  31267. });
  31268. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31269. this._currentRefreshId = -1;
  31270. };
  31271. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31272. get: function () {
  31273. return this._refreshRate;
  31274. },
  31275. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31276. set: function (value) {
  31277. this._refreshRate = value;
  31278. this.resetRefreshCounter();
  31279. },
  31280. enumerable: true,
  31281. configurable: true
  31282. });
  31283. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31284. if (!this._postProcessManager) {
  31285. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31286. this._postProcesses = new Array();
  31287. }
  31288. this._postProcesses.push(postProcess);
  31289. this._postProcesses[0].autoClear = false;
  31290. };
  31291. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31292. if (!this._postProcesses) {
  31293. return;
  31294. }
  31295. if (dispose) {
  31296. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31297. var postProcess = _a[_i];
  31298. postProcess.dispose();
  31299. postProcess = null;
  31300. }
  31301. }
  31302. this._postProcesses = [];
  31303. };
  31304. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31305. if (!this._postProcesses) {
  31306. return;
  31307. }
  31308. var index = this._postProcesses.indexOf(postProcess);
  31309. if (index === -1) {
  31310. return;
  31311. }
  31312. this._postProcesses.splice(index, 1);
  31313. if (this._postProcesses.length > 0) {
  31314. this._postProcesses[0].autoClear = false;
  31315. }
  31316. };
  31317. RenderTargetTexture.prototype._shouldRender = function () {
  31318. if (this._currentRefreshId === -1) {
  31319. this._currentRefreshId = 1;
  31320. return true;
  31321. }
  31322. if (this.refreshRate === this._currentRefreshId) {
  31323. this._currentRefreshId = 1;
  31324. return true;
  31325. }
  31326. this._currentRefreshId++;
  31327. return false;
  31328. };
  31329. RenderTargetTexture.prototype.isReady = function () {
  31330. if (!this.getScene().renderTargetsEnabled) {
  31331. return false;
  31332. }
  31333. return _super.prototype.isReady.call(this);
  31334. };
  31335. RenderTargetTexture.prototype.getRenderSize = function () {
  31336. return this._size;
  31337. };
  31338. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31339. get: function () {
  31340. return true;
  31341. },
  31342. enumerable: true,
  31343. configurable: true
  31344. });
  31345. RenderTargetTexture.prototype.scale = function (ratio) {
  31346. var newSize = this._size * ratio;
  31347. this.resize(newSize);
  31348. };
  31349. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31350. if (this.isCube) {
  31351. return this._textureMatrix;
  31352. }
  31353. return _super.prototype.getReflectionTextureMatrix.call(this);
  31354. };
  31355. RenderTargetTexture.prototype.resize = function (size) {
  31356. this.releaseInternalTexture();
  31357. if (this.isCube) {
  31358. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31359. }
  31360. else {
  31361. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31362. }
  31363. };
  31364. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31365. var scene = this.getScene();
  31366. var engine = scene.getEngine();
  31367. if (this.useCameraPostProcesses !== undefined) {
  31368. useCameraPostProcess = this.useCameraPostProcesses;
  31369. }
  31370. if (this._waitingRenderList) {
  31371. this.renderList = [];
  31372. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31373. var id = this._waitingRenderList[index];
  31374. this.renderList.push(scene.getMeshByID(id));
  31375. }
  31376. delete this._waitingRenderList;
  31377. }
  31378. // Is predicate defined?
  31379. if (this.renderListPredicate) {
  31380. this.renderList.splice(0); // Clear previous renderList
  31381. var sceneMeshes = this.getScene().meshes;
  31382. for (var index = 0; index < sceneMeshes.length; index++) {
  31383. var mesh = sceneMeshes[index];
  31384. if (this.renderListPredicate(mesh)) {
  31385. this.renderList.push(mesh);
  31386. }
  31387. }
  31388. }
  31389. if (this.renderList && this.renderList.length === 0) {
  31390. return;
  31391. }
  31392. // Set custom projection.
  31393. // Needs to be before binding to prevent changing the aspect ratio.
  31394. var camera;
  31395. if (this.activeCamera) {
  31396. camera = this.activeCamera;
  31397. engine.setViewport(this.activeCamera.viewport);
  31398. if (this.activeCamera !== scene.activeCamera) {
  31399. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31400. }
  31401. }
  31402. else {
  31403. camera = scene.activeCamera;
  31404. engine.setViewport(scene.activeCamera.viewport);
  31405. }
  31406. // Prepare renderingManager
  31407. this._renderingManager.reset();
  31408. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31409. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31410. var sceneRenderId = scene.getRenderId();
  31411. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31412. var mesh = currentRenderList[meshIndex];
  31413. if (mesh) {
  31414. if (!mesh.isReady()) {
  31415. // Reset _currentRefreshId
  31416. this.resetRefreshCounter();
  31417. continue;
  31418. }
  31419. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31420. var isMasked = void 0;
  31421. if (!this.renderList) {
  31422. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31423. }
  31424. else {
  31425. isMasked = false;
  31426. }
  31427. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31428. mesh._activate(sceneRenderId);
  31429. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31430. var subMesh = mesh.subMeshes[subIndex];
  31431. scene._activeIndices.addCount(subMesh.indexCount, false);
  31432. this._renderingManager.dispatch(subMesh);
  31433. }
  31434. }
  31435. }
  31436. }
  31437. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31438. var particleSystem = scene.particleSystems[particleIndex];
  31439. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31440. continue;
  31441. }
  31442. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31443. this._renderingManager.dispatchParticles(particleSystem);
  31444. }
  31445. }
  31446. if (this.isCube) {
  31447. for (var face = 0; face < 6; face++) {
  31448. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31449. scene.incrementRenderId();
  31450. scene.resetCachedMaterial();
  31451. }
  31452. }
  31453. else {
  31454. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31455. }
  31456. this.onAfterUnbindObservable.notifyObservers(this);
  31457. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31458. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31459. }
  31460. engine.setViewport(scene.activeCamera.viewport);
  31461. scene.resetCachedMaterial();
  31462. };
  31463. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31464. var _this = this;
  31465. var scene = this.getScene();
  31466. var engine = scene.getEngine();
  31467. // Bind
  31468. if (this._postProcessManager) {
  31469. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31470. }
  31471. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31472. if (this.isCube) {
  31473. engine.bindFramebuffer(this._texture, faceIndex);
  31474. }
  31475. else {
  31476. engine.bindFramebuffer(this._texture);
  31477. }
  31478. }
  31479. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31480. // Clear
  31481. if (this.onClearObservable.hasObservers()) {
  31482. this.onClearObservable.notifyObservers(engine);
  31483. }
  31484. else {
  31485. engine.clear(scene.clearColor, true, true, true);
  31486. }
  31487. if (!this._doNotChangeAspectRatio) {
  31488. scene.updateTransformMatrix(true);
  31489. }
  31490. // Render
  31491. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31492. if (this._postProcessManager) {
  31493. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31494. }
  31495. else if (useCameraPostProcess) {
  31496. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31497. }
  31498. if (!this._doNotChangeAspectRatio) {
  31499. scene.updateTransformMatrix(true);
  31500. }
  31501. // Dump ?
  31502. if (dumpForDebug) {
  31503. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31504. }
  31505. // Unbind
  31506. if (!this.isCube || faceIndex === 5) {
  31507. if (this.isCube) {
  31508. if (faceIndex === 5) {
  31509. engine.generateMipMapsForCubemap(this._texture);
  31510. }
  31511. }
  31512. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31513. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31514. });
  31515. }
  31516. else {
  31517. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31518. }
  31519. };
  31520. /**
  31521. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31522. * This allowed control for front to back rendering or reversly depending of the special needs.
  31523. *
  31524. * @param renderingGroupId The rendering group id corresponding to its index
  31525. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31526. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31527. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31528. */
  31529. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31530. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31531. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31532. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31533. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31534. };
  31535. /**
  31536. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31537. *
  31538. * @param renderingGroupId The rendering group id corresponding to its index
  31539. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31540. */
  31541. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31542. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31543. };
  31544. RenderTargetTexture.prototype.clone = function () {
  31545. var textureSize = this.getSize();
  31546. 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);
  31547. // Base texture
  31548. newTexture.hasAlpha = this.hasAlpha;
  31549. newTexture.level = this.level;
  31550. // RenderTarget Texture
  31551. newTexture.coordinatesMode = this.coordinatesMode;
  31552. newTexture.renderList = this.renderList.slice(0);
  31553. return newTexture;
  31554. };
  31555. RenderTargetTexture.prototype.serialize = function () {
  31556. if (!this.name) {
  31557. return null;
  31558. }
  31559. var serializationObject = _super.prototype.serialize.call(this);
  31560. serializationObject.renderTargetSize = this.getRenderSize();
  31561. serializationObject.renderList = [];
  31562. for (var index = 0; index < this.renderList.length; index++) {
  31563. serializationObject.renderList.push(this.renderList[index].id);
  31564. }
  31565. return serializationObject;
  31566. };
  31567. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  31568. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  31569. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  31570. };
  31571. RenderTargetTexture.prototype.dispose = function () {
  31572. if (this._postProcessManager) {
  31573. this._postProcessManager.dispose();
  31574. this._postProcessManager = null;
  31575. }
  31576. this.clearPostProcesses(true);
  31577. // Remove from custom render targets
  31578. var scene = this.getScene();
  31579. var index = scene.customRenderTargets.indexOf(this);
  31580. if (index >= 0) {
  31581. scene.customRenderTargets.splice(index, 1);
  31582. }
  31583. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  31584. var camera = _a[_i];
  31585. index = camera.customRenderTargets.indexOf(this);
  31586. if (index >= 0) {
  31587. camera.customRenderTargets.splice(index, 1);
  31588. }
  31589. }
  31590. _super.prototype.dispose.call(this);
  31591. };
  31592. return RenderTargetTexture;
  31593. }(BABYLON.Texture));
  31594. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31595. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31596. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31597. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31598. })(BABYLON || (BABYLON = {}));
  31599. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31600. var BABYLON;
  31601. (function (BABYLON) {
  31602. ;
  31603. var MultiRenderTarget = (function (_super) {
  31604. __extends(MultiRenderTarget, _super);
  31605. function MultiRenderTarget(name, size, count, scene, options) {
  31606. var _this = this;
  31607. options = options || {};
  31608. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31609. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31610. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31611. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31612. if (!_this.isSupported) {
  31613. _this.dispose();
  31614. return;
  31615. }
  31616. var types = [];
  31617. var samplingModes = [];
  31618. for (var i = 0; i < count; i++) {
  31619. if (options.types && options.types[i]) {
  31620. types.push(options.types[i]);
  31621. }
  31622. else {
  31623. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31624. }
  31625. if (options.samplingModes && options.samplingModes[i]) {
  31626. samplingModes.push(options.samplingModes[i]);
  31627. }
  31628. else {
  31629. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31630. }
  31631. }
  31632. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31633. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31634. _this._count = count;
  31635. _this._size = size;
  31636. _this._multiRenderTargetOptions = {
  31637. samplingModes: samplingModes,
  31638. generateMipMaps: generateMipMaps,
  31639. generateDepthBuffer: generateDepthBuffer,
  31640. generateStencilBuffer: generateStencilBuffer,
  31641. generateDepthTexture: generateDepthTexture,
  31642. types: types,
  31643. textureCount: count
  31644. };
  31645. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31646. _this._createInternalTextures();
  31647. return _this;
  31648. }
  31649. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31650. get: function () {
  31651. var engine = this.getScene().getEngine();
  31652. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31658. get: function () {
  31659. return this._textures;
  31660. },
  31661. enumerable: true,
  31662. configurable: true
  31663. });
  31664. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31665. get: function () {
  31666. return this._textures[this._textures.length - 1];
  31667. },
  31668. enumerable: true,
  31669. configurable: true
  31670. });
  31671. MultiRenderTarget.prototype._createInternalTextures = function () {
  31672. this._textures = [];
  31673. for (var i = 0; i < this._webGLTextures.length; i++) {
  31674. var texture = new BABYLON.Texture(null, this.getScene());
  31675. texture._texture = this._webGLTextures[i];
  31676. this._textures.push(texture);
  31677. }
  31678. // Keeps references to frame buffer and stencil/depth buffer
  31679. this._texture = this._webGLTextures[0];
  31680. };
  31681. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31682. get: function () {
  31683. return this._samples;
  31684. },
  31685. set: function (value) {
  31686. if (this._samples === value) {
  31687. return;
  31688. }
  31689. for (var i = 0; i < this._webGLTextures.length; i++) {
  31690. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31691. }
  31692. },
  31693. enumerable: true,
  31694. configurable: true
  31695. });
  31696. MultiRenderTarget.prototype.resize = function (size) {
  31697. this.releaseInternalTextures();
  31698. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31699. this._createInternalTextures();
  31700. };
  31701. MultiRenderTarget.prototype.dispose = function () {
  31702. this.releaseInternalTextures();
  31703. _super.prototype.dispose.call(this);
  31704. };
  31705. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31706. if (!this._webGLTextures) {
  31707. return;
  31708. }
  31709. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31710. if (this._webGLTextures[i] !== undefined) {
  31711. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31712. this._webGLTextures.splice(i, 1);
  31713. }
  31714. }
  31715. };
  31716. return MultiRenderTarget;
  31717. }(BABYLON.RenderTargetTexture));
  31718. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31719. })(BABYLON || (BABYLON = {}));
  31720. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31721. /// <reference path="babylon.renderTargetTexture.ts" />
  31722. var BABYLON;
  31723. (function (BABYLON) {
  31724. var MirrorTexture = (function (_super) {
  31725. __extends(MirrorTexture, _super);
  31726. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31727. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31728. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31729. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31730. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31731. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31732. _this._transformMatrix = BABYLON.Matrix.Zero();
  31733. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31734. _this._blurKernelX = 0;
  31735. _this._blurKernelY = 0;
  31736. _this._blurRatio = 1.0;
  31737. _this.onBeforeRenderObservable.add(function () {
  31738. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31739. _this._savedViewMatrix = scene.getViewMatrix();
  31740. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31741. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31742. scene.clipPlane = _this.mirrorPlane;
  31743. scene.getEngine().cullBackFaces = false;
  31744. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31745. });
  31746. _this.onAfterRenderObservable.add(function () {
  31747. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31748. scene.getEngine().cullBackFaces = true;
  31749. scene._mirroredCameraPosition = null;
  31750. delete scene.clipPlane;
  31751. });
  31752. return _this;
  31753. }
  31754. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31755. get: function () {
  31756. return this._blurRatio;
  31757. },
  31758. set: function (value) {
  31759. if (this._blurRatio === value) {
  31760. return;
  31761. }
  31762. this._blurRatio = value;
  31763. this._preparePostProcesses();
  31764. },
  31765. enumerable: true,
  31766. configurable: true
  31767. });
  31768. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  31769. set: function (value) {
  31770. this.blurKernelX = value;
  31771. this.blurKernelY = value;
  31772. },
  31773. enumerable: true,
  31774. configurable: true
  31775. });
  31776. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  31777. get: function () {
  31778. return this._blurKernelX;
  31779. },
  31780. set: function (value) {
  31781. if (this._blurKernelX === value) {
  31782. return;
  31783. }
  31784. this._blurKernelX = value;
  31785. this._preparePostProcesses();
  31786. },
  31787. enumerable: true,
  31788. configurable: true
  31789. });
  31790. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  31791. get: function () {
  31792. return this._blurKernelY;
  31793. },
  31794. set: function (value) {
  31795. if (this._blurKernelY === value) {
  31796. return;
  31797. }
  31798. this._blurKernelY = value;
  31799. this._preparePostProcesses();
  31800. },
  31801. enumerable: true,
  31802. configurable: true
  31803. });
  31804. MirrorTexture.prototype._preparePostProcesses = function () {
  31805. this.clearPostProcesses(true);
  31806. if (this._blurKernelX && this._blurKernelY) {
  31807. var engine = this.getScene().getEngine();
  31808. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  31809. 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);
  31810. this._blurX.autoClear = false;
  31811. if (this._blurRatio === 1 && this.samples < 2) {
  31812. this._blurX.outputTexture = this._texture;
  31813. }
  31814. else {
  31815. this._blurX.alwaysForcePOT = true;
  31816. }
  31817. 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);
  31818. this._blurY.autoClear = false;
  31819. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  31820. this.addPostProcess(this._blurX);
  31821. this.addPostProcess(this._blurY);
  31822. }
  31823. };
  31824. MirrorTexture.prototype.clone = function () {
  31825. var textureSize = this.getSize();
  31826. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  31827. // Base texture
  31828. newTexture.hasAlpha = this.hasAlpha;
  31829. newTexture.level = this.level;
  31830. // Mirror Texture
  31831. newTexture.mirrorPlane = this.mirrorPlane.clone();
  31832. newTexture.renderList = this.renderList.slice(0);
  31833. return newTexture;
  31834. };
  31835. MirrorTexture.prototype.serialize = function () {
  31836. if (!this.name) {
  31837. return null;
  31838. }
  31839. var serializationObject = _super.prototype.serialize.call(this);
  31840. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  31841. return serializationObject;
  31842. };
  31843. return MirrorTexture;
  31844. }(BABYLON.RenderTargetTexture));
  31845. BABYLON.MirrorTexture = MirrorTexture;
  31846. })(BABYLON || (BABYLON = {}));
  31847. //# sourceMappingURL=babylon.mirrorTexture.js.map
  31848. /// <reference path="babylon.renderTargetTexture.ts" />
  31849. var BABYLON;
  31850. (function (BABYLON) {
  31851. /**
  31852. * Creates a refraction texture used by refraction channel of the standard material.
  31853. * @param name the texture name
  31854. * @param size size of the underlying texture
  31855. * @param scene root scene
  31856. */
  31857. var RefractionTexture = (function (_super) {
  31858. __extends(RefractionTexture, _super);
  31859. function RefractionTexture(name, size, scene, generateMipMaps) {
  31860. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  31861. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  31862. _this.depth = 2.0;
  31863. _this.onBeforeRenderObservable.add(function () {
  31864. scene.clipPlane = _this.refractionPlane;
  31865. });
  31866. _this.onAfterRenderObservable.add(function () {
  31867. delete scene.clipPlane;
  31868. });
  31869. return _this;
  31870. }
  31871. RefractionTexture.prototype.clone = function () {
  31872. var textureSize = this.getSize();
  31873. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  31874. // Base texture
  31875. newTexture.hasAlpha = this.hasAlpha;
  31876. newTexture.level = this.level;
  31877. // Refraction Texture
  31878. newTexture.refractionPlane = this.refractionPlane.clone();
  31879. newTexture.renderList = this.renderList.slice(0);
  31880. newTexture.depth = this.depth;
  31881. return newTexture;
  31882. };
  31883. RefractionTexture.prototype.serialize = function () {
  31884. if (!this.name) {
  31885. return null;
  31886. }
  31887. var serializationObject = _super.prototype.serialize.call(this);
  31888. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  31889. serializationObject.depth = this.depth;
  31890. return serializationObject;
  31891. };
  31892. return RefractionTexture;
  31893. }(BABYLON.RenderTargetTexture));
  31894. BABYLON.RefractionTexture = RefractionTexture;
  31895. })(BABYLON || (BABYLON = {}));
  31896. //# sourceMappingURL=babylon.refractionTexture.js.map
  31897. /// <reference path="babylon.texture.ts" />
  31898. var BABYLON;
  31899. (function (BABYLON) {
  31900. var DynamicTexture = (function (_super) {
  31901. __extends(DynamicTexture, _super);
  31902. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  31903. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31904. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31905. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  31906. _this.name = name;
  31907. var engine = _this.getScene().getEngine();
  31908. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31909. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31910. _this._generateMipMaps = generateMipMaps;
  31911. if (options.getContext) {
  31912. _this._canvas = options;
  31913. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31914. }
  31915. else {
  31916. _this._canvas = document.createElement("canvas");
  31917. if (options.width) {
  31918. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31919. }
  31920. else {
  31921. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  31922. }
  31923. }
  31924. var textureSize = _this.getSize();
  31925. _this._canvas.width = textureSize.width;
  31926. _this._canvas.height = textureSize.height;
  31927. _this._context = _this._canvas.getContext("2d");
  31928. return _this;
  31929. }
  31930. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  31931. get: function () {
  31932. return true;
  31933. },
  31934. enumerable: true,
  31935. configurable: true
  31936. });
  31937. DynamicTexture.prototype._recreate = function (textureSize) {
  31938. this._canvas.width = textureSize.width;
  31939. this._canvas.height = textureSize.height;
  31940. this.releaseInternalTexture();
  31941. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  31942. };
  31943. DynamicTexture.prototype.scale = function (ratio) {
  31944. var textureSize = this.getSize();
  31945. textureSize.width *= ratio;
  31946. textureSize.height *= ratio;
  31947. this._recreate(textureSize);
  31948. };
  31949. DynamicTexture.prototype.scaleTo = function (width, height) {
  31950. var textureSize = this.getSize();
  31951. textureSize.width = width;
  31952. textureSize.height = height;
  31953. this._recreate(textureSize);
  31954. };
  31955. DynamicTexture.prototype.getContext = function () {
  31956. return this._context;
  31957. };
  31958. DynamicTexture.prototype.clear = function () {
  31959. var size = this.getSize();
  31960. this._context.fillRect(0, 0, size.width, size.height);
  31961. };
  31962. DynamicTexture.prototype.update = function (invertY) {
  31963. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  31964. };
  31965. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  31966. if (update === void 0) { update = true; }
  31967. var size = this.getSize();
  31968. if (clearColor) {
  31969. this._context.fillStyle = clearColor;
  31970. this._context.fillRect(0, 0, size.width, size.height);
  31971. }
  31972. this._context.font = font;
  31973. if (x === null || x === undefined) {
  31974. var textSize = this._context.measureText(text);
  31975. x = (size.width - textSize.width) / 2;
  31976. }
  31977. if (y === null || y === undefined) {
  31978. var fontSize = parseInt((font.replace(/\D/g, '')));
  31979. ;
  31980. y = (size.height / 2) + (fontSize / 3.65);
  31981. }
  31982. this._context.fillStyle = color;
  31983. this._context.fillText(text, x, y);
  31984. if (update) {
  31985. this.update(invertY);
  31986. }
  31987. };
  31988. DynamicTexture.prototype.clone = function () {
  31989. var textureSize = this.getSize();
  31990. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  31991. // Base texture
  31992. newTexture.hasAlpha = this.hasAlpha;
  31993. newTexture.level = this.level;
  31994. // Dynamic Texture
  31995. newTexture.wrapU = this.wrapU;
  31996. newTexture.wrapV = this.wrapV;
  31997. return newTexture;
  31998. };
  31999. return DynamicTexture;
  32000. }(BABYLON.Texture));
  32001. BABYLON.DynamicTexture = DynamicTexture;
  32002. })(BABYLON || (BABYLON = {}));
  32003. //# sourceMappingURL=babylon.dynamicTexture.js.map
  32004. var BABYLON;
  32005. (function (BABYLON) {
  32006. var VideoTexture = (function (_super) {
  32007. __extends(VideoTexture, _super);
  32008. /**
  32009. * Creates a video texture.
  32010. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  32011. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  32012. * @param {BABYLON.Scene} scene is obviously the current scene.
  32013. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  32014. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  32015. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  32016. */
  32017. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  32018. if (generateMipMaps === void 0) { generateMipMaps = false; }
  32019. if (invertY === void 0) { invertY = false; }
  32020. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32021. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32022. _this._autoLaunch = true;
  32023. var urls;
  32024. _this.name = name;
  32025. if (urlsOrVideo instanceof HTMLVideoElement) {
  32026. _this.video = urlsOrVideo;
  32027. }
  32028. else {
  32029. urls = urlsOrVideo;
  32030. _this.video = document.createElement("video");
  32031. _this.video.autoplay = false;
  32032. _this.video.loop = true;
  32033. }
  32034. _this._generateMipMaps = generateMipMaps;
  32035. _this._samplingMode = samplingMode;
  32036. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  32037. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32038. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32039. }
  32040. else {
  32041. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32042. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32043. _this._generateMipMaps = false;
  32044. }
  32045. if (urls) {
  32046. _this.video.addEventListener("canplay", function () {
  32047. _this._createTexture();
  32048. });
  32049. urls.forEach(function (url) {
  32050. var source = document.createElement("source");
  32051. source.src = url;
  32052. _this.video.appendChild(source);
  32053. });
  32054. }
  32055. else {
  32056. _this._createTexture();
  32057. }
  32058. _this._lastUpdate = BABYLON.Tools.Now;
  32059. return _this;
  32060. }
  32061. VideoTexture.prototype.__setTextureReady = function () {
  32062. this._texture.isReady = true;
  32063. };
  32064. VideoTexture.prototype._createTexture = function () {
  32065. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  32066. if (this._autoLaunch) {
  32067. this._autoLaunch = false;
  32068. this.video.play();
  32069. }
  32070. this._setTextureReady = this.__setTextureReady.bind(this);
  32071. this.video.addEventListener("playing", this._setTextureReady);
  32072. };
  32073. VideoTexture.prototype.update = function () {
  32074. var now = BABYLON.Tools.Now;
  32075. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  32076. return false;
  32077. }
  32078. this._lastUpdate = now;
  32079. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  32080. return true;
  32081. };
  32082. VideoTexture.prototype.dispose = function () {
  32083. _super.prototype.dispose.call(this);
  32084. this.video.removeEventListener("playing", this._setTextureReady);
  32085. };
  32086. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  32087. var video = document.createElement("video");
  32088. var constraintsDeviceId;
  32089. if (constraints && constraints.deviceId) {
  32090. constraintsDeviceId = {
  32091. exact: constraints.deviceId
  32092. };
  32093. }
  32094. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  32095. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  32096. if (navigator.getUserMedia) {
  32097. navigator.getUserMedia({
  32098. video: {
  32099. deviceId: constraintsDeviceId,
  32100. width: {
  32101. min: (constraints && constraints.minWidth) || 256,
  32102. max: (constraints && constraints.maxWidth) || 640
  32103. },
  32104. height: {
  32105. min: (constraints && constraints.minHeight) || 256,
  32106. max: (constraints && constraints.maxHeight) || 480
  32107. }
  32108. }
  32109. }, function (stream) {
  32110. if (video.mozSrcObject !== undefined) {
  32111. video.mozSrcObject = stream;
  32112. }
  32113. else {
  32114. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  32115. }
  32116. video.play();
  32117. if (onReady) {
  32118. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  32119. }
  32120. }, function (e) {
  32121. BABYLON.Tools.Error(e.name);
  32122. });
  32123. }
  32124. };
  32125. return VideoTexture;
  32126. }(BABYLON.Texture));
  32127. BABYLON.VideoTexture = VideoTexture;
  32128. })(BABYLON || (BABYLON = {}));
  32129. //# sourceMappingURL=babylon.videoTexture.js.map
  32130. var BABYLON;
  32131. (function (BABYLON) {
  32132. var RawTexture = (function (_super) {
  32133. __extends(RawTexture, _super);
  32134. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32136. if (invertY === void 0) { invertY = false; }
  32137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32138. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32139. _this.format = format;
  32140. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32141. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32142. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32143. return _this;
  32144. }
  32145. RawTexture.prototype.update = function (data) {
  32146. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32147. };
  32148. // Statics
  32149. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32150. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32151. if (invertY === void 0) { invertY = false; }
  32152. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32153. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32154. };
  32155. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32156. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32157. if (invertY === void 0) { invertY = false; }
  32158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32159. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32160. };
  32161. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32162. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32163. if (invertY === void 0) { invertY = false; }
  32164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32165. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32166. };
  32167. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32169. if (invertY === void 0) { invertY = false; }
  32170. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32171. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32172. };
  32173. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32174. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32175. if (invertY === void 0) { invertY = false; }
  32176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32177. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32178. };
  32179. return RawTexture;
  32180. }(BABYLON.Texture));
  32181. BABYLON.RawTexture = RawTexture;
  32182. })(BABYLON || (BABYLON = {}));
  32183. //# sourceMappingURL=babylon.rawTexture.js.map
  32184. var BABYLON;
  32185. (function (BABYLON) {
  32186. var Internals;
  32187. (function (Internals) {
  32188. /*
  32189. * Based on jsTGALoader - Javascript loader for TGA file
  32190. * By Vincent Thibault
  32191. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  32192. */
  32193. var TGATools = (function () {
  32194. function TGATools() {
  32195. }
  32196. TGATools.GetTGAHeader = function (data) {
  32197. var offset = 0;
  32198. var header = {
  32199. id_length: data[offset++],
  32200. colormap_type: data[offset++],
  32201. image_type: data[offset++],
  32202. colormap_index: data[offset++] | data[offset++] << 8,
  32203. colormap_length: data[offset++] | data[offset++] << 8,
  32204. colormap_size: data[offset++],
  32205. origin: [
  32206. data[offset++] | data[offset++] << 8,
  32207. data[offset++] | data[offset++] << 8
  32208. ],
  32209. width: data[offset++] | data[offset++] << 8,
  32210. height: data[offset++] | data[offset++] << 8,
  32211. pixel_size: data[offset++],
  32212. flags: data[offset++]
  32213. };
  32214. return header;
  32215. };
  32216. TGATools.UploadContent = function (gl, data) {
  32217. // Not enough data to contain header ?
  32218. if (data.length < 19) {
  32219. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  32220. return;
  32221. }
  32222. // Read Header
  32223. var offset = 18;
  32224. var header = TGATools.GetTGAHeader(data);
  32225. // Assume it's a valid Targa file.
  32226. if (header.id_length + offset > data.length) {
  32227. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  32228. return;
  32229. }
  32230. // Skip not needed data
  32231. offset += header.id_length;
  32232. var use_rle = false;
  32233. var use_pal = false;
  32234. var use_rgb = false;
  32235. var use_grey = false;
  32236. // Get some informations.
  32237. switch (header.image_type) {
  32238. case TGATools._TYPE_RLE_INDEXED:
  32239. use_rle = true;
  32240. case TGATools._TYPE_INDEXED:
  32241. use_pal = true;
  32242. break;
  32243. case TGATools._TYPE_RLE_RGB:
  32244. use_rle = true;
  32245. case TGATools._TYPE_RGB:
  32246. use_rgb = true;
  32247. break;
  32248. case TGATools._TYPE_RLE_GREY:
  32249. use_rle = true;
  32250. case TGATools._TYPE_GREY:
  32251. use_grey = true;
  32252. break;
  32253. }
  32254. var pixel_data;
  32255. var numAlphaBits = header.flags & 0xf;
  32256. var pixel_size = header.pixel_size >> 3;
  32257. var pixel_total = header.width * header.height * pixel_size;
  32258. // Read palettes
  32259. var palettes;
  32260. if (use_pal) {
  32261. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32262. }
  32263. // Read LRE
  32264. if (use_rle) {
  32265. pixel_data = new Uint8Array(pixel_total);
  32266. var c, count, i;
  32267. var localOffset = 0;
  32268. var pixels = new Uint8Array(pixel_size);
  32269. while (offset < pixel_total && localOffset < pixel_total) {
  32270. c = data[offset++];
  32271. count = (c & 0x7f) + 1;
  32272. // RLE pixels
  32273. if (c & 0x80) {
  32274. // Bind pixel tmp array
  32275. for (i = 0; i < pixel_size; ++i) {
  32276. pixels[i] = data[offset++];
  32277. }
  32278. // Copy pixel array
  32279. for (i = 0; i < count; ++i) {
  32280. pixel_data.set(pixels, localOffset + i * pixel_size);
  32281. }
  32282. localOffset += pixel_size * count;
  32283. }
  32284. else {
  32285. count *= pixel_size;
  32286. for (i = 0; i < count; ++i) {
  32287. pixel_data[localOffset + i] = data[offset++];
  32288. }
  32289. localOffset += count;
  32290. }
  32291. }
  32292. }
  32293. else {
  32294. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32295. }
  32296. // Load to texture
  32297. var x_start, y_start, x_step, y_step, y_end, x_end;
  32298. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32299. default:
  32300. case TGATools._ORIGIN_UL:
  32301. x_start = 0;
  32302. x_step = 1;
  32303. x_end = header.width;
  32304. y_start = 0;
  32305. y_step = 1;
  32306. y_end = header.height;
  32307. break;
  32308. case TGATools._ORIGIN_BL:
  32309. x_start = 0;
  32310. x_step = 1;
  32311. x_end = header.width;
  32312. y_start = header.height - 1;
  32313. y_step = -1;
  32314. y_end = -1;
  32315. break;
  32316. case TGATools._ORIGIN_UR:
  32317. x_start = header.width - 1;
  32318. x_step = -1;
  32319. x_end = -1;
  32320. y_start = 0;
  32321. y_step = 1;
  32322. y_end = header.height;
  32323. break;
  32324. case TGATools._ORIGIN_BR:
  32325. x_start = header.width - 1;
  32326. x_step = -1;
  32327. x_end = -1;
  32328. y_start = header.height - 1;
  32329. y_step = -1;
  32330. y_end = -1;
  32331. break;
  32332. }
  32333. // Load the specify method
  32334. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32335. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32336. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32337. };
  32338. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32339. var image = pixel_data, colormap = palettes;
  32340. var width = header.width, height = header.height;
  32341. var color, i = 0, x, y;
  32342. var imageData = new Uint8Array(width * height * 4);
  32343. for (y = y_start; y !== y_end; y += y_step) {
  32344. for (x = x_start; x !== x_end; x += x_step, i++) {
  32345. color = image[i];
  32346. imageData[(x + width * y) * 4 + 3] = 255;
  32347. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32348. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32349. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32350. }
  32351. }
  32352. return imageData;
  32353. };
  32354. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32355. var image = pixel_data;
  32356. var width = header.width, height = header.height;
  32357. var color, i = 0, x, y;
  32358. var imageData = new Uint8Array(width * height * 4);
  32359. for (y = y_start; y !== y_end; y += y_step) {
  32360. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32361. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32362. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32363. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32364. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32365. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32366. }
  32367. }
  32368. return imageData;
  32369. };
  32370. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32371. var image = pixel_data;
  32372. var width = header.width, height = header.height;
  32373. var i = 0, x, y;
  32374. var imageData = new Uint8Array(width * height * 4);
  32375. for (y = y_start; y !== y_end; y += y_step) {
  32376. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32377. imageData[(x + width * y) * 4 + 3] = 255;
  32378. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32379. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32380. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32381. }
  32382. }
  32383. return imageData;
  32384. };
  32385. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32386. var image = pixel_data;
  32387. var width = header.width, height = header.height;
  32388. var i = 0, x, y;
  32389. var imageData = new Uint8Array(width * height * 4);
  32390. for (y = y_start; y !== y_end; y += y_step) {
  32391. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32392. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32393. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32394. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32395. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32396. }
  32397. }
  32398. return imageData;
  32399. };
  32400. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32401. var image = pixel_data;
  32402. var width = header.width, height = header.height;
  32403. var color, i = 0, x, y;
  32404. var imageData = new Uint8Array(width * height * 4);
  32405. for (y = y_start; y !== y_end; y += y_step) {
  32406. for (x = x_start; x !== x_end; x += x_step, i++) {
  32407. color = image[i];
  32408. imageData[(x + width * y) * 4 + 0] = color;
  32409. imageData[(x + width * y) * 4 + 1] = color;
  32410. imageData[(x + width * y) * 4 + 2] = color;
  32411. imageData[(x + width * y) * 4 + 3] = 255;
  32412. }
  32413. }
  32414. return imageData;
  32415. };
  32416. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32417. var image = pixel_data;
  32418. var width = header.width, height = header.height;
  32419. var i = 0, x, y;
  32420. var imageData = new Uint8Array(width * height * 4);
  32421. for (y = y_start; y !== y_end; y += y_step) {
  32422. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32423. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32424. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32425. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32426. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32427. }
  32428. }
  32429. return imageData;
  32430. };
  32431. return TGATools;
  32432. }());
  32433. TGATools._TYPE_NO_DATA = 0;
  32434. TGATools._TYPE_INDEXED = 1;
  32435. TGATools._TYPE_RGB = 2;
  32436. TGATools._TYPE_GREY = 3;
  32437. TGATools._TYPE_RLE_INDEXED = 9;
  32438. TGATools._TYPE_RLE_RGB = 10;
  32439. TGATools._TYPE_RLE_GREY = 11;
  32440. TGATools._ORIGIN_MASK = 0x30;
  32441. TGATools._ORIGIN_SHIFT = 0x04;
  32442. TGATools._ORIGIN_BL = 0x00;
  32443. TGATools._ORIGIN_BR = 0x01;
  32444. TGATools._ORIGIN_UL = 0x02;
  32445. TGATools._ORIGIN_UR = 0x03;
  32446. Internals.TGATools = TGATools;
  32447. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32448. })(BABYLON || (BABYLON = {}));
  32449. //# sourceMappingURL=babylon.tga.js.map
  32450. var BABYLON;
  32451. (function (BABYLON) {
  32452. var Internals;
  32453. (function (Internals) {
  32454. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32455. // All values and structures referenced from:
  32456. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32457. var DDS_MAGIC = 0x20534444;
  32458. 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;
  32459. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32460. 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;
  32461. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32462. function FourCCToInt32(value) {
  32463. return value.charCodeAt(0) +
  32464. (value.charCodeAt(1) << 8) +
  32465. (value.charCodeAt(2) << 16) +
  32466. (value.charCodeAt(3) << 24);
  32467. }
  32468. function Int32ToFourCC(value) {
  32469. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32470. }
  32471. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32472. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32473. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32474. var headerLengthInt = 31; // The header length in 32 bit ints
  32475. // Offsets into the header array
  32476. var off_magic = 0;
  32477. var off_size = 1;
  32478. var off_flags = 2;
  32479. var off_height = 3;
  32480. var off_width = 4;
  32481. var off_mipmapCount = 7;
  32482. var off_pfFlags = 20;
  32483. var off_pfFourCC = 21;
  32484. var off_RGBbpp = 22;
  32485. var off_RMask = 23;
  32486. var off_GMask = 24;
  32487. var off_BMask = 25;
  32488. var off_AMask = 26;
  32489. var off_caps1 = 27;
  32490. var off_caps2 = 28;
  32491. ;
  32492. var DDSTools = (function () {
  32493. function DDSTools() {
  32494. }
  32495. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32496. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32497. var mipmapCount = 1;
  32498. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32499. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32500. }
  32501. return {
  32502. width: header[off_width],
  32503. height: header[off_height],
  32504. mipmapCount: mipmapCount,
  32505. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32506. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32507. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32508. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32509. };
  32510. };
  32511. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32512. var byteArray = new Uint8Array(dataLength);
  32513. var srcData = new Uint8Array(arrayBuffer);
  32514. var index = 0;
  32515. for (var y = height - 1; y >= 0; y--) {
  32516. for (var x = 0; x < width; x++) {
  32517. var srcPos = dataOffset + (x + y * width) * 4;
  32518. byteArray[index + 2] = srcData[srcPos];
  32519. byteArray[index + 1] = srcData[srcPos + 1];
  32520. byteArray[index] = srcData[srcPos + 2];
  32521. byteArray[index + 3] = srcData[srcPos + 3];
  32522. index += 4;
  32523. }
  32524. }
  32525. return byteArray;
  32526. };
  32527. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32528. var byteArray = new Uint8Array(dataLength);
  32529. var srcData = new Uint8Array(arrayBuffer);
  32530. var index = 0;
  32531. for (var y = height - 1; y >= 0; y--) {
  32532. for (var x = 0; x < width; x++) {
  32533. var srcPos = dataOffset + (x + y * width) * 3;
  32534. byteArray[index + 2] = srcData[srcPos];
  32535. byteArray[index + 1] = srcData[srcPos + 1];
  32536. byteArray[index] = srcData[srcPos + 2];
  32537. index += 3;
  32538. }
  32539. }
  32540. return byteArray;
  32541. };
  32542. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32543. var byteArray = new Uint8Array(dataLength);
  32544. var srcData = new Uint8Array(arrayBuffer);
  32545. var index = 0;
  32546. for (var y = height - 1; y >= 0; y--) {
  32547. for (var x = 0; x < width; x++) {
  32548. var srcPos = dataOffset + (x + y * width);
  32549. byteArray[index] = srcData[srcPos];
  32550. index++;
  32551. }
  32552. }
  32553. return byteArray;
  32554. };
  32555. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32556. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32557. if (header[off_magic] != DDS_MAGIC) {
  32558. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32559. return;
  32560. }
  32561. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32562. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32563. return;
  32564. }
  32565. if (info.isFourCC) {
  32566. fourCC = header[off_pfFourCC];
  32567. switch (fourCC) {
  32568. case FOURCC_DXT1:
  32569. blockBytes = 8;
  32570. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32571. break;
  32572. case FOURCC_DXT3:
  32573. blockBytes = 16;
  32574. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32575. break;
  32576. case FOURCC_DXT5:
  32577. blockBytes = 16;
  32578. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32579. break;
  32580. default:
  32581. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32582. return;
  32583. }
  32584. }
  32585. mipmapCount = 1;
  32586. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32587. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32588. }
  32589. var bpp = header[off_RGBbpp];
  32590. for (var face = 0; face < faces; face++) {
  32591. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32592. width = header[off_width];
  32593. height = header[off_height];
  32594. dataOffset = header[off_size] + 4;
  32595. for (i = 0; i < mipmapCount; ++i) {
  32596. if (info.isRGB) {
  32597. if (bpp === 24) {
  32598. dataLength = width * height * 3;
  32599. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32600. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32601. }
  32602. else {
  32603. dataLength = width * height * 4;
  32604. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32605. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32606. }
  32607. }
  32608. else if (info.isLuminance) {
  32609. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32610. var unpaddedRowSize = width;
  32611. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32612. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32613. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32614. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32615. }
  32616. else {
  32617. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32618. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32619. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32620. }
  32621. dataOffset += dataLength;
  32622. width *= 0.5;
  32623. height *= 0.5;
  32624. width = Math.max(1.0, width);
  32625. height = Math.max(1.0, height);
  32626. }
  32627. }
  32628. };
  32629. return DDSTools;
  32630. }());
  32631. Internals.DDSTools = DDSTools;
  32632. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32633. })(BABYLON || (BABYLON = {}));
  32634. //# sourceMappingURL=babylon.dds.js.map
  32635. var BABYLON;
  32636. (function (BABYLON) {
  32637. var Internals;
  32638. (function (Internals) {
  32639. /**
  32640. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  32641. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  32642. */
  32643. var KhronosTextureContainer = (function () {
  32644. /**
  32645. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  32646. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  32647. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  32648. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  32649. */
  32650. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  32651. this.arrayBuffer = arrayBuffer;
  32652. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  32653. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  32654. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  32655. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  32656. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  32657. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  32658. BABYLON.Tools.Error("texture missing KTX identifier");
  32659. return;
  32660. }
  32661. // load the reset of the header in native 32 bit int
  32662. var header = new Int32Array(this.arrayBuffer, 12, 13);
  32663. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  32664. var oppositeEndianess = header[0] === 0x01020304;
  32665. // read all the header elements in order they exist in the file, without modification (sans endainness)
  32666. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  32667. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  32668. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  32669. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  32670. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  32671. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  32672. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  32673. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  32674. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  32675. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  32676. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  32677. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  32678. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  32679. if (this.glType !== 0) {
  32680. BABYLON.Tools.Error("only compressed formats currently supported");
  32681. return;
  32682. }
  32683. else {
  32684. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  32685. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  32686. }
  32687. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  32688. BABYLON.Tools.Error("only 2D textures currently supported");
  32689. return;
  32690. }
  32691. if (this.numberOfArrayElements !== 0) {
  32692. BABYLON.Tools.Error("texture arrays not currently supported");
  32693. return;
  32694. }
  32695. if (this.numberOfFaces !== facesExpected) {
  32696. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  32697. return;
  32698. }
  32699. // we now have a completely validated file, so could use existence of loadType as success
  32700. // would need to make this more elaborate & adjust checks above to support more than one load type
  32701. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  32702. }
  32703. // not as fast hardware based, but will probably never need to use
  32704. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  32705. return ((val & 0xFF) << 24)
  32706. | ((val & 0xFF00) << 8)
  32707. | ((val >> 8) & 0xFF00)
  32708. | ((val >> 24) & 0xFF);
  32709. };
  32710. /**
  32711. * It is assumed that the texture has already been created & is currently bound
  32712. */
  32713. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  32714. switch (this.loadType) {
  32715. case KhronosTextureContainer.COMPRESSED_2D:
  32716. this._upload2DCompressedLevels(gl, loadMipmaps);
  32717. break;
  32718. case KhronosTextureContainer.TEX_2D:
  32719. case KhronosTextureContainer.COMPRESSED_3D:
  32720. case KhronosTextureContainer.TEX_3D:
  32721. }
  32722. };
  32723. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  32724. // initialize width & height for level 1
  32725. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  32726. var width = this.pixelWidth;
  32727. var height = this.pixelHeight;
  32728. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  32729. for (var level = 0; level < mipmapCount; level++) {
  32730. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  32731. for (var face = 0; face < this.numberOfFaces; face++) {
  32732. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32733. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  32734. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  32735. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  32736. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  32737. }
  32738. width = Math.max(1.0, width * 0.5);
  32739. height = Math.max(1.0, height * 0.5);
  32740. }
  32741. };
  32742. return KhronosTextureContainer;
  32743. }());
  32744. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  32745. // load types
  32746. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  32747. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  32748. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  32749. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  32750. Internals.KhronosTextureContainer = KhronosTextureContainer;
  32751. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32752. })(BABYLON || (BABYLON = {}));
  32753. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  32754. var BABYLON;
  32755. (function (BABYLON) {
  32756. var PostProcess = (function () {
  32757. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  32758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32759. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32760. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  32761. if (blockCompilation === void 0) { blockCompilation = false; }
  32762. this.name = name;
  32763. this.width = -1;
  32764. this.height = -1;
  32765. this.autoClear = true;
  32766. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  32767. /*
  32768. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32769. Can only be used on a single postprocess or on the last one of a chain.
  32770. */
  32771. this.enablePixelPerfectMode = false;
  32772. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  32773. this.alwaysForcePOT = false;
  32774. this.samples = 1;
  32775. this._reusable = false;
  32776. this._textures = new BABYLON.SmartArray(2);
  32777. this._currentRenderTextureInd = 0;
  32778. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32779. this._texelSize = BABYLON.Vector2.Zero();
  32780. // Events
  32781. /**
  32782. * An event triggered when the postprocess is activated.
  32783. * @type {BABYLON.Observable}
  32784. */
  32785. this.onActivateObservable = new BABYLON.Observable();
  32786. /**
  32787. * An event triggered when the postprocess changes its size.
  32788. * @type {BABYLON.Observable}
  32789. */
  32790. this.onSizeChangedObservable = new BABYLON.Observable();
  32791. /**
  32792. * An event triggered when the postprocess applies its effect.
  32793. * @type {BABYLON.Observable}
  32794. */
  32795. this.onApplyObservable = new BABYLON.Observable();
  32796. /**
  32797. * An event triggered before rendering the postprocess
  32798. * @type {BABYLON.Observable}
  32799. */
  32800. this.onBeforeRenderObservable = new BABYLON.Observable();
  32801. /**
  32802. * An event triggered after rendering the postprocess
  32803. * @type {BABYLON.Observable}
  32804. */
  32805. this.onAfterRenderObservable = new BABYLON.Observable();
  32806. if (camera != null) {
  32807. this._camera = camera;
  32808. this._scene = camera.getScene();
  32809. camera.attachPostProcess(this);
  32810. this._engine = this._scene.getEngine();
  32811. }
  32812. else {
  32813. this._engine = engine;
  32814. }
  32815. this._options = options;
  32816. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32817. this._reusable = reusable || false;
  32818. this._textureType = textureType;
  32819. this._samplers = samplers || [];
  32820. this._samplers.push("textureSampler");
  32821. this._fragmentUrl = fragmentUrl;
  32822. this._vertexUrl = vertexUrl;
  32823. this._parameters = parameters || [];
  32824. this._parameters.push("scale");
  32825. this._indexParameters = indexParameters;
  32826. if (!blockCompilation) {
  32827. this.updateEffect(defines);
  32828. }
  32829. }
  32830. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32831. set: function (callback) {
  32832. if (this._onActivateObserver) {
  32833. this.onActivateObservable.remove(this._onActivateObserver);
  32834. }
  32835. this._onActivateObserver = this.onActivateObservable.add(callback);
  32836. },
  32837. enumerable: true,
  32838. configurable: true
  32839. });
  32840. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32841. set: function (callback) {
  32842. if (this._onSizeChangedObserver) {
  32843. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32844. }
  32845. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32846. },
  32847. enumerable: true,
  32848. configurable: true
  32849. });
  32850. Object.defineProperty(PostProcess.prototype, "onApply", {
  32851. set: function (callback) {
  32852. if (this._onApplyObserver) {
  32853. this.onApplyObservable.remove(this._onApplyObserver);
  32854. }
  32855. this._onApplyObserver = this.onApplyObservable.add(callback);
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32861. set: function (callback) {
  32862. if (this._onBeforeRenderObserver) {
  32863. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32864. }
  32865. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32866. },
  32867. enumerable: true,
  32868. configurable: true
  32869. });
  32870. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32871. set: function (callback) {
  32872. if (this._onAfterRenderObserver) {
  32873. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32874. }
  32875. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  32881. get: function () {
  32882. return this._textures.data[this._currentRenderTextureInd];
  32883. },
  32884. set: function (value) {
  32885. this._forcedOutputTexture = value;
  32886. },
  32887. enumerable: true,
  32888. configurable: true
  32889. });
  32890. PostProcess.prototype.getCamera = function () {
  32891. return this._camera;
  32892. };
  32893. Object.defineProperty(PostProcess.prototype, "texelSize", {
  32894. get: function () {
  32895. if (this._shareOutputWithPostProcess) {
  32896. return this._shareOutputWithPostProcess.texelSize;
  32897. }
  32898. if (this._forcedOutputTexture) {
  32899. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  32900. }
  32901. return this._texelSize;
  32902. },
  32903. enumerable: true,
  32904. configurable: true
  32905. });
  32906. PostProcess.prototype.getEngine = function () {
  32907. return this._engine;
  32908. };
  32909. PostProcess.prototype.getEffect = function () {
  32910. return this._effect;
  32911. };
  32912. PostProcess.prototype.shareOutputWith = function (postProcess) {
  32913. this._disposeTextures();
  32914. this._shareOutputWithPostProcess = postProcess;
  32915. return this;
  32916. };
  32917. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  32918. 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);
  32919. };
  32920. PostProcess.prototype.isReusable = function () {
  32921. return this._reusable;
  32922. };
  32923. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32924. PostProcess.prototype.markTextureDirty = function () {
  32925. this.width = -1;
  32926. };
  32927. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  32928. var _this = this;
  32929. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  32930. camera = camera || this._camera;
  32931. var scene = camera.getScene();
  32932. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32933. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32934. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32935. var desiredWidth = this._options.width || requiredWidth;
  32936. var desiredHeight = this._options.height || requiredHeight;
  32937. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  32938. if (!this._options.width) {
  32939. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  32940. }
  32941. if (!this._options.height) {
  32942. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  32943. }
  32944. }
  32945. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32946. if (this._textures.length > 0) {
  32947. for (var i = 0; i < this._textures.length; i++) {
  32948. this._engine._releaseTexture(this._textures.data[i]);
  32949. }
  32950. this._textures.reset();
  32951. }
  32952. this.width = desiredWidth;
  32953. this.height = desiredHeight;
  32954. var textureSize = { width: this.width, height: this.height };
  32955. var textureOptions = {
  32956. generateMipMaps: false,
  32957. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  32958. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  32959. samplingMode: this.renderTargetSamplingMode,
  32960. type: this._textureType
  32961. };
  32962. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32963. if (this._reusable) {
  32964. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32965. }
  32966. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  32967. this.onSizeChangedObservable.notifyObservers(this);
  32968. }
  32969. this._textures.forEach(function (texture) {
  32970. if (texture.samples !== _this.samples) {
  32971. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  32972. }
  32973. });
  32974. }
  32975. var target;
  32976. if (this._shareOutputWithPostProcess) {
  32977. target = this._shareOutputWithPostProcess.outputTexture;
  32978. }
  32979. else if (this._forcedOutputTexture) {
  32980. target = this._forcedOutputTexture;
  32981. this.width = this._forcedOutputTexture._width;
  32982. this.height = this._forcedOutputTexture._height;
  32983. }
  32984. else {
  32985. target = this.outputTexture;
  32986. }
  32987. if (this.enablePixelPerfectMode) {
  32988. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32989. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  32990. }
  32991. else {
  32992. this._scaleRatio.copyFromFloats(1, 1);
  32993. this._engine.bindFramebuffer(target);
  32994. }
  32995. this.onActivateObservable.notifyObservers(camera);
  32996. // Clear
  32997. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  32998. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  32999. }
  33000. if (this._reusable) {
  33001. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  33002. }
  33003. };
  33004. Object.defineProperty(PostProcess.prototype, "isSupported", {
  33005. get: function () {
  33006. return this._effect.isSupported;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  33012. get: function () {
  33013. if (this._shareOutputWithPostProcess) {
  33014. return this._shareOutputWithPostProcess.aspectRatio;
  33015. }
  33016. if (this._forcedOutputTexture) {
  33017. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  33018. }
  33019. return this.width / this.height;
  33020. },
  33021. enumerable: true,
  33022. configurable: true
  33023. });
  33024. PostProcess.prototype.apply = function () {
  33025. // Check
  33026. if (!this._effect || !this._effect.isReady())
  33027. return null;
  33028. // States
  33029. this._engine.enableEffect(this._effect);
  33030. this._engine.setState(false);
  33031. this._engine.setDepthBuffer(false);
  33032. this._engine.setDepthWrite(false);
  33033. // Alpha
  33034. this._engine.setAlphaMode(this.alphaMode);
  33035. if (this.alphaConstants) {
  33036. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  33037. }
  33038. // Texture
  33039. var source;
  33040. if (this._shareOutputWithPostProcess) {
  33041. source = this._shareOutputWithPostProcess.outputTexture;
  33042. }
  33043. else if (this._forcedOutputTexture) {
  33044. source = this._forcedOutputTexture;
  33045. }
  33046. else {
  33047. source = this.outputTexture;
  33048. }
  33049. this._effect._bindTexture("textureSampler", source);
  33050. // Parameters
  33051. this._effect.setVector2("scale", this._scaleRatio);
  33052. this.onApplyObservable.notifyObservers(this._effect);
  33053. return this._effect;
  33054. };
  33055. PostProcess.prototype._disposeTextures = function () {
  33056. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  33057. return;
  33058. }
  33059. if (this._textures.length > 0) {
  33060. for (var i = 0; i < this._textures.length; i++) {
  33061. this._engine._releaseTexture(this._textures.data[i]);
  33062. }
  33063. }
  33064. this._textures.dispose();
  33065. };
  33066. PostProcess.prototype.dispose = function (camera) {
  33067. camera = camera || this._camera;
  33068. this._disposeTextures();
  33069. if (!camera) {
  33070. return;
  33071. }
  33072. camera.detachPostProcess(this);
  33073. var index = camera._postProcesses.indexOf(this);
  33074. if (index === 0 && camera._postProcesses.length > 0) {
  33075. this._camera._postProcesses[0].markTextureDirty();
  33076. }
  33077. this.onActivateObservable.clear();
  33078. this.onAfterRenderObservable.clear();
  33079. this.onApplyObservable.clear();
  33080. this.onBeforeRenderObservable.clear();
  33081. this.onSizeChangedObservable.clear();
  33082. };
  33083. return PostProcess;
  33084. }());
  33085. BABYLON.PostProcess = PostProcess;
  33086. })(BABYLON || (BABYLON = {}));
  33087. //# sourceMappingURL=babylon.postProcess.js.map
  33088. var BABYLON;
  33089. (function (BABYLON) {
  33090. var PassPostProcess = (function (_super) {
  33091. __extends(PassPostProcess, _super);
  33092. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  33093. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33094. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  33095. }
  33096. return PassPostProcess;
  33097. }(BABYLON.PostProcess));
  33098. BABYLON.PassPostProcess = PassPostProcess;
  33099. })(BABYLON || (BABYLON = {}));
  33100. //# sourceMappingURL=babylon.passPostProcess.js.map
  33101. var BABYLON;
  33102. (function (BABYLON) {
  33103. var ShadowGenerator = (function () {
  33104. /**
  33105. * Creates a ShadowGenerator object.
  33106. * A ShadowGenerator is the required tool to use the shadows.
  33107. * Each light casting shadows needs to use its own ShadowGenerator.
  33108. * Required parameters :
  33109. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  33110. * - `light`: the light object generating the shadows.
  33111. * - `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.
  33112. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  33113. */
  33114. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  33115. // Members
  33116. this._bias = 0.00005;
  33117. this._blurBoxOffset = 1;
  33118. this._blurScale = 2;
  33119. this._blurKernel = 1;
  33120. this._useKernelBlur = false;
  33121. this._filter = ShadowGenerator.FILTER_NONE;
  33122. this._darkness = 0;
  33123. this._transparencyShadow = false;
  33124. this.forceBackFacesOnly = false;
  33125. this._lightDirection = BABYLON.Vector3.Zero();
  33126. this._viewMatrix = BABYLON.Matrix.Zero();
  33127. this._projectionMatrix = BABYLON.Matrix.Zero();
  33128. this._transformMatrix = BABYLON.Matrix.Zero();
  33129. this._worldViewProjection = BABYLON.Matrix.Zero();
  33130. this._currentFaceIndex = 0;
  33131. this._currentFaceIndexCache = 0;
  33132. this._isCube = false;
  33133. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  33134. this._mapSize = mapSize;
  33135. this._light = light;
  33136. this._scene = light.getScene();
  33137. light._shadowGenerator = this;
  33138. // Texture type fallback from float to int if not supported.
  33139. var caps = this._scene.getEngine().getCaps();
  33140. if (!useFullFloatFirst) {
  33141. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33142. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33143. }
  33144. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33145. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33146. }
  33147. else {
  33148. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33149. }
  33150. }
  33151. else {
  33152. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33153. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33154. }
  33155. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33156. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33157. }
  33158. else {
  33159. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33160. }
  33161. }
  33162. this._initializeGenerator();
  33163. }
  33164. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  33165. // Static
  33166. get: function () {
  33167. return ShadowGenerator._FILTER_NONE;
  33168. },
  33169. enumerable: true,
  33170. configurable: true
  33171. });
  33172. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  33173. get: function () {
  33174. return ShadowGenerator._FILTER_POISSONSAMPLING;
  33175. },
  33176. enumerable: true,
  33177. configurable: true
  33178. });
  33179. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  33180. get: function () {
  33181. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  33182. },
  33183. enumerable: true,
  33184. configurable: true
  33185. });
  33186. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  33187. get: function () {
  33188. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  33189. },
  33190. enumerable: true,
  33191. configurable: true
  33192. });
  33193. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  33194. get: function () {
  33195. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33196. },
  33197. enumerable: true,
  33198. configurable: true
  33199. });
  33200. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  33201. get: function () {
  33202. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33203. },
  33204. enumerable: true,
  33205. configurable: true
  33206. });
  33207. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  33208. get: function () {
  33209. return this._bias;
  33210. },
  33211. set: function (bias) {
  33212. this._bias = bias;
  33213. },
  33214. enumerable: true,
  33215. configurable: true
  33216. });
  33217. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  33218. get: function () {
  33219. return this._blurBoxOffset;
  33220. },
  33221. set: function (value) {
  33222. if (this._blurBoxOffset === value) {
  33223. return;
  33224. }
  33225. this._blurBoxOffset = value;
  33226. this._disposeBlurPostProcesses();
  33227. },
  33228. enumerable: true,
  33229. configurable: true
  33230. });
  33231. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  33232. get: function () {
  33233. return this._blurScale;
  33234. },
  33235. set: function (value) {
  33236. if (this._blurScale === value) {
  33237. return;
  33238. }
  33239. this._blurScale = value;
  33240. this._disposeBlurPostProcesses();
  33241. },
  33242. enumerable: true,
  33243. configurable: true
  33244. });
  33245. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  33246. get: function () {
  33247. return this._blurKernel;
  33248. },
  33249. set: function (value) {
  33250. if (this._blurKernel === value) {
  33251. return;
  33252. }
  33253. this._blurKernel = value;
  33254. this._disposeBlurPostProcesses();
  33255. },
  33256. enumerable: true,
  33257. configurable: true
  33258. });
  33259. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33260. get: function () {
  33261. return this._useKernelBlur;
  33262. },
  33263. set: function (value) {
  33264. if (this._useKernelBlur === value) {
  33265. return;
  33266. }
  33267. this._useKernelBlur = value;
  33268. this._disposeBlurPostProcesses();
  33269. },
  33270. enumerable: true,
  33271. configurable: true
  33272. });
  33273. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33274. get: function () {
  33275. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33276. },
  33277. set: function (value) {
  33278. this._depthScale = value;
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33284. get: function () {
  33285. return this._filter;
  33286. },
  33287. set: function (value) {
  33288. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33289. if (this._light.needCube()) {
  33290. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33291. this.useExponentialShadowMap = true;
  33292. return;
  33293. }
  33294. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33295. this.useCloseExponentialShadowMap = true;
  33296. return;
  33297. }
  33298. }
  33299. if (this._filter === value) {
  33300. return;
  33301. }
  33302. this._filter = value;
  33303. this._disposeBlurPostProcesses();
  33304. this._applyFilterValues();
  33305. this._light._markMeshesAsLightDirty();
  33306. },
  33307. enumerable: true,
  33308. configurable: true
  33309. });
  33310. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33311. get: function () {
  33312. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33313. },
  33314. set: function (value) {
  33315. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33316. },
  33317. enumerable: true,
  33318. configurable: true
  33319. });
  33320. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33321. get: function () {
  33322. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33323. return this.useExponentialShadowMap;
  33324. },
  33325. set: function (value) {
  33326. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33327. this.useExponentialShadowMap = value;
  33328. },
  33329. enumerable: true,
  33330. configurable: true
  33331. });
  33332. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33333. get: function () {
  33334. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33335. return this.useBlurExponentialShadowMap;
  33336. },
  33337. set: function (value) {
  33338. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33339. this.useBlurExponentialShadowMap = value;
  33340. },
  33341. enumerable: true,
  33342. configurable: true
  33343. });
  33344. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33345. get: function () {
  33346. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33347. },
  33348. set: function (value) {
  33349. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33350. },
  33351. enumerable: true,
  33352. configurable: true
  33353. });
  33354. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33355. get: function () {
  33356. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33357. },
  33358. set: function (value) {
  33359. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33360. },
  33361. enumerable: true,
  33362. configurable: true
  33363. });
  33364. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33365. get: function () {
  33366. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33367. },
  33368. set: function (value) {
  33369. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33370. },
  33371. enumerable: true,
  33372. configurable: true
  33373. });
  33374. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33375. get: function () {
  33376. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33377. },
  33378. set: function (value) {
  33379. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33380. },
  33381. enumerable: true,
  33382. configurable: true
  33383. });
  33384. /**
  33385. * Returns the darkness value (float).
  33386. */
  33387. ShadowGenerator.prototype.getDarkness = function () {
  33388. return this._darkness;
  33389. };
  33390. /**
  33391. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33392. * Returns the ShadowGenerator.
  33393. */
  33394. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33395. if (darkness >= 1.0)
  33396. this._darkness = 1.0;
  33397. else if (darkness <= 0.0)
  33398. this._darkness = 0.0;
  33399. else
  33400. this._darkness = darkness;
  33401. return this;
  33402. };
  33403. /**
  33404. * Sets the ability to have transparent shadow (boolean).
  33405. * Returns the ShadowGenerator.
  33406. */
  33407. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33408. this._transparencyShadow = hasShadow;
  33409. return this;
  33410. };
  33411. /**
  33412. * Returns a RenderTargetTexture object : the shadow map texture.
  33413. */
  33414. ShadowGenerator.prototype.getShadowMap = function () {
  33415. return this._shadowMap;
  33416. };
  33417. /**
  33418. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33419. */
  33420. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33421. if (this._shadowMap2) {
  33422. return this._shadowMap2;
  33423. }
  33424. return this._shadowMap;
  33425. };
  33426. /**
  33427. * Returns the associated light object.
  33428. */
  33429. ShadowGenerator.prototype.getLight = function () {
  33430. return this._light;
  33431. };
  33432. ShadowGenerator.prototype._initializeGenerator = function () {
  33433. this._light._markMeshesAsLightDirty();
  33434. this._initializeShadowMap();
  33435. };
  33436. ShadowGenerator.prototype._initializeShadowMap = function () {
  33437. var _this = this;
  33438. // Render target
  33439. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33440. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33441. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33442. this._shadowMap.anisotropicFilteringLevel = 1;
  33443. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33444. this._shadowMap.renderParticles = false;
  33445. // Record Face Index before render.
  33446. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33447. _this._currentFaceIndex = faceIndex;
  33448. });
  33449. // Custom render function.
  33450. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33451. // Blur if required afer render.
  33452. this._shadowMap.onAfterUnbindObservable.add(function () {
  33453. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33454. return;
  33455. }
  33456. if (!_this._blurPostProcesses) {
  33457. _this._initializeBlurRTTAndPostProcesses();
  33458. }
  33459. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33460. });
  33461. // Clear according to the chosen filter.
  33462. this._shadowMap.onClearObservable.add(function (engine) {
  33463. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33464. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33465. }
  33466. else {
  33467. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33468. }
  33469. });
  33470. };
  33471. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33472. var _this = this;
  33473. var engine = this._scene.getEngine();
  33474. var targetSize = this._mapSize / this.blurScale;
  33475. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33476. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33477. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33478. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33479. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33480. }
  33481. if (this.useKernelBlur) {
  33482. 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);
  33483. this._kernelBlurXPostprocess.width = targetSize;
  33484. this._kernelBlurXPostprocess.height = targetSize;
  33485. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33486. effect.setTexture("textureSampler", _this._shadowMap);
  33487. });
  33488. 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);
  33489. this._kernelBlurXPostprocess.autoClear = false;
  33490. this._kernelBlurYPostprocess.autoClear = false;
  33491. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33492. this._kernelBlurXPostprocess.packedFloat = true;
  33493. this._kernelBlurYPostprocess.packedFloat = true;
  33494. }
  33495. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33496. }
  33497. else {
  33498. 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);
  33499. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33500. effect.setFloat2("screenSize", targetSize, targetSize);
  33501. effect.setTexture("textureSampler", _this._shadowMap);
  33502. });
  33503. this._boxBlurPostprocess.autoClear = false;
  33504. this._blurPostProcesses = [this._boxBlurPostprocess];
  33505. }
  33506. };
  33507. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33508. var index;
  33509. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33510. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33511. }
  33512. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33513. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33514. }
  33515. if (this._transparencyShadow) {
  33516. for (index = 0; index < transparentSubMeshes.length; index++) {
  33517. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33518. }
  33519. }
  33520. };
  33521. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  33522. var _this = this;
  33523. var mesh = subMesh.getRenderingMesh();
  33524. var scene = this._scene;
  33525. var engine = scene.getEngine();
  33526. // Culling
  33527. engine.setState(subMesh.getMaterial().backFaceCulling);
  33528. // Managing instances
  33529. var batch = mesh._getInstancesRenderList(subMesh._id);
  33530. if (batch.mustReturn) {
  33531. return;
  33532. }
  33533. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33534. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  33535. engine.enableEffect(this._effect);
  33536. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33537. var material = subMesh.getMaterial();
  33538. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  33539. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  33540. this._effect.setVector3("lightPosition", this.getLight().position);
  33541. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  33542. // Alpha test
  33543. if (material && material.needAlphaTesting()) {
  33544. var alphaTexture = material.getAlphaTestTexture();
  33545. if (alphaTexture) {
  33546. this._effect.setTexture("diffuseSampler", alphaTexture);
  33547. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  33548. }
  33549. }
  33550. // Bones
  33551. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33552. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33553. }
  33554. if (this.forceBackFacesOnly) {
  33555. engine.setState(true, 0, false, true);
  33556. }
  33557. // Draw
  33558. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33559. if (this.forceBackFacesOnly) {
  33560. engine.setState(true, 0, false, false);
  33561. }
  33562. }
  33563. else {
  33564. // Need to reset refresh rate of the shadowMap
  33565. this._shadowMap.resetRefreshCounter();
  33566. }
  33567. };
  33568. ShadowGenerator.prototype._applyFilterValues = function () {
  33569. if (this.filter === ShadowGenerator.FILTER_NONE) {
  33570. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  33571. }
  33572. else {
  33573. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33574. }
  33575. };
  33576. /**
  33577. * Boolean : true when the ShadowGenerator is finally computed.
  33578. */
  33579. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  33580. var defines = [];
  33581. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33582. defines.push("#define FLOAT");
  33583. }
  33584. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33585. defines.push("#define ESM");
  33586. }
  33587. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33588. var mesh = subMesh.getMesh();
  33589. var material = subMesh.getMaterial();
  33590. // Alpha test
  33591. if (material && material.needAlphaTesting()) {
  33592. var alphaTexture = material.getAlphaTestTexture();
  33593. if (alphaTexture) {
  33594. defines.push("#define ALPHATEST");
  33595. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33596. attribs.push(BABYLON.VertexBuffer.UVKind);
  33597. defines.push("#define UV1");
  33598. }
  33599. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33600. if (alphaTexture.coordinatesIndex === 1) {
  33601. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33602. defines.push("#define UV2");
  33603. }
  33604. }
  33605. }
  33606. }
  33607. // Bones
  33608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33611. if (mesh.numBoneInfluencers > 4) {
  33612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33614. }
  33615. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33616. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33617. }
  33618. else {
  33619. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33620. }
  33621. // Instances
  33622. if (useInstances) {
  33623. defines.push("#define INSTANCES");
  33624. attribs.push("world0");
  33625. attribs.push("world1");
  33626. attribs.push("world2");
  33627. attribs.push("world3");
  33628. }
  33629. // Get correct effect
  33630. var join = defines.join("\n");
  33631. if (this._cachedDefines !== join) {
  33632. this._cachedDefines = join;
  33633. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  33634. }
  33635. return this._effect.isReady();
  33636. };
  33637. /**
  33638. * This creates the defines related to the standard BJS materials.
  33639. */
  33640. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  33641. var scene = this._scene;
  33642. var light = this._light;
  33643. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33644. return;
  33645. }
  33646. defines["SHADOW" + lightIndex] = true;
  33647. if (this.usePoissonSampling) {
  33648. defines["SHADOWPCF" + lightIndex] = true;
  33649. }
  33650. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33651. defines["SHADOWESM" + lightIndex] = true;
  33652. }
  33653. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  33654. defines["SHADOWCLOSEESM" + lightIndex] = true;
  33655. }
  33656. if (light.needCube()) {
  33657. defines["SHADOWCUBE" + lightIndex] = true;
  33658. }
  33659. };
  33660. /**
  33661. * This binds shadow lights related to the standard BJS materials.
  33662. * It implies the unifroms available on the materials are the standard BJS ones.
  33663. */
  33664. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  33665. var light = this._light;
  33666. var scene = this._scene;
  33667. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33668. return;
  33669. }
  33670. if (!light.needCube()) {
  33671. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  33672. }
  33673. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  33674. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  33675. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  33676. };
  33677. // Methods
  33678. /**
  33679. * Returns a Matrix object : the updated transformation matrix.
  33680. */
  33681. ShadowGenerator.prototype.getTransformMatrix = function () {
  33682. var scene = this._scene;
  33683. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  33684. return this._transformMatrix;
  33685. }
  33686. this._currentRenderID = scene.getRenderId();
  33687. this._currentFaceIndexCache = this._currentFaceIndex;
  33688. var lightPosition = this._light.position;
  33689. if (this._light.computeTransformedInformation()) {
  33690. lightPosition = this._light.transformedPosition;
  33691. }
  33692. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  33693. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  33694. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  33695. }
  33696. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  33697. this._cachedPosition = lightPosition.clone();
  33698. this._cachedDirection = this._lightDirection.clone();
  33699. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  33700. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  33701. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  33702. }
  33703. return this._transformMatrix;
  33704. };
  33705. ShadowGenerator.prototype.recreateShadowMap = function () {
  33706. // Track render list.
  33707. var renderList = this._shadowMap.renderList;
  33708. // Clean up existing data.
  33709. this._disposeRTTandPostProcesses();
  33710. // Reinitializes.
  33711. this._initializeGenerator();
  33712. // Reaffect the filter to ensure a correct fallback if necessary.
  33713. this.filter = this.filter;
  33714. // Reaffect the filter.
  33715. this._applyFilterValues();
  33716. // Reaffect Render List.
  33717. this._shadowMap.renderList = renderList;
  33718. };
  33719. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  33720. if (this._shadowMap2) {
  33721. this._shadowMap2.dispose();
  33722. this._shadowMap2 = null;
  33723. }
  33724. if (this._downSamplePostprocess) {
  33725. this._downSamplePostprocess.dispose();
  33726. this._downSamplePostprocess = null;
  33727. }
  33728. if (this._boxBlurPostprocess) {
  33729. this._boxBlurPostprocess.dispose();
  33730. this._boxBlurPostprocess = null;
  33731. }
  33732. if (this._kernelBlurXPostprocess) {
  33733. this._kernelBlurXPostprocess.dispose();
  33734. this._kernelBlurXPostprocess = null;
  33735. }
  33736. if (this._kernelBlurYPostprocess) {
  33737. this._kernelBlurYPostprocess.dispose();
  33738. this._kernelBlurYPostprocess = null;
  33739. }
  33740. this._blurPostProcesses = null;
  33741. };
  33742. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  33743. if (this._shadowMap) {
  33744. this._shadowMap.dispose();
  33745. this._shadowMap = null;
  33746. }
  33747. this._disposeBlurPostProcesses();
  33748. };
  33749. /**
  33750. * Disposes the ShadowGenerator.
  33751. * Returns nothing.
  33752. */
  33753. ShadowGenerator.prototype.dispose = function () {
  33754. this._disposeRTTandPostProcesses();
  33755. this._light._shadowGenerator = null;
  33756. this._light._markMeshesAsLightDirty();
  33757. };
  33758. /**
  33759. * Serializes the ShadowGenerator and returns a serializationObject.
  33760. */
  33761. ShadowGenerator.prototype.serialize = function () {
  33762. var serializationObject = {};
  33763. var shadowMap = this.getShadowMap();
  33764. serializationObject.lightId = this._light.id;
  33765. serializationObject.mapSize = shadowMap.getRenderSize();
  33766. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  33767. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  33768. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33769. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33770. serializationObject.usePoissonSampling = this.usePoissonSampling;
  33771. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  33772. serializationObject.depthScale = this.depthScale;
  33773. serializationObject.darkness = this.getDarkness();
  33774. serializationObject.blurBoxOffset = this.blurBoxOffset;
  33775. serializationObject.blurKernel = this.blurKernel;
  33776. serializationObject.blurScale = this.blurScale;
  33777. serializationObject.useKernelBlur = this.useKernelBlur;
  33778. serializationObject.transparencyShadow = this._transparencyShadow;
  33779. serializationObject.renderList = [];
  33780. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  33781. var mesh = shadowMap.renderList[meshIndex];
  33782. serializationObject.renderList.push(mesh.id);
  33783. }
  33784. return serializationObject;
  33785. };
  33786. /**
  33787. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  33788. */
  33789. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  33790. //casting to point light, as light is missing the position attr and typescript complains.
  33791. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  33792. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  33793. var shadowMap = shadowGenerator.getShadowMap();
  33794. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  33795. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  33796. meshes.forEach(function (mesh) {
  33797. shadowMap.renderList.push(mesh);
  33798. });
  33799. }
  33800. if (parsedShadowGenerator.usePoissonSampling) {
  33801. shadowGenerator.usePoissonSampling = true;
  33802. }
  33803. else if (parsedShadowGenerator.useExponentialShadowMap) {
  33804. shadowGenerator.useExponentialShadowMap = true;
  33805. }
  33806. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33807. shadowGenerator.useBlurExponentialShadowMap = true;
  33808. }
  33809. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  33810. shadowGenerator.useCloseExponentialShadowMap = true;
  33811. }
  33812. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33813. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  33814. }
  33815. else if (parsedShadowGenerator.useVarianceShadowMap) {
  33816. shadowGenerator.useExponentialShadowMap = true;
  33817. }
  33818. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  33819. shadowGenerator.useBlurExponentialShadowMap = true;
  33820. }
  33821. if (parsedShadowGenerator.depthScale) {
  33822. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  33823. }
  33824. if (parsedShadowGenerator.blurScale) {
  33825. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  33826. }
  33827. if (parsedShadowGenerator.blurBoxOffset) {
  33828. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  33829. }
  33830. if (parsedShadowGenerator.useKernelBlur) {
  33831. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  33832. }
  33833. if (parsedShadowGenerator.blurKernel) {
  33834. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  33835. }
  33836. if (parsedShadowGenerator.bias !== undefined) {
  33837. shadowGenerator.bias = parsedShadowGenerator.bias;
  33838. }
  33839. if (parsedShadowGenerator.darkness) {
  33840. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  33841. }
  33842. if (parsedShadowGenerator.transparencyShadow) {
  33843. shadowGenerator.setTransparencyShadow(true);
  33844. }
  33845. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  33846. return shadowGenerator;
  33847. };
  33848. return ShadowGenerator;
  33849. }());
  33850. ShadowGenerator._FILTER_NONE = 0;
  33851. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  33852. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  33853. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  33854. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  33855. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  33856. BABYLON.ShadowGenerator = ShadowGenerator;
  33857. })(BABYLON || (BABYLON = {}));
  33858. //# sourceMappingURL=babylon.shadowGenerator.js.map
  33859. var BABYLON;
  33860. (function (BABYLON) {
  33861. var ShadowLight = (function (_super) {
  33862. __extends(ShadowLight, _super);
  33863. function ShadowLight() {
  33864. var _this = _super !== null && _super.apply(this, arguments) || this;
  33865. _this._needProjectionMatrixCompute = true;
  33866. return _this;
  33867. }
  33868. Object.defineProperty(ShadowLight.prototype, "direction", {
  33869. get: function () {
  33870. return this._direction;
  33871. },
  33872. set: function (value) {
  33873. this._direction = value;
  33874. },
  33875. enumerable: true,
  33876. configurable: true
  33877. });
  33878. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33879. get: function () {
  33880. return this._shadowMinZ;
  33881. },
  33882. set: function (value) {
  33883. this._shadowMinZ = value;
  33884. this.forceProjectionMatrixCompute();
  33885. },
  33886. enumerable: true,
  33887. configurable: true
  33888. });
  33889. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33890. get: function () {
  33891. return this._shadowMaxZ;
  33892. },
  33893. set: function (value) {
  33894. this._shadowMaxZ = value;
  33895. this.forceProjectionMatrixCompute();
  33896. },
  33897. enumerable: true,
  33898. configurable: true
  33899. });
  33900. /**
  33901. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33902. */
  33903. ShadowLight.prototype.computeTransformedInformation = function () {
  33904. if (this.parent && this.parent.getWorldMatrix) {
  33905. if (!this.transformedPosition) {
  33906. this.transformedPosition = BABYLON.Vector3.Zero();
  33907. }
  33908. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33909. // In case the direction is present.
  33910. if (this.direction) {
  33911. if (!this.transformedDirection) {
  33912. this.transformedDirection = BABYLON.Vector3.Zero();
  33913. }
  33914. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33915. }
  33916. return true;
  33917. }
  33918. return false;
  33919. };
  33920. /**
  33921. * Return the depth scale used for the shadow map.
  33922. */
  33923. ShadowLight.prototype.getDepthScale = function () {
  33924. return 50.0;
  33925. };
  33926. /**
  33927. * Returns the light direction (Vector3) for any passed face index.
  33928. */
  33929. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33930. return this.transformedDirection ? this.transformedDirection : this.direction;
  33931. };
  33932. /**
  33933. * Returns the DirectionalLight absolute position in the World.
  33934. */
  33935. ShadowLight.prototype.getAbsolutePosition = function () {
  33936. return this.transformedPosition ? this.transformedPosition : this.position;
  33937. };
  33938. /**
  33939. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33940. * Returns the updated DirectionalLight direction (Vector3).
  33941. */
  33942. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33943. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33944. return this.direction;
  33945. };
  33946. /**
  33947. * Returns the light rotation (Vector3).
  33948. */
  33949. ShadowLight.prototype.getRotation = function () {
  33950. this.direction.normalize();
  33951. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33952. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33953. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33954. };
  33955. /**
  33956. * Boolean : false by default.
  33957. */
  33958. ShadowLight.prototype.needCube = function () {
  33959. return false;
  33960. };
  33961. /**
  33962. * Specifies wether or not the projection matrix should be recomputed this frame.
  33963. */
  33964. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33965. return this._needProjectionMatrixCompute;
  33966. };
  33967. /**
  33968. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33969. */
  33970. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33971. this._needProjectionMatrixCompute = true;
  33972. };
  33973. /**
  33974. * Get the world matrix of the sahdow lights.
  33975. */
  33976. ShadowLight.prototype._getWorldMatrix = function () {
  33977. if (!this._worldMatrix) {
  33978. this._worldMatrix = BABYLON.Matrix.Identity();
  33979. }
  33980. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33981. return this._worldMatrix;
  33982. };
  33983. /**
  33984. * Gets the minZ used for shadow according to both the scene and the light.
  33985. * @param activeCamera
  33986. */
  33987. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33988. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33989. };
  33990. /**
  33991. * Gets the maxZ used for shadow according to both the scene and the light.
  33992. * @param activeCamera
  33993. */
  33994. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33995. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33996. };
  33997. /**
  33998. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33999. * Returns the light.
  34000. */
  34001. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34002. if (this.customProjectionMatrixBuilder) {
  34003. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  34004. }
  34005. else {
  34006. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34007. }
  34008. return this;
  34009. };
  34010. return ShadowLight;
  34011. }(BABYLON.Light));
  34012. __decorate([
  34013. BABYLON.serializeAsVector3()
  34014. ], ShadowLight.prototype, "position", void 0);
  34015. __decorate([
  34016. BABYLON.serializeAsVector3()
  34017. ], ShadowLight.prototype, "direction", null);
  34018. __decorate([
  34019. BABYLON.serialize()
  34020. ], ShadowLight.prototype, "shadowMinZ", null);
  34021. __decorate([
  34022. BABYLON.serialize()
  34023. ], ShadowLight.prototype, "shadowMaxZ", null);
  34024. BABYLON.ShadowLight = ShadowLight;
  34025. })(BABYLON || (BABYLON = {}));
  34026. //# sourceMappingURL=babylon.shadowLight.js.map
  34027. var BABYLON;
  34028. (function (BABYLON) {
  34029. var PointLight = (function (_super) {
  34030. __extends(PointLight, _super);
  34031. /**
  34032. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  34033. * A PointLight emits the light in every direction.
  34034. * It can cast shadows.
  34035. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  34036. * ```javascript
  34037. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  34038. * ```
  34039. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34040. */
  34041. function PointLight(name, position, scene) {
  34042. var _this = _super.call(this, name, scene) || this;
  34043. _this._shadowAngle = Math.PI / 2;
  34044. _this.position = position;
  34045. return _this;
  34046. }
  34047. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  34048. /**
  34049. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34050. * This specifies what angle the shadow will use to be created.
  34051. *
  34052. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34053. */
  34054. get: function () {
  34055. return this._shadowAngle;
  34056. },
  34057. /**
  34058. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34059. * This specifies what angle the shadow will use to be created.
  34060. *
  34061. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34062. */
  34063. set: function (value) {
  34064. this._shadowAngle = value;
  34065. this.forceProjectionMatrixCompute();
  34066. },
  34067. enumerable: true,
  34068. configurable: true
  34069. });
  34070. Object.defineProperty(PointLight.prototype, "direction", {
  34071. get: function () {
  34072. return this._direction;
  34073. },
  34074. /**
  34075. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34076. */
  34077. set: function (value) {
  34078. var previousNeedCube = this.needCube();
  34079. this._direction = value;
  34080. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34081. this._shadowGenerator.recreateShadowMap();
  34082. }
  34083. },
  34084. enumerable: true,
  34085. configurable: true
  34086. });
  34087. /**
  34088. * Returns the string "PointLight"
  34089. */
  34090. PointLight.prototype.getClassName = function () {
  34091. return "PointLight";
  34092. };
  34093. /**
  34094. * Returns the integer 0.
  34095. */
  34096. PointLight.prototype.getTypeID = function () {
  34097. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34098. };
  34099. /**
  34100. * Specifies wether or not the shadowmap should be a cube texture.
  34101. */
  34102. PointLight.prototype.needCube = function () {
  34103. return !this.direction;
  34104. };
  34105. /**
  34106. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34107. */
  34108. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34109. if (this.direction) {
  34110. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34111. }
  34112. else {
  34113. switch (faceIndex) {
  34114. case 0:
  34115. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34116. case 1:
  34117. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34118. case 2:
  34119. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34120. case 3:
  34121. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34122. case 4:
  34123. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34124. case 5:
  34125. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34126. }
  34127. }
  34128. return BABYLON.Vector3.Zero();
  34129. };
  34130. /**
  34131. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34132. * - fov = PI / 2
  34133. * - aspect ratio : 1.0
  34134. * - z-near and far equal to the active camera minZ and maxZ.
  34135. * Returns the PointLight.
  34136. */
  34137. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34138. var activeCamera = this.getScene().activeCamera;
  34139. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34140. };
  34141. PointLight.prototype._buildUniformLayout = function () {
  34142. this._uniformBuffer.addUniform("vLightData", 4);
  34143. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34144. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34145. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34146. this._uniformBuffer.addUniform("depthValues", 2);
  34147. this._uniformBuffer.create();
  34148. };
  34149. /**
  34150. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34151. * Returns the PointLight.
  34152. */
  34153. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34154. if (this.computeTransformedInformation()) {
  34155. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34156. return this;
  34157. }
  34158. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34159. return this;
  34160. };
  34161. return PointLight;
  34162. }(BABYLON.ShadowLight));
  34163. __decorate([
  34164. BABYLON.serialize()
  34165. ], PointLight.prototype, "shadowAngle", null);
  34166. BABYLON.PointLight = PointLight;
  34167. })(BABYLON || (BABYLON = {}));
  34168. //# sourceMappingURL=babylon.pointLight.js.map
  34169. /// <reference path="babylon.light.ts" />
  34170. var BABYLON;
  34171. (function (BABYLON) {
  34172. var DirectionalLight = (function (_super) {
  34173. __extends(DirectionalLight, _super);
  34174. /**
  34175. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34176. * The directional light is emitted from everywhere in the given direction.
  34177. * It can cast shawdows.
  34178. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34179. */
  34180. function DirectionalLight(name, direction, scene) {
  34181. var _this = _super.call(this, name, scene) || this;
  34182. _this._shadowFrustumSize = 0;
  34183. _this._shadowOrthoScale = 0.5;
  34184. _this.autoUpdateExtends = true;
  34185. // Cache
  34186. _this._orthoLeft = Number.MAX_VALUE;
  34187. _this._orthoRight = Number.MIN_VALUE;
  34188. _this._orthoTop = Number.MIN_VALUE;
  34189. _this._orthoBottom = Number.MAX_VALUE;
  34190. _this.position = direction.scale(-1.0);
  34191. _this.direction = direction;
  34192. return _this;
  34193. }
  34194. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34195. /**
  34196. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34197. */
  34198. get: function () {
  34199. return this._shadowFrustumSize;
  34200. },
  34201. /**
  34202. * Specifies a fix frustum size for the shadow generation.
  34203. */
  34204. set: function (value) {
  34205. this._shadowFrustumSize = value;
  34206. this.forceProjectionMatrixCompute();
  34207. },
  34208. enumerable: true,
  34209. configurable: true
  34210. });
  34211. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34212. get: function () {
  34213. return this._shadowOrthoScale;
  34214. },
  34215. set: function (value) {
  34216. this._shadowOrthoScale = value;
  34217. this.forceProjectionMatrixCompute();
  34218. },
  34219. enumerable: true,
  34220. configurable: true
  34221. });
  34222. /**
  34223. * Returns the string "DirectionalLight".
  34224. */
  34225. DirectionalLight.prototype.getClassName = function () {
  34226. return "DirectionalLight";
  34227. };
  34228. /**
  34229. * Returns the integer 1.
  34230. */
  34231. DirectionalLight.prototype.getTypeID = function () {
  34232. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34233. };
  34234. /**
  34235. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34236. * Returns the DirectionalLight Shadow projection matrix.
  34237. */
  34238. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34239. if (this.shadowFrustumSize > 0) {
  34240. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34241. }
  34242. else {
  34243. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34244. }
  34245. };
  34246. /**
  34247. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34248. * Returns the DirectionalLight Shadow projection matrix.
  34249. */
  34250. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34251. var activeCamera = this.getScene().activeCamera;
  34252. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34253. };
  34254. /**
  34255. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34256. * Returns the DirectionalLight Shadow projection matrix.
  34257. */
  34258. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34259. var activeCamera = this.getScene().activeCamera;
  34260. // Check extends
  34261. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34262. var tempVector3 = BABYLON.Vector3.Zero();
  34263. this._orthoLeft = Number.MAX_VALUE;
  34264. this._orthoRight = Number.MIN_VALUE;
  34265. this._orthoTop = Number.MIN_VALUE;
  34266. this._orthoBottom = Number.MAX_VALUE;
  34267. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34268. var mesh = renderList[meshIndex];
  34269. if (!mesh) {
  34270. continue;
  34271. }
  34272. var boundingInfo = mesh.getBoundingInfo();
  34273. if (!boundingInfo) {
  34274. continue;
  34275. }
  34276. var boundingBox = boundingInfo.boundingBox;
  34277. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34278. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34279. if (tempVector3.x < this._orthoLeft)
  34280. this._orthoLeft = tempVector3.x;
  34281. if (tempVector3.y < this._orthoBottom)
  34282. this._orthoBottom = tempVector3.y;
  34283. if (tempVector3.x > this._orthoRight)
  34284. this._orthoRight = tempVector3.x;
  34285. if (tempVector3.y > this._orthoTop)
  34286. this._orthoTop = tempVector3.y;
  34287. }
  34288. }
  34289. }
  34290. var xOffset = this._orthoRight - this._orthoLeft;
  34291. var yOffset = this._orthoTop - this._orthoBottom;
  34292. 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);
  34293. };
  34294. DirectionalLight.prototype._buildUniformLayout = function () {
  34295. this._uniformBuffer.addUniform("vLightData", 4);
  34296. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34297. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34298. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34299. this._uniformBuffer.addUniform("depthValues", 2);
  34300. this._uniformBuffer.create();
  34301. };
  34302. /**
  34303. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34304. * Returns the DirectionalLight.
  34305. */
  34306. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34307. if (this.computeTransformedInformation()) {
  34308. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34309. return this;
  34310. }
  34311. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34312. return this;
  34313. };
  34314. /**
  34315. * Gets the minZ used for shadow according to both the scene and the light.
  34316. *
  34317. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34318. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34319. * @param activeCamera
  34320. */
  34321. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34322. return 1;
  34323. };
  34324. /**
  34325. * Gets the maxZ used for shadow according to both the scene and the light.
  34326. *
  34327. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34328. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34329. * @param activeCamera
  34330. */
  34331. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34332. return 1;
  34333. };
  34334. return DirectionalLight;
  34335. }(BABYLON.ShadowLight));
  34336. __decorate([
  34337. BABYLON.serialize()
  34338. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34339. __decorate([
  34340. BABYLON.serialize()
  34341. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34342. __decorate([
  34343. BABYLON.serialize()
  34344. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34345. BABYLON.DirectionalLight = DirectionalLight;
  34346. })(BABYLON || (BABYLON = {}));
  34347. //# sourceMappingURL=babylon.directionalLight.js.map
  34348. var BABYLON;
  34349. (function (BABYLON) {
  34350. var SpotLight = (function (_super) {
  34351. __extends(SpotLight, _super);
  34352. /**
  34353. * Creates a SpotLight object in the scene with the passed parameters :
  34354. * - `position` (Vector3) is the initial SpotLight position,
  34355. * - `direction` (Vector3) is the initial SpotLight direction,
  34356. * - `angle` (float, in radians) is the spot light cone angle,
  34357. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34358. * A spot light is a simply light oriented cone.
  34359. * It can cast shadows.
  34360. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34361. */
  34362. function SpotLight(name, position, direction, angle, exponent, scene) {
  34363. var _this = _super.call(this, name, scene) || this;
  34364. _this.position = position;
  34365. _this.direction = direction;
  34366. _this.angle = angle;
  34367. _this.exponent = exponent;
  34368. return _this;
  34369. }
  34370. Object.defineProperty(SpotLight.prototype, "angle", {
  34371. get: function () {
  34372. return this._angle;
  34373. },
  34374. set: function (value) {
  34375. this._angle = value;
  34376. this.forceProjectionMatrixCompute();
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34382. get: function () {
  34383. return this._shadowAngleScale;
  34384. },
  34385. /**
  34386. * Allows scaling the angle of the light for shadow generation only.
  34387. */
  34388. set: function (value) {
  34389. this._shadowAngleScale = value;
  34390. this.forceProjectionMatrixCompute();
  34391. },
  34392. enumerable: true,
  34393. configurable: true
  34394. });
  34395. /**
  34396. * Returns the string "SpotLight".
  34397. */
  34398. SpotLight.prototype.getClassName = function () {
  34399. return "SpotLight";
  34400. };
  34401. /**
  34402. * Returns the integer 2.
  34403. */
  34404. SpotLight.prototype.getTypeID = function () {
  34405. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34406. };
  34407. /**
  34408. * 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.
  34409. * Returns the SpotLight.
  34410. */
  34411. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34412. var activeCamera = this.getScene().activeCamera;
  34413. this._shadowAngleScale = this._shadowAngleScale || 1;
  34414. var angle = this._shadowAngleScale * this._angle;
  34415. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34416. };
  34417. SpotLight.prototype._buildUniformLayout = function () {
  34418. this._uniformBuffer.addUniform("vLightData", 4);
  34419. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34420. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34421. this._uniformBuffer.addUniform("vLightDirection", 3);
  34422. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34423. this._uniformBuffer.addUniform("depthValues", 2);
  34424. this._uniformBuffer.create();
  34425. };
  34426. /**
  34427. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34428. * Return the SpotLight.
  34429. */
  34430. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34431. var normalizeDirection;
  34432. if (this.computeTransformedInformation()) {
  34433. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34434. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34435. }
  34436. else {
  34437. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34438. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34439. }
  34440. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34441. return this;
  34442. };
  34443. return SpotLight;
  34444. }(BABYLON.ShadowLight));
  34445. __decorate([
  34446. BABYLON.serialize()
  34447. ], SpotLight.prototype, "angle", null);
  34448. __decorate([
  34449. BABYLON.serialize()
  34450. /**
  34451. * Allows scaling the angle of the light for shadow generation only.
  34452. */
  34453. ], SpotLight.prototype, "shadowAngleScale", null);
  34454. __decorate([
  34455. BABYLON.serialize()
  34456. ], SpotLight.prototype, "exponent", void 0);
  34457. BABYLON.SpotLight = SpotLight;
  34458. })(BABYLON || (BABYLON = {}));
  34459. //# sourceMappingURL=babylon.spotLight.js.map
  34460. var BABYLON;
  34461. (function (BABYLON) {
  34462. var MultiMaterial = (function (_super) {
  34463. __extends(MultiMaterial, _super);
  34464. function MultiMaterial(name, scene) {
  34465. var _this = _super.call(this, name, scene, true) || this;
  34466. scene.multiMaterials.push(_this);
  34467. _this.subMaterials = new Array();
  34468. return _this;
  34469. }
  34470. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  34471. get: function () {
  34472. return this._subMaterials;
  34473. },
  34474. set: function (value) {
  34475. this._subMaterials = value;
  34476. this._hookArray(value);
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. MultiMaterial.prototype._hookArray = function (array) {
  34482. var _this = this;
  34483. var oldPush = array.push;
  34484. array.push = function () {
  34485. var items = [];
  34486. for (var _i = 0; _i < arguments.length; _i++) {
  34487. items[_i] = arguments[_i];
  34488. }
  34489. var result = oldPush.apply(array, items);
  34490. _this._markAllSubMeshesAsTexturesDirty();
  34491. return result;
  34492. };
  34493. var oldSplice = array.splice;
  34494. array.splice = function (index, deleteCount) {
  34495. var deleted = oldSplice.apply(array, [index, deleteCount]);
  34496. _this._markAllSubMeshesAsTexturesDirty();
  34497. return deleted;
  34498. };
  34499. };
  34500. // Properties
  34501. MultiMaterial.prototype.getSubMaterial = function (index) {
  34502. if (index < 0 || index >= this.subMaterials.length) {
  34503. return this.getScene().defaultMaterial;
  34504. }
  34505. return this.subMaterials[index];
  34506. };
  34507. MultiMaterial.prototype.getActiveTextures = function () {
  34508. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  34509. var _a;
  34510. };
  34511. // Methods
  34512. MultiMaterial.prototype.getClassName = function () {
  34513. return "MultiMaterial";
  34514. };
  34515. MultiMaterial.prototype.isReady = function (mesh) {
  34516. for (var index = 0; index < this.subMaterials.length; index++) {
  34517. var subMaterial = this.subMaterials[index];
  34518. if (subMaterial) {
  34519. if (!this.subMaterials[index].isReady(mesh)) {
  34520. return false;
  34521. }
  34522. }
  34523. }
  34524. return true;
  34525. };
  34526. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  34527. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  34528. for (var index = 0; index < this.subMaterials.length; index++) {
  34529. var subMaterial = null;
  34530. if (cloneChildren) {
  34531. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  34532. }
  34533. else {
  34534. subMaterial = this.subMaterials[index];
  34535. }
  34536. newMultiMaterial.subMaterials.push(subMaterial);
  34537. }
  34538. return newMultiMaterial;
  34539. };
  34540. MultiMaterial.prototype.serialize = function () {
  34541. var serializationObject = {};
  34542. serializationObject.name = this.name;
  34543. serializationObject.id = this.id;
  34544. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34545. serializationObject.materials = [];
  34546. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  34547. var subMat = this.subMaterials[matIndex];
  34548. if (subMat) {
  34549. serializationObject.materials.push(subMat.id);
  34550. }
  34551. else {
  34552. serializationObject.materials.push(null);
  34553. }
  34554. }
  34555. return serializationObject;
  34556. };
  34557. return MultiMaterial;
  34558. }(BABYLON.Material));
  34559. BABYLON.MultiMaterial = MultiMaterial;
  34560. })(BABYLON || (BABYLON = {}));
  34561. //# sourceMappingURL=babylon.multiMaterial.js.map
  34562. var BABYLON;
  34563. (function (BABYLON) {
  34564. var PBRMaterialDefines = (function (_super) {
  34565. __extends(PBRMaterialDefines, _super);
  34566. function PBRMaterialDefines() {
  34567. var _this = _super.call(this) || this;
  34568. _this.PBR = true;
  34569. _this.ALBEDO = false;
  34570. _this.AMBIENT = false;
  34571. _this.AMBIENTINGRAYSCALE = false;
  34572. _this.OPACITY = false;
  34573. _this.OPACITYRGB = false;
  34574. _this.REFLECTION = false;
  34575. _this.EMISSIVE = false;
  34576. _this.REFLECTIVITY = false;
  34577. _this.BUMP = false;
  34578. _this.PARALLAX = false;
  34579. _this.PARALLAXOCCLUSION = false;
  34580. _this.SPECULAROVERALPHA = false;
  34581. _this.CLIPPLANE = false;
  34582. _this.ALPHATEST = false;
  34583. _this.ALPHABLEND = false;
  34584. _this.ALPHAFROMALBEDO = false;
  34585. _this.POINTSIZE = false;
  34586. _this.FOG = false;
  34587. _this.SPECULARTERM = false;
  34588. _this.NORMAL = false;
  34589. _this.TANGENT = false;
  34590. _this.UV1 = false;
  34591. _this.UV2 = false;
  34592. _this.VERTEXCOLOR = false;
  34593. _this.VERTEXALPHA = false;
  34594. _this.NUM_BONE_INFLUENCERS = 0;
  34595. _this.BonesPerMesh = 0;
  34596. _this.INSTANCES = false;
  34597. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34598. _this.MICROSURFACEAUTOMATIC = false;
  34599. _this.LIGHTMAP = false;
  34600. _this.USELIGHTMAPASSHADOWMAP = false;
  34601. _this.REFLECTIONMAP_3D = false;
  34602. _this.REFLECTIONMAP_SPHERICAL = false;
  34603. _this.REFLECTIONMAP_PLANAR = false;
  34604. _this.REFLECTIONMAP_CUBIC = false;
  34605. _this.REFLECTIONMAP_PROJECTION = false;
  34606. _this.REFLECTIONMAP_SKYBOX = false;
  34607. _this.REFLECTIONMAP_EXPLICIT = false;
  34608. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34609. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34610. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34611. _this.INVERTCUBICMAP = false;
  34612. _this.LOGARITHMICDEPTH = false;
  34613. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34614. _this.REFRACTION = false;
  34615. _this.REFRACTIONMAP_3D = false;
  34616. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34617. _this.REFRACTIONMAPINLINEARSPACE = false;
  34618. _this.LODBASEDMICROSFURACE = false;
  34619. _this.USEPHYSICALLIGHTFALLOFF = false;
  34620. _this.RADIANCEOVERALPHA = false;
  34621. _this.USEPMREMREFLECTION = false;
  34622. _this.USEPMREMREFRACTION = false;
  34623. _this.INVERTNORMALMAPX = false;
  34624. _this.INVERTNORMALMAPY = false;
  34625. _this.TWOSIDEDLIGHTING = false;
  34626. _this.SHADOWFLOAT = false;
  34627. _this.NORMALXYSCALE = true;
  34628. _this.USERIGHTHANDEDSYSTEM = false;
  34629. _this.METALLICWORKFLOW = false;
  34630. _this.METALLICMAP = false;
  34631. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34632. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34633. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34634. _this.AOSTOREINMETALMAPRED = false;
  34635. _this.MICROSURFACEMAP = false;
  34636. _this.MORPHTARGETS = false;
  34637. _this.MORPHTARGETS_NORMAL = false;
  34638. _this.MORPHTARGETS_TANGENT = false;
  34639. _this.NUM_MORPH_INFLUENCERS = 0;
  34640. _this.ALPHATESTVALUE = 0.5;
  34641. _this.PREMULTIPLYALPHA = false;
  34642. _this.ALPHAFRESNEL = false;
  34643. _this.IMAGEPROCESSING = false;
  34644. _this.VIGNETTE = false;
  34645. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34646. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34647. _this.TONEMAPPING = false;
  34648. _this.CONTRAST = false;
  34649. _this.COLORCURVES = false;
  34650. _this.COLORGRADING = false;
  34651. _this.SAMPLER3DGREENDEPTH = false;
  34652. _this.SAMPLER3DBGRMAP = false;
  34653. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34654. _this.EXPOSURE = false;
  34655. _this.rebuild();
  34656. return _this;
  34657. }
  34658. PBRMaterialDefines.prototype.reset = function () {
  34659. _super.prototype.reset.call(this);
  34660. this.ALPHATESTVALUE = 0.5;
  34661. this.PBR = true;
  34662. };
  34663. return PBRMaterialDefines;
  34664. }(BABYLON.MaterialDefines));
  34665. /**
  34666. * The Physically based material base class of BJS.
  34667. *
  34668. * This offers the main features of a standard PBR material.
  34669. * For more information, please refer to the documentation :
  34670. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34671. */
  34672. var PBRBaseMaterial = (function (_super) {
  34673. __extends(PBRBaseMaterial, _super);
  34674. /**
  34675. * Instantiates a new PBRMaterial instance.
  34676. *
  34677. * @param name The material name
  34678. * @param scene The scene the material will be use in.
  34679. */
  34680. function PBRBaseMaterial(name, scene) {
  34681. var _this = _super.call(this, name, scene) || this;
  34682. /**
  34683. * Intensity of the direct lights e.g. the four lights available in your scene.
  34684. * This impacts both the direct diffuse and specular highlights.
  34685. */
  34686. _this._directIntensity = 1.0;
  34687. /**
  34688. * Intensity of the emissive part of the material.
  34689. * This helps controlling the emissive effect without modifying the emissive color.
  34690. */
  34691. _this._emissiveIntensity = 1.0;
  34692. /**
  34693. * Intensity of the environment e.g. how much the environment will light the object
  34694. * either through harmonics for rough material or through the refelction for shiny ones.
  34695. */
  34696. _this._environmentIntensity = 1.0;
  34697. /**
  34698. * This is a special control allowing the reduction of the specular highlights coming from the
  34699. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34700. */
  34701. _this._specularIntensity = 1.0;
  34702. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34703. /**
  34704. * Debug Control allowing disabling the bump map on this material.
  34705. */
  34706. _this._disableBumpMap = false;
  34707. /**
  34708. * AKA Occlusion Texture Intensity in other nomenclature.
  34709. */
  34710. _this._ambientTextureStrength = 1.0;
  34711. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  34712. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34713. /**
  34714. * AKA Diffuse Color in other nomenclature.
  34715. */
  34716. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34717. /**
  34718. * AKA Specular Color in other nomenclature.
  34719. */
  34720. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34721. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34722. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34723. /**
  34724. * AKA Glossiness in other nomenclature.
  34725. */
  34726. _this._microSurface = 0.9;
  34727. /**
  34728. * source material index of refraction (IOR)' / 'destination material IOR.
  34729. */
  34730. _this._indexOfRefraction = 0.66;
  34731. /**
  34732. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34733. */
  34734. _this._invertRefractionY = false;
  34735. /**
  34736. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34737. * Materials half opaque for instance using refraction could benefit from this control.
  34738. */
  34739. _this._linkRefractionWithTransparency = false;
  34740. _this._useLightmapAsShadowmap = false;
  34741. /**
  34742. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34743. */
  34744. _this._useAlphaFromAlbedoTexture = false;
  34745. /**
  34746. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34747. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34748. */
  34749. _this._useSpecularOverAlpha = true;
  34750. /**
  34751. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34752. */
  34753. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34754. /**
  34755. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34756. */
  34757. _this._useRoughnessFromMetallicTextureAlpha = true;
  34758. /**
  34759. * Specifies if the metallic texture contains the roughness information in its green channel.
  34760. */
  34761. _this._useRoughnessFromMetallicTextureGreen = false;
  34762. /**
  34763. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34764. */
  34765. _this._useMetallnessFromMetallicTextureBlue = false;
  34766. /**
  34767. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34768. */
  34769. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34770. /**
  34771. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34772. */
  34773. _this._useAmbientInGrayScale = false;
  34774. /**
  34775. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34776. * The material will try to infer what glossiness each pixel should be.
  34777. */
  34778. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34779. /**
  34780. * BJS is using an harcoded light falloff based on a manually sets up range.
  34781. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34782. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34783. */
  34784. _this._usePhysicalLightFalloff = true;
  34785. /**
  34786. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34787. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34788. */
  34789. _this._useRadianceOverAlpha = true;
  34790. /**
  34791. * Allows using the bump map in parallax mode.
  34792. */
  34793. _this._useParallax = false;
  34794. /**
  34795. * Allows using the bump map in parallax occlusion mode.
  34796. */
  34797. _this._useParallaxOcclusion = false;
  34798. /**
  34799. * Controls the scale bias of the parallax mode.
  34800. */
  34801. _this._parallaxScaleBias = 0.05;
  34802. /**
  34803. * If sets to true, disables all the lights affecting the material.
  34804. */
  34805. _this._disableLighting = false;
  34806. /**
  34807. * Number of Simultaneous lights allowed on the material.
  34808. */
  34809. _this._maxSimultaneousLights = 4;
  34810. /**
  34811. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34812. */
  34813. _this._invertNormalMapX = false;
  34814. /**
  34815. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34816. */
  34817. _this._invertNormalMapY = false;
  34818. /**
  34819. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34820. */
  34821. _this._twoSidedLighting = false;
  34822. /**
  34823. * Defines the alpha limits in alpha test mode.
  34824. */
  34825. _this._alphaCutOff = 0.4;
  34826. /**
  34827. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34828. */
  34829. _this._forceAlphaTest = false;
  34830. /**
  34831. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  34832. * in your scene composition.
  34833. */
  34834. _this._premultiplyAlpha = false;
  34835. /**
  34836. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34837. * And/Or occlude the blended part.
  34838. */
  34839. _this._useAlphaFresnel = false;
  34840. _this._renderTargets = new BABYLON.SmartArray(16);
  34841. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34842. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34843. _this._tempColor = new BABYLON.Color3();
  34844. // Setup the default processing configuration to the scene.
  34845. _this._attachImageProcessingConfiguration(null);
  34846. _this.getRenderTargetTextures = function () {
  34847. _this._renderTargets.reset();
  34848. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34849. _this._renderTargets.push(_this._reflectionTexture);
  34850. }
  34851. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34852. _this._renderTargets.push(_this._refractionTexture);
  34853. }
  34854. return _this._renderTargets;
  34855. };
  34856. return _this;
  34857. }
  34858. /**
  34859. * Attaches a new image processing configuration to the PBR Material.
  34860. * @param configuration
  34861. */
  34862. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34863. var _this = this;
  34864. if (configuration === this._imageProcessingConfiguration) {
  34865. return;
  34866. }
  34867. // Detaches observer.
  34868. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34869. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34870. }
  34871. // Pick the scene configuration if needed.
  34872. if (!configuration) {
  34873. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34874. }
  34875. else {
  34876. this._imageProcessingConfiguration = configuration;
  34877. }
  34878. // Attaches observer.
  34879. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34880. _this._markAllSubMeshesAsTexturesDirty();
  34881. });
  34882. };
  34883. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34884. get: function () {
  34885. return this._useLogarithmicDepth;
  34886. },
  34887. set: function (value) {
  34888. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34889. },
  34890. enumerable: true,
  34891. configurable: true
  34892. });
  34893. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34894. if (this._linkRefractionWithTransparency) {
  34895. return false;
  34896. }
  34897. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34898. };
  34899. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34900. if (this._forceAlphaTest) {
  34901. return true;
  34902. }
  34903. if (this._linkRefractionWithTransparency) {
  34904. return false;
  34905. }
  34906. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34907. };
  34908. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34909. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34910. };
  34911. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34912. return this._albedoTexture;
  34913. };
  34914. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34915. if (this.isFrozen) {
  34916. if (this._wasPreviouslyReady) {
  34917. return true;
  34918. }
  34919. }
  34920. if (!subMesh._materialDefines) {
  34921. subMesh._materialDefines = new PBRMaterialDefines();
  34922. }
  34923. var scene = this.getScene();
  34924. var defines = subMesh._materialDefines;
  34925. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34926. if (defines._renderId === scene.getRenderId()) {
  34927. return true;
  34928. }
  34929. }
  34930. var engine = scene.getEngine();
  34931. // Lights
  34932. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34933. defines._needNormals = true;
  34934. // Textures
  34935. if (defines._areTexturesDirty) {
  34936. defines._needUVs = false;
  34937. if (scene.texturesEnabled) {
  34938. if (scene.getEngine().getCaps().textureLOD) {
  34939. defines.LODBASEDMICROSFURACE = true;
  34940. }
  34941. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34942. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34943. return false;
  34944. }
  34945. defines._needUVs = true;
  34946. defines.ALBEDO = true;
  34947. }
  34948. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34949. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34950. return false;
  34951. }
  34952. defines._needUVs = true;
  34953. defines.AMBIENT = true;
  34954. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34955. }
  34956. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34957. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34958. return false;
  34959. }
  34960. defines._needUVs = true;
  34961. defines.OPACITY = true;
  34962. if (this._opacityTexture.getAlphaFromRGB) {
  34963. defines.OPACITYRGB = true;
  34964. }
  34965. }
  34966. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  34967. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34968. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34969. return false;
  34970. }
  34971. defines.REFLECTION = true;
  34972. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34973. defines.INVERTCUBICMAP = true;
  34974. }
  34975. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34976. switch (reflectionTexture.coordinatesMode) {
  34977. case BABYLON.Texture.CUBIC_MODE:
  34978. case BABYLON.Texture.INVCUBIC_MODE:
  34979. defines.REFLECTIONMAP_CUBIC = true;
  34980. break;
  34981. case BABYLON.Texture.EXPLICIT_MODE:
  34982. defines.REFLECTIONMAP_EXPLICIT = true;
  34983. break;
  34984. case BABYLON.Texture.PLANAR_MODE:
  34985. defines.REFLECTIONMAP_PLANAR = true;
  34986. break;
  34987. case BABYLON.Texture.PROJECTION_MODE:
  34988. defines.REFLECTIONMAP_PROJECTION = true;
  34989. break;
  34990. case BABYLON.Texture.SKYBOX_MODE:
  34991. defines.REFLECTIONMAP_SKYBOX = true;
  34992. break;
  34993. case BABYLON.Texture.SPHERICAL_MODE:
  34994. defines.REFLECTIONMAP_SPHERICAL = true;
  34995. break;
  34996. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34997. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34998. break;
  34999. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35000. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35001. break;
  35002. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35003. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35004. break;
  35005. }
  35006. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  35007. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35008. if (reflectionTexture.isPMREM) {
  35009. defines.USEPMREMREFLECTION = true;
  35010. }
  35011. }
  35012. }
  35013. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35014. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35015. return false;
  35016. }
  35017. defines._needUVs = true;
  35018. defines.LIGHTMAP = true;
  35019. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35020. }
  35021. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35022. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35023. return false;
  35024. }
  35025. defines._needUVs = true;
  35026. defines.EMISSIVE = true;
  35027. }
  35028. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35029. if (this._metallicTexture) {
  35030. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35031. return false;
  35032. }
  35033. defines._needUVs = true;
  35034. defines.METALLICWORKFLOW = true;
  35035. defines.METALLICMAP = true;
  35036. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35037. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35038. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35039. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35040. }
  35041. else if (this._reflectivityTexture) {
  35042. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35043. return false;
  35044. }
  35045. defines._needUVs = true;
  35046. defines.REFLECTIVITY = true;
  35047. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35048. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35049. }
  35050. if (this._microSurfaceTexture) {
  35051. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35052. return false;
  35053. }
  35054. defines._needUVs = true;
  35055. defines.MICROSURFACEMAP = true;
  35056. }
  35057. }
  35058. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35059. // Bump texure can not be none blocking.
  35060. if (!this._bumpTexture.isReady()) {
  35061. return false;
  35062. }
  35063. defines._needUVs = true;
  35064. defines.BUMP = true;
  35065. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35066. defines.PARALLAX = true;
  35067. if (this._useParallaxOcclusion) {
  35068. defines.PARALLAXOCCLUSION = true;
  35069. }
  35070. }
  35071. if (this._invertNormalMapX) {
  35072. defines.INVERTNORMALMAPX = true;
  35073. }
  35074. if (this._invertNormalMapY) {
  35075. defines.INVERTNORMALMAPY = true;
  35076. }
  35077. if (scene._mirroredCameraPosition) {
  35078. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  35079. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  35080. }
  35081. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  35082. }
  35083. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35084. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35085. return false;
  35086. }
  35087. defines._needUVs = true;
  35088. defines.REFRACTION = true;
  35089. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35090. if (this._linkRefractionWithTransparency) {
  35091. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35092. }
  35093. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  35094. defines.REFRACTIONMAPINLINEARSPACE = true;
  35095. if (this._refractionTexture.isPMREM) {
  35096. defines.USEPMREMREFRACTION = true;
  35097. }
  35098. }
  35099. }
  35100. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35101. defines.ALPHAFROMALBEDO = true;
  35102. }
  35103. }
  35104. if (this._useSpecularOverAlpha) {
  35105. defines.SPECULAROVERALPHA = true;
  35106. }
  35107. if (this._usePhysicalLightFalloff) {
  35108. defines.USEPHYSICALLIGHTFALLOFF = true;
  35109. }
  35110. if (this._useRadianceOverAlpha) {
  35111. defines.RADIANCEOVERALPHA = true;
  35112. }
  35113. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35114. defines.METALLICWORKFLOW = true;
  35115. }
  35116. if (!this.backFaceCulling && this._twoSidedLighting) {
  35117. defines.TWOSIDEDLIGHTING = true;
  35118. }
  35119. defines.ALPHATESTVALUE = this._alphaCutOff;
  35120. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  35121. defines.ALPHABLEND = this.needAlphaBlending();
  35122. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35123. if (!this._imageProcessingConfiguration.isReady()) {
  35124. return false;
  35125. }
  35126. this._imageProcessingConfiguration.prepareDefines(defines);
  35127. }
  35128. // Misc.
  35129. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35130. // Values that need to be evaluated on every frame
  35131. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  35132. // Attribs
  35133. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35134. if (mesh) {
  35135. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35136. mesh.createNormals(true);
  35137. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35138. }
  35139. }
  35140. }
  35141. // Get correct effect
  35142. if (defines.isDirty) {
  35143. defines.markAsProcessed();
  35144. scene.resetCachedMaterial();
  35145. // Fallbacks
  35146. var fallbacks = new BABYLON.EffectFallbacks();
  35147. if (defines.REFLECTION) {
  35148. fallbacks.addFallback(0, "REFLECTION");
  35149. }
  35150. if (defines.REFRACTION) {
  35151. fallbacks.addFallback(0, "REFRACTION");
  35152. }
  35153. if (defines.REFLECTIVITY) {
  35154. fallbacks.addFallback(0, "REFLECTIVITY");
  35155. }
  35156. if (defines.BUMP) {
  35157. fallbacks.addFallback(0, "BUMP");
  35158. }
  35159. if (defines.PARALLAX) {
  35160. fallbacks.addFallback(1, "PARALLAX");
  35161. }
  35162. if (defines.PARALLAXOCCLUSION) {
  35163. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35164. }
  35165. if (defines.SPECULAROVERALPHA) {
  35166. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35167. }
  35168. if (defines.FOG) {
  35169. fallbacks.addFallback(1, "FOG");
  35170. }
  35171. if (defines.POINTSIZE) {
  35172. fallbacks.addFallback(0, "POINTSIZE");
  35173. }
  35174. if (defines.LOGARITHMICDEPTH) {
  35175. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35176. }
  35177. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35178. if (defines.SPECULARTERM) {
  35179. fallbacks.addFallback(0, "SPECULARTERM");
  35180. }
  35181. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35182. fallbacks.addCPUSkinningFallback(0, mesh);
  35183. }
  35184. //Attributes
  35185. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35186. if (defines.NORMAL) {
  35187. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35188. }
  35189. if (defines.TANGENT) {
  35190. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35191. }
  35192. if (defines.UV1) {
  35193. attribs.push(BABYLON.VertexBuffer.UVKind);
  35194. }
  35195. if (defines.UV2) {
  35196. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35197. }
  35198. if (defines.VERTEXCOLOR) {
  35199. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35200. }
  35201. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35202. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35203. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35204. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35205. "vFogInfos", "vFogColor", "pointSize",
  35206. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35207. "mBones",
  35208. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35209. "vLightingIntensity",
  35210. "logarithmicDepthConstant",
  35211. "vSphericalX", "vSphericalY", "vSphericalZ",
  35212. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35213. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35214. "vMicrosurfaceTextureLods"
  35215. ];
  35216. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35217. var uniformBuffers = ["Material", "Scene"];
  35218. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35219. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35220. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35221. uniformsNames: uniforms,
  35222. uniformBuffersNames: uniformBuffers,
  35223. samplers: samplers,
  35224. defines: defines,
  35225. maxSimultaneousLights: this._maxSimultaneousLights
  35226. });
  35227. var onCompiled = function (effect) {
  35228. if (this.onCompiled) {
  35229. this.onCompiled(effect);
  35230. }
  35231. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35232. }.bind(this);
  35233. var join = defines.toString();
  35234. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35235. attributes: attribs,
  35236. uniformsNames: uniforms,
  35237. uniformBuffersNames: uniformBuffers,
  35238. samplers: samplers,
  35239. defines: join,
  35240. fallbacks: fallbacks,
  35241. onCompiled: onCompiled,
  35242. onError: this.onError,
  35243. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35244. }, engine), defines);
  35245. this.buildUniformLayout();
  35246. }
  35247. if (!subMesh.effect.isReady()) {
  35248. return false;
  35249. }
  35250. defines._renderId = scene.getRenderId();
  35251. this._wasPreviouslyReady = true;
  35252. return true;
  35253. };
  35254. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35255. // Order is important !
  35256. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35257. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35258. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35259. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35260. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35261. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35262. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35263. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35264. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35265. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35266. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35267. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35268. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35269. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35270. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35271. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35272. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35273. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35274. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35275. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35276. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35277. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35278. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35279. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  35280. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35281. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35282. this._uniformBuffer.addUniform("pointSize", 1);
  35283. this._uniformBuffer.create();
  35284. };
  35285. PBRBaseMaterial.prototype.unbind = function () {
  35286. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35287. this._uniformBuffer.setTexture("reflection2DSampler", null);
  35288. }
  35289. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35290. this._uniformBuffer.setTexture("refraction2DSampler", null);
  35291. }
  35292. _super.prototype.unbind.call(this);
  35293. };
  35294. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35295. this._activeEffect.setMatrix("world", world);
  35296. };
  35297. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35298. var scene = this.getScene();
  35299. var defines = subMesh._materialDefines;
  35300. if (!defines) {
  35301. return;
  35302. }
  35303. var effect = subMesh.effect;
  35304. this._activeEffect = effect;
  35305. // Matrices
  35306. this.bindOnlyWorldMatrix(world);
  35307. // Bones
  35308. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35309. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35310. this._uniformBuffer.bindToEffect(effect, "Material");
  35311. this.bindViewProjection(effect);
  35312. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35313. // Texture uniforms
  35314. if (scene.texturesEnabled) {
  35315. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35316. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35317. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  35318. }
  35319. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35320. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35321. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35322. }
  35323. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35324. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35325. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35326. }
  35327. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35328. ;
  35329. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35330. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  35331. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35332. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35333. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35334. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  35335. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  35336. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  35337. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  35338. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  35339. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  35340. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  35341. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  35342. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  35343. }
  35344. }
  35345. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35346. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35347. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35348. }
  35349. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35350. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35351. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35352. }
  35353. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35354. if (this._metallicTexture) {
  35355. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35356. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  35357. }
  35358. else if (this._reflectivityTexture) {
  35359. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35360. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  35361. }
  35362. if (this._microSurfaceTexture) {
  35363. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35364. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  35365. }
  35366. }
  35367. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35368. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35369. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35370. }
  35371. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35372. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  35373. var depth = 1.0;
  35374. if (!this._refractionTexture.isCube) {
  35375. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35376. if (this._refractionTexture.depth) {
  35377. depth = this._refractionTexture.depth;
  35378. }
  35379. }
  35380. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35381. }
  35382. if ((reflectionTexture || this._refractionTexture)) {
  35383. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  35384. }
  35385. }
  35386. // Point size
  35387. if (this.pointsCloud) {
  35388. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35389. }
  35390. // Colors
  35391. if (defines.METALLICWORKFLOW) {
  35392. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35393. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35394. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35395. }
  35396. else {
  35397. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35398. }
  35399. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35400. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35401. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35402. // Misc
  35403. this._lightingInfos.x = this._directIntensity;
  35404. this._lightingInfos.y = this._emissiveIntensity;
  35405. this._lightingInfos.z = this._environmentIntensity;
  35406. this._lightingInfos.w = this._specularIntensity;
  35407. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35408. }
  35409. // Textures
  35410. if (scene.texturesEnabled) {
  35411. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35412. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35413. }
  35414. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35415. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35416. }
  35417. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35418. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35419. }
  35420. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35421. if (reflectionTexture.isCube) {
  35422. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  35423. }
  35424. else {
  35425. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  35426. }
  35427. }
  35428. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35429. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35430. }
  35431. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35432. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35433. }
  35434. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35435. if (this._metallicTexture) {
  35436. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35437. }
  35438. else if (this._reflectivityTexture) {
  35439. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35440. }
  35441. if (this._microSurfaceTexture) {
  35442. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35443. }
  35444. }
  35445. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35446. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35447. }
  35448. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35449. if (this._refractionTexture.isCube) {
  35450. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  35451. }
  35452. else {
  35453. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  35454. }
  35455. }
  35456. }
  35457. // Clip plane
  35458. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35459. // Colors
  35460. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35461. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35462. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35463. }
  35464. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35465. // Lights
  35466. if (scene.lightsEnabled && !this._disableLighting) {
  35467. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35468. }
  35469. // View
  35470. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35471. this.bindView(effect);
  35472. }
  35473. // Fog
  35474. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35475. // Morph targets
  35476. if (defines.NUM_MORPH_INFLUENCERS) {
  35477. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35478. }
  35479. // image processing
  35480. this._imageProcessingConfiguration.bind(this._activeEffect);
  35481. // Log. depth
  35482. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35483. }
  35484. this._uniformBuffer.update();
  35485. this._afterBind(mesh);
  35486. scene = null;
  35487. };
  35488. PBRBaseMaterial.prototype.getAnimatables = function () {
  35489. var results = [];
  35490. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35491. results.push(this._albedoTexture);
  35492. }
  35493. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35494. results.push(this._ambientTexture);
  35495. }
  35496. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35497. results.push(this._opacityTexture);
  35498. }
  35499. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35500. results.push(this._reflectionTexture);
  35501. }
  35502. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35503. results.push(this._emissiveTexture);
  35504. }
  35505. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35506. results.push(this._metallicTexture);
  35507. }
  35508. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35509. results.push(this._reflectivityTexture);
  35510. }
  35511. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35512. results.push(this._bumpTexture);
  35513. }
  35514. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35515. results.push(this._lightmapTexture);
  35516. }
  35517. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35518. results.push(this._refractionTexture);
  35519. }
  35520. return results;
  35521. };
  35522. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35523. if (forceDisposeTextures) {
  35524. if (this._albedoTexture) {
  35525. this._albedoTexture.dispose();
  35526. }
  35527. if (this._ambientTexture) {
  35528. this._ambientTexture.dispose();
  35529. }
  35530. if (this._opacityTexture) {
  35531. this._opacityTexture.dispose();
  35532. }
  35533. if (this._reflectionTexture) {
  35534. this._reflectionTexture.dispose();
  35535. }
  35536. if (this._emissiveTexture) {
  35537. this._emissiveTexture.dispose();
  35538. }
  35539. if (this._metallicTexture) {
  35540. this._metallicTexture.dispose();
  35541. }
  35542. if (this._reflectivityTexture) {
  35543. this._reflectivityTexture.dispose();
  35544. }
  35545. if (this._bumpTexture) {
  35546. this._bumpTexture.dispose();
  35547. }
  35548. if (this._lightmapTexture) {
  35549. this._lightmapTexture.dispose();
  35550. }
  35551. if (this._refractionTexture) {
  35552. this._refractionTexture.dispose();
  35553. }
  35554. }
  35555. this._renderTargets.dispose();
  35556. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35557. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35558. }
  35559. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35560. };
  35561. return PBRBaseMaterial;
  35562. }(BABYLON.PushMaterial));
  35563. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35564. __decorate([
  35565. BABYLON.serializeAsImageProcessingConfiguration()
  35566. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35567. __decorate([
  35568. BABYLON.serialize()
  35569. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35570. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35571. })(BABYLON || (BABYLON = {}));
  35572. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35573. var BABYLON;
  35574. (function (BABYLON) {
  35575. var Internals;
  35576. (function (Internals) {
  35577. /**
  35578. * The Physically based simple base material of BJS.
  35579. *
  35580. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35581. * It is used as the base class for both the specGloss and metalRough conventions.
  35582. */
  35583. var PBRBaseSimpleMaterial = (function (_super) {
  35584. __extends(PBRBaseSimpleMaterial, _super);
  35585. /**
  35586. * Instantiates a new PBRMaterial instance.
  35587. *
  35588. * @param name The material name
  35589. * @param scene The scene the material will be use in.
  35590. */
  35591. function PBRBaseSimpleMaterial(name, scene) {
  35592. var _this = _super.call(this, name, scene) || this;
  35593. /**
  35594. * Number of Simultaneous lights allowed on the material.
  35595. */
  35596. _this.maxSimultaneousLights = 4;
  35597. /**
  35598. * If sets to true, disables all the lights affecting the material.
  35599. */
  35600. _this.disableLighting = false;
  35601. /**
  35602. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35603. */
  35604. _this.invertNormalMapX = false;
  35605. /**
  35606. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35607. */
  35608. _this.invertNormalMapY = false;
  35609. /**
  35610. * Emissivie color used to self-illuminate the model.
  35611. */
  35612. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35613. /**
  35614. * Occlusion Channel Strenght.
  35615. */
  35616. _this.occlusionStrength = 1.0;
  35617. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35618. _this._useAmbientInGrayScale = true;
  35619. return _this;
  35620. }
  35621. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35622. /**
  35623. * Gets the current transparency mode.
  35624. */
  35625. get: function () {
  35626. return this._transparencyMode;
  35627. },
  35628. /**
  35629. * Sets the transparency mode of the material.
  35630. */
  35631. set: function (value) {
  35632. if (this._transparencyMode === value) {
  35633. return;
  35634. }
  35635. this._transparencyMode = value;
  35636. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35637. this._forceAlphaTest = true;
  35638. }
  35639. else {
  35640. this._forceAlphaTest = false;
  35641. }
  35642. this._markAllSubMeshesAsTexturesDirty();
  35643. },
  35644. enumerable: true,
  35645. configurable: true
  35646. });
  35647. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35648. /**
  35649. * Gets the current double sided mode.
  35650. */
  35651. get: function () {
  35652. return this._twoSidedLighting;
  35653. },
  35654. /**
  35655. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35656. */
  35657. set: function (value) {
  35658. if (this._twoSidedLighting === value) {
  35659. return;
  35660. }
  35661. this._twoSidedLighting = value;
  35662. this.backFaceCulling = !value;
  35663. this._markAllSubMeshesAsTexturesDirty();
  35664. },
  35665. enumerable: true,
  35666. configurable: true
  35667. });
  35668. /**
  35669. * Specifies wether or not the alpha value of the albedo texture should be used.
  35670. */
  35671. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35672. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35673. };
  35674. /**
  35675. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35676. */
  35677. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35678. if (this._linkRefractionWithTransparency) {
  35679. return false;
  35680. }
  35681. return (this.alpha < 1.0) ||
  35682. (this._shouldUseAlphaFromAlbedoTexture() &&
  35683. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35684. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35685. };
  35686. /**
  35687. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35688. */
  35689. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35690. if (this._linkRefractionWithTransparency) {
  35691. return false;
  35692. }
  35693. return this._shouldUseAlphaFromAlbedoTexture() &&
  35694. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35695. };
  35696. return PBRBaseSimpleMaterial;
  35697. }(BABYLON.PBRBaseMaterial));
  35698. __decorate([
  35699. BABYLON.serialize(),
  35700. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35701. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35702. __decorate([
  35703. BABYLON.serialize(),
  35704. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35705. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35706. __decorate([
  35707. BABYLON.serializeAsTexture(),
  35708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35709. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35710. __decorate([
  35711. BABYLON.serialize(),
  35712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35713. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35714. __decorate([
  35715. BABYLON.serialize(),
  35716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35717. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35718. __decorate([
  35719. BABYLON.serializeAsTexture(),
  35720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35721. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35722. __decorate([
  35723. BABYLON.serializeAsColor3("emissive"),
  35724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35725. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35726. __decorate([
  35727. BABYLON.serializeAsTexture(),
  35728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35729. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35730. __decorate([
  35731. BABYLON.serialize(),
  35732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35733. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35734. __decorate([
  35735. BABYLON.serializeAsTexture(),
  35736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35737. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35738. __decorate([
  35739. BABYLON.serialize(),
  35740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35741. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35742. __decorate([
  35743. BABYLON.serialize()
  35744. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35745. __decorate([
  35746. BABYLON.serialize()
  35747. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35748. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35750. })(BABYLON || (BABYLON = {}));
  35751. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35752. var BABYLON;
  35753. (function (BABYLON) {
  35754. /**
  35755. * The Physically based material of BJS.
  35756. *
  35757. * This offers the main features of a standard PBR material.
  35758. * For more information, please refer to the documentation :
  35759. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35760. */
  35761. var PBRMaterial = (function (_super) {
  35762. __extends(PBRMaterial, _super);
  35763. /**
  35764. * Instantiates a new PBRMaterial instance.
  35765. *
  35766. * @param name The material name
  35767. * @param scene The scene the material will be use in.
  35768. */
  35769. function PBRMaterial(name, scene) {
  35770. var _this = _super.call(this, name, scene) || this;
  35771. /**
  35772. * Intensity of the direct lights e.g. the four lights available in your scene.
  35773. * This impacts both the direct diffuse and specular highlights.
  35774. */
  35775. _this.directIntensity = 1.0;
  35776. /**
  35777. * Intensity of the emissive part of the material.
  35778. * This helps controlling the emissive effect without modifying the emissive color.
  35779. */
  35780. _this.emissiveIntensity = 1.0;
  35781. /**
  35782. * Intensity of the environment e.g. how much the environment will light the object
  35783. * either through harmonics for rough material or through the refelction for shiny ones.
  35784. */
  35785. _this.environmentIntensity = 1.0;
  35786. /**
  35787. * This is a special control allowing the reduction of the specular highlights coming from the
  35788. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35789. */
  35790. _this.specularIntensity = 1.0;
  35791. /**
  35792. * Debug Control allowing disabling the bump map on this material.
  35793. */
  35794. _this.disableBumpMap = false;
  35795. /**
  35796. * AKA Occlusion Texture Intensity in other nomenclature.
  35797. */
  35798. _this.ambientTextureStrength = 1.0;
  35799. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35800. /**
  35801. * AKA Diffuse Color in other nomenclature.
  35802. */
  35803. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35804. /**
  35805. * AKA Specular Color in other nomenclature.
  35806. */
  35807. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35808. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35809. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35810. /**
  35811. * AKA Glossiness in other nomenclature.
  35812. */
  35813. _this.microSurface = 0.9;
  35814. /**
  35815. * source material index of refraction (IOR)' / 'destination material IOR.
  35816. */
  35817. _this.indexOfRefraction = 0.66;
  35818. /**
  35819. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35820. */
  35821. _this.invertRefractionY = false;
  35822. /**
  35823. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35824. * Materials half opaque for instance using refraction could benefit from this control.
  35825. */
  35826. _this.linkRefractionWithTransparency = false;
  35827. _this.useLightmapAsShadowmap = false;
  35828. /**
  35829. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35830. */
  35831. _this.useAlphaFromAlbedoTexture = false;
  35832. /**
  35833. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35834. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35835. */
  35836. _this.useSpecularOverAlpha = true;
  35837. /**
  35838. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35839. */
  35840. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35841. /**
  35842. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35843. */
  35844. _this.useRoughnessFromMetallicTextureAlpha = true;
  35845. /**
  35846. * Specifies if the metallic texture contains the roughness information in its green channel.
  35847. */
  35848. _this.useRoughnessFromMetallicTextureGreen = false;
  35849. /**
  35850. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35851. */
  35852. _this.useMetallnessFromMetallicTextureBlue = false;
  35853. /**
  35854. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35855. */
  35856. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35857. /**
  35858. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35859. */
  35860. _this.useAmbientInGrayScale = false;
  35861. /**
  35862. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35863. * The material will try to infer what glossiness each pixel should be.
  35864. */
  35865. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35866. /**
  35867. * BJS is using an harcoded light falloff based on a manually sets up range.
  35868. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35869. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35870. */
  35871. _this.usePhysicalLightFalloff = true;
  35872. /**
  35873. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35874. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35875. */
  35876. _this.useRadianceOverAlpha = true;
  35877. /**
  35878. * Allows using the bump map in parallax mode.
  35879. */
  35880. _this.useParallax = false;
  35881. /**
  35882. * Allows using the bump map in parallax occlusion mode.
  35883. */
  35884. _this.useParallaxOcclusion = false;
  35885. /**
  35886. * Controls the scale bias of the parallax mode.
  35887. */
  35888. _this.parallaxScaleBias = 0.05;
  35889. /**
  35890. * If sets to true, disables all the lights affecting the material.
  35891. */
  35892. _this.disableLighting = false;
  35893. /**
  35894. * Number of Simultaneous lights allowed on the material.
  35895. */
  35896. _this.maxSimultaneousLights = 4;
  35897. /**
  35898. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35899. */
  35900. _this.invertNormalMapX = false;
  35901. /**
  35902. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35903. */
  35904. _this.invertNormalMapY = false;
  35905. /**
  35906. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35907. */
  35908. _this.twoSidedLighting = false;
  35909. /**
  35910. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  35911. * in your scene composition.
  35912. */
  35913. _this.premultiplyAlpha = false;
  35914. /**
  35915. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35916. * And/Or occlude the blended part.
  35917. */
  35918. _this.useAlphaFresnel = false;
  35919. return _this;
  35920. }
  35921. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35922. /**
  35923. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35924. */
  35925. get: function () {
  35926. return this._PBRMATERIAL_OPAQUE;
  35927. },
  35928. enumerable: true,
  35929. configurable: true
  35930. });
  35931. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35932. /**
  35933. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35934. */
  35935. get: function () {
  35936. return this._PBRMATERIAL_ALPHATEST;
  35937. },
  35938. enumerable: true,
  35939. configurable: true
  35940. });
  35941. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35942. /**
  35943. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35944. */
  35945. get: function () {
  35946. return this._PBRMATERIAL_ALPHABLEND;
  35947. },
  35948. enumerable: true,
  35949. configurable: true
  35950. });
  35951. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35952. /**
  35953. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35954. * They are also discarded below the alpha cutoff threshold to improve performances.
  35955. */
  35956. get: function () {
  35957. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35958. },
  35959. enumerable: true,
  35960. configurable: true
  35961. });
  35962. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  35963. /**
  35964. * Gets the image processing configuration used either in this material.
  35965. */
  35966. get: function () {
  35967. return this._imageProcessingConfiguration;
  35968. },
  35969. /**
  35970. * Sets the Default image processing configuration used either in the this material.
  35971. *
  35972. * If sets to null, the scene one is in use.
  35973. */
  35974. set: function (value) {
  35975. this._attachImageProcessingConfiguration(value);
  35976. // Ensure the effect will be rebuilt.
  35977. this._markAllSubMeshesAsTexturesDirty();
  35978. },
  35979. enumerable: true,
  35980. configurable: true
  35981. });
  35982. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35983. /**
  35984. * Gets wether the color curves effect is enabled.
  35985. */
  35986. get: function () {
  35987. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35988. },
  35989. /**
  35990. * Sets wether the color curves effect is enabled.
  35991. */
  35992. set: function (value) {
  35993. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35994. },
  35995. enumerable: true,
  35996. configurable: true
  35997. });
  35998. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  35999. /**
  36000. * Gets wether the color grading effect is enabled.
  36001. */
  36002. get: function () {
  36003. return this.imageProcessingConfiguration.colorGradingEnabled;
  36004. },
  36005. /**
  36006. * Gets wether the color grading effect is enabled.
  36007. */
  36008. set: function (value) {
  36009. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36010. },
  36011. enumerable: true,
  36012. configurable: true
  36013. });
  36014. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36015. /**
  36016. * Gets wether tonemapping is enabled or not.
  36017. */
  36018. get: function () {
  36019. return this._imageProcessingConfiguration.toneMappingEnabled;
  36020. },
  36021. /**
  36022. * Sets wether tonemapping is enabled or not
  36023. */
  36024. set: function (value) {
  36025. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36026. },
  36027. enumerable: true,
  36028. configurable: true
  36029. });
  36030. ;
  36031. ;
  36032. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36033. /**
  36034. * The camera exposure used on this material.
  36035. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36036. * This corresponds to a photographic exposure.
  36037. */
  36038. get: function () {
  36039. return this._imageProcessingConfiguration.exposure;
  36040. },
  36041. /**
  36042. * The camera exposure used on this material.
  36043. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36044. * This corresponds to a photographic exposure.
  36045. */
  36046. set: function (value) {
  36047. this._imageProcessingConfiguration.exposure = value;
  36048. },
  36049. enumerable: true,
  36050. configurable: true
  36051. });
  36052. ;
  36053. ;
  36054. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36055. /**
  36056. * Gets The camera contrast used on this material.
  36057. */
  36058. get: function () {
  36059. return this._imageProcessingConfiguration.contrast;
  36060. },
  36061. /**
  36062. * Sets The camera contrast used on this material.
  36063. */
  36064. set: function (value) {
  36065. this._imageProcessingConfiguration.contrast = value;
  36066. },
  36067. enumerable: true,
  36068. configurable: true
  36069. });
  36070. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36071. /**
  36072. * Gets the Color Grading 2D Lookup Texture.
  36073. */
  36074. get: function () {
  36075. return this._imageProcessingConfiguration.colorGradingTexture;
  36076. },
  36077. /**
  36078. * Sets the Color Grading 2D Lookup Texture.
  36079. */
  36080. set: function (value) {
  36081. this._imageProcessingConfiguration.colorGradingTexture = value;
  36082. },
  36083. enumerable: true,
  36084. configurable: true
  36085. });
  36086. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36087. /**
  36088. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36089. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36090. * 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;
  36091. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36092. */
  36093. get: function () {
  36094. return this._imageProcessingConfiguration.colorCurves;
  36095. },
  36096. /**
  36097. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36098. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36099. * 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;
  36100. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36101. */
  36102. set: function (value) {
  36103. this._imageProcessingConfiguration.colorCurves = value;
  36104. },
  36105. enumerable: true,
  36106. configurable: true
  36107. });
  36108. PBRMaterial.prototype.getClassName = function () {
  36109. return "PBRMaterial";
  36110. };
  36111. PBRMaterial.prototype.getActiveTextures = function () {
  36112. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36113. if (this._albedoTexture) {
  36114. activeTextures.push(this._albedoTexture);
  36115. }
  36116. if (this._ambientTexture) {
  36117. activeTextures.push(this._ambientTexture);
  36118. }
  36119. if (this._opacityTexture) {
  36120. activeTextures.push(this._opacityTexture);
  36121. }
  36122. if (this._reflectionTexture) {
  36123. activeTextures.push(this._reflectionTexture);
  36124. }
  36125. if (this._emissiveTexture) {
  36126. activeTextures.push(this._emissiveTexture);
  36127. }
  36128. if (this._reflectionTexture) {
  36129. activeTextures.push(this._reflectionTexture);
  36130. }
  36131. if (this._metallicTexture) {
  36132. activeTextures.push(this._metallicTexture);
  36133. }
  36134. if (this._microSurfaceTexture) {
  36135. activeTextures.push(this._microSurfaceTexture);
  36136. }
  36137. if (this._bumpTexture) {
  36138. activeTextures.push(this._bumpTexture);
  36139. }
  36140. if (this._lightmapTexture) {
  36141. activeTextures.push(this._lightmapTexture);
  36142. }
  36143. if (this._refractionTexture) {
  36144. activeTextures.push(this._refractionTexture);
  36145. }
  36146. return activeTextures;
  36147. };
  36148. PBRMaterial.prototype.clone = function (name) {
  36149. var _this = this;
  36150. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36151. };
  36152. PBRMaterial.prototype.serialize = function () {
  36153. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36154. serializationObject.customType = "BABYLON.PBRMaterial";
  36155. return serializationObject;
  36156. };
  36157. // Statics
  36158. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36159. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36160. };
  36161. return PBRMaterial;
  36162. }(BABYLON.PBRBaseMaterial));
  36163. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36164. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36165. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36166. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36167. __decorate([
  36168. BABYLON.serialize(),
  36169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36170. ], PBRMaterial.prototype, "directIntensity", void 0);
  36171. __decorate([
  36172. BABYLON.serialize(),
  36173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36174. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36175. __decorate([
  36176. BABYLON.serialize(),
  36177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36178. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36179. __decorate([
  36180. BABYLON.serialize(),
  36181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36182. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36183. __decorate([
  36184. BABYLON.serialize(),
  36185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36186. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36187. __decorate([
  36188. BABYLON.serializeAsTexture(),
  36189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36190. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36191. __decorate([
  36192. BABYLON.serializeAsTexture(),
  36193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36194. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36195. __decorate([
  36196. BABYLON.serialize(),
  36197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36198. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36199. __decorate([
  36200. BABYLON.serializeAsTexture(),
  36201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36202. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36203. __decorate([
  36204. BABYLON.serializeAsTexture(),
  36205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36206. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36207. __decorate([
  36208. BABYLON.serializeAsTexture(),
  36209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36210. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36211. __decorate([
  36212. BABYLON.serializeAsTexture(),
  36213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36214. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36215. __decorate([
  36216. BABYLON.serializeAsTexture(),
  36217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36218. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36219. __decorate([
  36220. BABYLON.serialize(),
  36221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36222. ], PBRMaterial.prototype, "metallic", void 0);
  36223. __decorate([
  36224. BABYLON.serialize(),
  36225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36226. ], PBRMaterial.prototype, "roughness", void 0);
  36227. __decorate([
  36228. BABYLON.serializeAsTexture(),
  36229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36230. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36231. __decorate([
  36232. BABYLON.serializeAsTexture(),
  36233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36234. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36235. __decorate([
  36236. BABYLON.serializeAsTexture(),
  36237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36238. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36239. __decorate([
  36240. BABYLON.serializeAsTexture(),
  36241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36242. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36243. __decorate([
  36244. BABYLON.serializeAsColor3("ambient"),
  36245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36246. ], PBRMaterial.prototype, "ambientColor", void 0);
  36247. __decorate([
  36248. BABYLON.serializeAsColor3("albedo"),
  36249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36250. ], PBRMaterial.prototype, "albedoColor", void 0);
  36251. __decorate([
  36252. BABYLON.serializeAsColor3("reflectivity"),
  36253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36254. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36255. __decorate([
  36256. BABYLON.serializeAsColor3("reflection"),
  36257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36258. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36259. __decorate([
  36260. BABYLON.serializeAsColor3("emissive"),
  36261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36262. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36263. __decorate([
  36264. BABYLON.serialize(),
  36265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36266. ], PBRMaterial.prototype, "microSurface", void 0);
  36267. __decorate([
  36268. BABYLON.serialize(),
  36269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36270. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36271. __decorate([
  36272. BABYLON.serialize(),
  36273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36274. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36275. __decorate([
  36276. BABYLON.serialize(),
  36277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36278. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36279. __decorate([
  36280. BABYLON.serialize(),
  36281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36282. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36283. __decorate([
  36284. BABYLON.serialize(),
  36285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36286. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36287. __decorate([
  36288. BABYLON.serialize(),
  36289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36290. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36291. __decorate([
  36292. BABYLON.serialize(),
  36293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36294. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36295. __decorate([
  36296. BABYLON.serialize(),
  36297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36298. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36299. __decorate([
  36300. BABYLON.serialize(),
  36301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36302. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36303. __decorate([
  36304. BABYLON.serialize(),
  36305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36306. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36307. __decorate([
  36308. BABYLON.serialize(),
  36309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36310. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36311. __decorate([
  36312. BABYLON.serialize(),
  36313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36314. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36315. __decorate([
  36316. BABYLON.serialize(),
  36317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36318. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36319. __decorate([
  36320. BABYLON.serialize(),
  36321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36322. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36323. __decorate([
  36324. BABYLON.serialize(),
  36325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36326. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36327. __decorate([
  36328. BABYLON.serialize(),
  36329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36330. ], PBRMaterial.prototype, "useParallax", void 0);
  36331. __decorate([
  36332. BABYLON.serialize(),
  36333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36334. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36335. __decorate([
  36336. BABYLON.serialize(),
  36337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36338. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36339. __decorate([
  36340. BABYLON.serialize(),
  36341. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36342. ], PBRMaterial.prototype, "disableLighting", void 0);
  36343. __decorate([
  36344. BABYLON.serialize(),
  36345. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36346. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36347. __decorate([
  36348. BABYLON.serialize(),
  36349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36350. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36351. __decorate([
  36352. BABYLON.serialize(),
  36353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36354. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36355. __decorate([
  36356. BABYLON.serialize(),
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36358. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36359. __decorate([
  36360. BABYLON.serialize(),
  36361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36362. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  36363. __decorate([
  36364. BABYLON.serialize(),
  36365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36366. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36367. BABYLON.PBRMaterial = PBRMaterial;
  36368. })(BABYLON || (BABYLON = {}));
  36369. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36370. var BABYLON;
  36371. (function (BABYLON) {
  36372. /**
  36373. * The PBR material of BJS following the metal roughness convention.
  36374. *
  36375. * This fits to the define PBR convention in the GLTF definition:
  36376. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36377. */
  36378. var PBRMetallicRoughnessMaterial = (function (_super) {
  36379. __extends(PBRMetallicRoughnessMaterial, _super);
  36380. /**
  36381. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36382. *
  36383. * @param name The material name
  36384. * @param scene The scene the material will be use in.
  36385. */
  36386. function PBRMetallicRoughnessMaterial(name, scene) {
  36387. var _this = _super.call(this, name, scene) || this;
  36388. _this._useRoughnessFromMetallicTextureGreen = true;
  36389. _this._useMetallnessFromMetallicTextureBlue = true;
  36390. return _this;
  36391. }
  36392. /**
  36393. * Return the currrent class name of the material.
  36394. */
  36395. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36396. return "PBRMetallicRoughnessMaterial";
  36397. };
  36398. /**
  36399. * Return the active textures of the material.
  36400. */
  36401. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36402. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36403. if (this.baseTexture) {
  36404. activeTextures.push(this.baseTexture);
  36405. }
  36406. if (this.metallicRoughnessTexture) {
  36407. activeTextures.push(this.metallicRoughnessTexture);
  36408. }
  36409. return activeTextures;
  36410. };
  36411. /**
  36412. * Serialize the material to a parsable JSON object.
  36413. */
  36414. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36415. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36416. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36417. return serializationObject;
  36418. };
  36419. /**
  36420. * Parses a JSON object correponding to the serialize function.
  36421. */
  36422. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36423. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36424. };
  36425. return PBRMetallicRoughnessMaterial;
  36426. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36427. __decorate([
  36428. BABYLON.serializeAsTexture(),
  36429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36430. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36431. __decorate([
  36432. BABYLON.serializeAsTexture(),
  36433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36434. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36435. __decorate([
  36436. BABYLON.serialize(),
  36437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36438. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36439. __decorate([
  36440. BABYLON.serialize(),
  36441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36442. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36443. __decorate([
  36444. BABYLON.serializeAsTexture(),
  36445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36446. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36447. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36448. })(BABYLON || (BABYLON = {}));
  36449. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36450. var BABYLON;
  36451. (function (BABYLON) {
  36452. /**
  36453. * The PBR material of BJS following the specular glossiness convention.
  36454. *
  36455. * This fits to the define PBR convention in the GLTF definition:
  36456. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36457. */
  36458. var PBRSpecularGlossinessMaterial = (function (_super) {
  36459. __extends(PBRSpecularGlossinessMaterial, _super);
  36460. /**
  36461. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36462. *
  36463. * @param name The material name
  36464. * @param scene The scene the material will be use in.
  36465. */
  36466. function PBRSpecularGlossinessMaterial(name, scene) {
  36467. var _this = _super.call(this, name, scene) || this;
  36468. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36469. return _this;
  36470. }
  36471. /**
  36472. * Return the currrent class name of the material.
  36473. */
  36474. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36475. return "PBRSpecularGlossinessMaterial";
  36476. };
  36477. /**
  36478. * Return the active textures of the material.
  36479. */
  36480. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36481. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36482. if (this.diffuseTexture) {
  36483. activeTextures.push(this.diffuseTexture);
  36484. }
  36485. if (this.specularGlossinessTexture) {
  36486. activeTextures.push(this.specularGlossinessTexture);
  36487. }
  36488. return activeTextures;
  36489. };
  36490. /**
  36491. * Serialize the material to a parsable JSON object.
  36492. */
  36493. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36494. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36495. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36496. return serializationObject;
  36497. };
  36498. /**
  36499. * Parses a JSON object correponding to the serialize function.
  36500. */
  36501. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36502. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36503. };
  36504. return PBRSpecularGlossinessMaterial;
  36505. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36506. __decorate([
  36507. BABYLON.serializeAsColor3(),
  36508. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36509. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36510. __decorate([
  36511. BABYLON.serializeAsTexture(),
  36512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36513. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36514. __decorate([
  36515. BABYLON.serializeAsColor3(),
  36516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36517. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36518. __decorate([
  36519. BABYLON.serialize(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36521. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36522. __decorate([
  36523. BABYLON.serializeAsTexture(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36525. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36526. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36527. })(BABYLON || (BABYLON = {}));
  36528. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36529. var BABYLON;
  36530. (function (BABYLON) {
  36531. var ShaderMaterial = (function (_super) {
  36532. __extends(ShaderMaterial, _super);
  36533. function ShaderMaterial(name, scene, shaderPath, options) {
  36534. var _this = _super.call(this, name, scene) || this;
  36535. _this._textures = {};
  36536. _this._textureArrays = {};
  36537. _this._floats = {};
  36538. _this._floatsArrays = {};
  36539. _this._colors3 = {};
  36540. _this._colors4 = {};
  36541. _this._vectors2 = {};
  36542. _this._vectors3 = {};
  36543. _this._vectors4 = {};
  36544. _this._matrices = {};
  36545. _this._matrices3x3 = {};
  36546. _this._matrices2x2 = {};
  36547. _this._vectors3Arrays = {};
  36548. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  36549. _this._shaderPath = shaderPath;
  36550. options.needAlphaBlending = options.needAlphaBlending || false;
  36551. options.needAlphaTesting = options.needAlphaTesting || false;
  36552. options.attributes = options.attributes || ["position", "normal", "uv"];
  36553. options.uniforms = options.uniforms || ["worldViewProjection"];
  36554. options.uniformBuffers = options.uniformBuffers || [];
  36555. options.samplers = options.samplers || [];
  36556. options.defines = options.defines || [];
  36557. _this._options = options;
  36558. return _this;
  36559. }
  36560. ShaderMaterial.prototype.getClassName = function () {
  36561. return "ShaderMaterial";
  36562. };
  36563. ShaderMaterial.prototype.needAlphaBlending = function () {
  36564. return this._options.needAlphaBlending;
  36565. };
  36566. ShaderMaterial.prototype.needAlphaTesting = function () {
  36567. return this._options.needAlphaTesting;
  36568. };
  36569. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  36570. if (this._options.uniforms.indexOf(uniformName) === -1) {
  36571. this._options.uniforms.push(uniformName);
  36572. }
  36573. };
  36574. ShaderMaterial.prototype.setTexture = function (name, texture) {
  36575. if (this._options.samplers.indexOf(name) === -1) {
  36576. this._options.samplers.push(name);
  36577. }
  36578. this._textures[name] = texture;
  36579. return this;
  36580. };
  36581. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  36582. if (this._options.samplers.indexOf(name) === -1) {
  36583. this._options.samplers.push(name);
  36584. }
  36585. this._checkUniform(name);
  36586. this._textureArrays[name] = textures;
  36587. return this;
  36588. };
  36589. ShaderMaterial.prototype.setFloat = function (name, value) {
  36590. this._checkUniform(name);
  36591. this._floats[name] = value;
  36592. return this;
  36593. };
  36594. ShaderMaterial.prototype.setFloats = function (name, value) {
  36595. this._checkUniform(name);
  36596. this._floatsArrays[name] = value;
  36597. return this;
  36598. };
  36599. ShaderMaterial.prototype.setColor3 = function (name, value) {
  36600. this._checkUniform(name);
  36601. this._colors3[name] = value;
  36602. return this;
  36603. };
  36604. ShaderMaterial.prototype.setColor4 = function (name, value) {
  36605. this._checkUniform(name);
  36606. this._colors4[name] = value;
  36607. return this;
  36608. };
  36609. ShaderMaterial.prototype.setVector2 = function (name, value) {
  36610. this._checkUniform(name);
  36611. this._vectors2[name] = value;
  36612. return this;
  36613. };
  36614. ShaderMaterial.prototype.setVector3 = function (name, value) {
  36615. this._checkUniform(name);
  36616. this._vectors3[name] = value;
  36617. return this;
  36618. };
  36619. ShaderMaterial.prototype.setVector4 = function (name, value) {
  36620. this._checkUniform(name);
  36621. this._vectors4[name] = value;
  36622. return this;
  36623. };
  36624. ShaderMaterial.prototype.setMatrix = function (name, value) {
  36625. this._checkUniform(name);
  36626. this._matrices[name] = value;
  36627. return this;
  36628. };
  36629. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  36630. this._checkUniform(name);
  36631. this._matrices3x3[name] = value;
  36632. return this;
  36633. };
  36634. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  36635. this._checkUniform(name);
  36636. this._matrices2x2[name] = value;
  36637. return this;
  36638. };
  36639. ShaderMaterial.prototype.setArray3 = function (name, value) {
  36640. this._checkUniform(name);
  36641. this._vectors3Arrays[name] = value;
  36642. return this;
  36643. };
  36644. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  36645. if (!mesh) {
  36646. return true;
  36647. }
  36648. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  36649. return false;
  36650. }
  36651. return false;
  36652. };
  36653. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  36654. var scene = this.getScene();
  36655. var engine = scene.getEngine();
  36656. if (!this.checkReadyOnEveryCall) {
  36657. if (this._renderId === scene.getRenderId()) {
  36658. if (this._checkCache(scene, mesh, useInstances)) {
  36659. return true;
  36660. }
  36661. }
  36662. }
  36663. // Instances
  36664. var defines = [];
  36665. var attribs = [];
  36666. var fallbacks = new BABYLON.EffectFallbacks();
  36667. if (useInstances) {
  36668. defines.push("#define INSTANCES");
  36669. }
  36670. for (var index = 0; index < this._options.defines.length; index++) {
  36671. defines.push(this._options.defines[index]);
  36672. }
  36673. for (var index = 0; index < this._options.attributes.length; index++) {
  36674. attribs.push(this._options.attributes[index]);
  36675. }
  36676. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36677. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36678. defines.push("#define VERTEXCOLOR");
  36679. }
  36680. // Bones
  36681. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  36682. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36683. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36684. if (mesh.numBoneInfluencers > 4) {
  36685. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36686. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36687. }
  36688. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36689. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36690. fallbacks.addCPUSkinningFallback(0, mesh);
  36691. if (this._options.uniforms.indexOf("mBones") === -1) {
  36692. this._options.uniforms.push("mBones");
  36693. }
  36694. }
  36695. else {
  36696. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36697. }
  36698. // Textures
  36699. for (var name in this._textures) {
  36700. if (!this._textures[name].isReady()) {
  36701. return false;
  36702. }
  36703. }
  36704. // Alpha test
  36705. if (engine.getAlphaTesting()) {
  36706. defines.push("#define ALPHATEST");
  36707. }
  36708. var previousEffect = this._effect;
  36709. var join = defines.join("\n");
  36710. this._effect = engine.createEffect(this._shaderPath, {
  36711. attributes: attribs,
  36712. uniformsNames: this._options.uniforms,
  36713. uniformBuffersNames: this._options.uniformBuffers,
  36714. samplers: this._options.samplers,
  36715. defines: join,
  36716. fallbacks: fallbacks,
  36717. onCompiled: this.onCompiled,
  36718. onError: this.onError
  36719. }, engine);
  36720. if (!this._effect.isReady()) {
  36721. return false;
  36722. }
  36723. if (previousEffect !== this._effect) {
  36724. scene.resetCachedMaterial();
  36725. }
  36726. this._renderId = scene.getRenderId();
  36727. return true;
  36728. };
  36729. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36730. var scene = this.getScene();
  36731. if (this._options.uniforms.indexOf("world") !== -1) {
  36732. this._effect.setMatrix("world", world);
  36733. }
  36734. if (this._options.uniforms.indexOf("worldView") !== -1) {
  36735. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  36736. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  36737. }
  36738. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  36739. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  36740. }
  36741. };
  36742. ShaderMaterial.prototype.bind = function (world, mesh) {
  36743. // Std values
  36744. this.bindOnlyWorldMatrix(world);
  36745. if (this.getScene().getCachedMaterial() !== this) {
  36746. if (this._options.uniforms.indexOf("view") !== -1) {
  36747. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  36748. }
  36749. if (this._options.uniforms.indexOf("projection") !== -1) {
  36750. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  36751. }
  36752. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  36753. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36754. }
  36755. // Bones
  36756. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  36757. var name;
  36758. // Texture
  36759. for (name in this._textures) {
  36760. this._effect.setTexture(name, this._textures[name]);
  36761. }
  36762. // Texture arrays
  36763. for (name in this._textureArrays) {
  36764. this._effect.setTextureArray(name, this._textureArrays[name]);
  36765. }
  36766. // Float
  36767. for (name in this._floats) {
  36768. this._effect.setFloat(name, this._floats[name]);
  36769. }
  36770. // Float s
  36771. for (name in this._floatsArrays) {
  36772. this._effect.setArray(name, this._floatsArrays[name]);
  36773. }
  36774. // Color3
  36775. for (name in this._colors3) {
  36776. this._effect.setColor3(name, this._colors3[name]);
  36777. }
  36778. // Color4
  36779. for (name in this._colors4) {
  36780. var color = this._colors4[name];
  36781. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  36782. }
  36783. // Vector2
  36784. for (name in this._vectors2) {
  36785. this._effect.setVector2(name, this._vectors2[name]);
  36786. }
  36787. // Vector3
  36788. for (name in this._vectors3) {
  36789. this._effect.setVector3(name, this._vectors3[name]);
  36790. }
  36791. // Vector4
  36792. for (name in this._vectors4) {
  36793. this._effect.setVector4(name, this._vectors4[name]);
  36794. }
  36795. // Matrix
  36796. for (name in this._matrices) {
  36797. this._effect.setMatrix(name, this._matrices[name]);
  36798. }
  36799. // Matrix 3x3
  36800. for (name in this._matrices3x3) {
  36801. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  36802. }
  36803. // Matrix 2x2
  36804. for (name in this._matrices2x2) {
  36805. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  36806. }
  36807. // Vector3Array
  36808. for (name in this._vectors3Arrays) {
  36809. this._effect.setArray3(name, this._vectors3Arrays[name]);
  36810. }
  36811. }
  36812. this._afterBind(mesh);
  36813. };
  36814. ShaderMaterial.prototype.getActiveTextures = function () {
  36815. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36816. for (var name in this._textures) {
  36817. activeTextures.push(this._textures[name]);
  36818. }
  36819. for (var name in this._textureArrays) {
  36820. var array = this._textureArrays[name];
  36821. for (var index = 0; index < array.length; index++) {
  36822. activeTextures.push(array[index]);
  36823. }
  36824. }
  36825. return activeTextures;
  36826. };
  36827. ShaderMaterial.prototype.clone = function (name) {
  36828. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  36829. return newShaderMaterial;
  36830. };
  36831. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36832. if (forceDisposeTextures) {
  36833. var name;
  36834. for (name in this._textures) {
  36835. this._textures[name].dispose();
  36836. }
  36837. for (name in this._textureArrays) {
  36838. var array = this._textureArrays[name];
  36839. for (var index = 0; index < array.length; index++) {
  36840. array[index].dispose();
  36841. }
  36842. }
  36843. }
  36844. this._textures = {};
  36845. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36846. };
  36847. ShaderMaterial.prototype.serialize = function () {
  36848. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36849. serializationObject.customType = "BABYLON.ShaderMaterial";
  36850. serializationObject.options = this._options;
  36851. serializationObject.shaderPath = this._shaderPath;
  36852. var name;
  36853. // Texture
  36854. serializationObject.textures = {};
  36855. for (name in this._textures) {
  36856. serializationObject.textures[name] = this._textures[name].serialize();
  36857. }
  36858. // Texture arrays
  36859. serializationObject.textureArrays = {};
  36860. for (name in this._textureArrays) {
  36861. serializationObject.textureArrays[name] = [];
  36862. var array = this._textureArrays[name];
  36863. for (var index = 0; index < array.length; index++) {
  36864. serializationObject.textureArrays[name].push(array[index].serialize());
  36865. }
  36866. }
  36867. // Float
  36868. serializationObject.floats = {};
  36869. for (name in this._floats) {
  36870. serializationObject.floats[name] = this._floats[name];
  36871. }
  36872. // Float s
  36873. serializationObject.floatArrays = {};
  36874. for (name in this._floatsArrays) {
  36875. serializationObject.floatArrays[name] = this._floatsArrays[name];
  36876. }
  36877. // Color3
  36878. serializationObject.colors3 = {};
  36879. for (name in this._colors3) {
  36880. serializationObject.colors3[name] = this._colors3[name].asArray();
  36881. }
  36882. // Color4
  36883. serializationObject.colors4 = {};
  36884. for (name in this._colors4) {
  36885. serializationObject.colors4[name] = this._colors4[name].asArray();
  36886. }
  36887. // Vector2
  36888. serializationObject.vectors2 = {};
  36889. for (name in this._vectors2) {
  36890. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  36891. }
  36892. // Vector3
  36893. serializationObject.vectors3 = {};
  36894. for (name in this._vectors3) {
  36895. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  36896. }
  36897. // Vector4
  36898. serializationObject.vectors4 = {};
  36899. for (name in this._vectors4) {
  36900. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  36901. }
  36902. // Matrix
  36903. serializationObject.matrices = {};
  36904. for (name in this._matrices) {
  36905. serializationObject.matrices[name] = this._matrices[name].asArray();
  36906. }
  36907. // Matrix 3x3
  36908. serializationObject.matrices3x3 = {};
  36909. for (name in this._matrices3x3) {
  36910. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  36911. }
  36912. // Matrix 2x2
  36913. serializationObject.matrices2x2 = {};
  36914. for (name in this._matrices2x2) {
  36915. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  36916. }
  36917. // Vector3Array
  36918. serializationObject.vectors3Arrays = {};
  36919. for (name in this._vectors3Arrays) {
  36920. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  36921. }
  36922. return serializationObject;
  36923. };
  36924. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  36925. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  36926. var name;
  36927. // Texture
  36928. for (name in source.textures) {
  36929. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  36930. }
  36931. // Texture arrays
  36932. for (name in source.textureArrays) {
  36933. var array = source.textureArrays[name];
  36934. var textureArray = new Array();
  36935. for (var index = 0; index < array.length; index++) {
  36936. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  36937. }
  36938. material.setTextureArray(name, textureArray);
  36939. }
  36940. // Float
  36941. for (name in source.floats) {
  36942. material.setFloat(name, source.floats[name]);
  36943. }
  36944. // Float s
  36945. for (name in source.floatsArrays) {
  36946. material.setFloats(name, source.floatsArrays[name]);
  36947. }
  36948. // Color3
  36949. for (name in source.colors3) {
  36950. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  36951. }
  36952. // Color4
  36953. for (name in source.colors4) {
  36954. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  36955. }
  36956. // Vector2
  36957. for (name in source.vectors2) {
  36958. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  36959. }
  36960. // Vector3
  36961. for (name in source.vectors3) {
  36962. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  36963. }
  36964. // Vector4
  36965. for (name in source.vectors4) {
  36966. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  36967. }
  36968. // Matrix
  36969. for (name in source.matrices) {
  36970. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  36971. }
  36972. // Matrix 3x3
  36973. for (name in source.matrices3x3) {
  36974. material.setMatrix3x3(name, source.matrices3x3[name]);
  36975. }
  36976. // Matrix 2x2
  36977. for (name in source.matrices2x2) {
  36978. material.setMatrix2x2(name, source.matrices2x2[name]);
  36979. }
  36980. // Vector3Array
  36981. for (name in source.vectors3Arrays) {
  36982. material.setArray3(name, source.vectors3Arrays[name]);
  36983. }
  36984. return material;
  36985. };
  36986. return ShaderMaterial;
  36987. }(BABYLON.Material));
  36988. BABYLON.ShaderMaterial = ShaderMaterial;
  36989. })(BABYLON || (BABYLON = {}));
  36990. //# sourceMappingURL=babylon.shaderMaterial.js.map
  36991. var BABYLON;
  36992. (function (BABYLON) {
  36993. var MeshBuilder = (function () {
  36994. function MeshBuilder() {
  36995. }
  36996. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  36997. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  36998. return BABYLON.Mesh.DOUBLESIDE;
  36999. }
  37000. if (orientation === undefined || orientation === null) {
  37001. return BABYLON.Mesh.FRONTSIDE;
  37002. }
  37003. return orientation;
  37004. };
  37005. /**
  37006. * Creates a box mesh.
  37007. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37008. * The parameter `size` sets the size (float) of each box side (default 1).
  37009. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37010. * 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).
  37011. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37013. * 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).
  37014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37016. */
  37017. MeshBuilder.CreateBox = function (name, options, scene) {
  37018. var box = new BABYLON.Mesh(name, scene);
  37019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37020. box.sideOrientation = options.sideOrientation;
  37021. var vertexData = BABYLON.VertexData.CreateBox(options);
  37022. vertexData.applyToMesh(box, options.updatable);
  37023. return box;
  37024. };
  37025. /**
  37026. * Creates a sphere mesh.
  37027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37028. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37029. * 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`).
  37030. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37031. * 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
  37032. * 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).
  37033. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37034. * 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).
  37035. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37036. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37037. */
  37038. MeshBuilder.CreateSphere = function (name, options, scene) {
  37039. var sphere = new BABYLON.Mesh(name, scene);
  37040. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37041. sphere.sideOrientation = options.sideOrientation;
  37042. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37043. vertexData.applyToMesh(sphere, options.updatable);
  37044. return sphere;
  37045. };
  37046. /**
  37047. * Creates a plane polygonal mesh. By default, this is a disc.
  37048. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37049. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37050. * 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.
  37051. * 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
  37052. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37053. * 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).
  37054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37056. */
  37057. MeshBuilder.CreateDisc = function (name, options, scene) {
  37058. var disc = new BABYLON.Mesh(name, scene);
  37059. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37060. disc.sideOrientation = options.sideOrientation;
  37061. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37062. vertexData.applyToMesh(disc, options.updatable);
  37063. return disc;
  37064. };
  37065. /**
  37066. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37067. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37068. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37069. * 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`).
  37070. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37071. * 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.
  37072. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37073. * 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).
  37074. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37076. */
  37077. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37078. var sphere = new BABYLON.Mesh(name, scene);
  37079. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37080. sphere.sideOrientation = options.sideOrientation;
  37081. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37082. vertexData.applyToMesh(sphere, options.updatable);
  37083. return sphere;
  37084. };
  37085. ;
  37086. /**
  37087. * Creates a ribbon mesh.
  37088. * 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.
  37089. *
  37090. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37091. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37092. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37093. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37094. * 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.
  37095. * 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.
  37096. * 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
  37097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37098. * 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).
  37099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37100. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37101. * 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.
  37102. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37103. * 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
  37104. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37105. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37107. */
  37108. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37109. var pathArray = options.pathArray;
  37110. var closeArray = options.closeArray;
  37111. var closePath = options.closePath;
  37112. var offset = options.offset;
  37113. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37114. var instance = options.instance;
  37115. var updatable = options.updatable;
  37116. if (instance) {
  37117. // positionFunction : ribbon case
  37118. // only pathArray and sideOrientation parameters are taken into account for positions update
  37119. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37120. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37121. var positionFunction = function (positions) {
  37122. var minlg = pathArray[0].length;
  37123. var i = 0;
  37124. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37125. for (var si = 1; si <= ns; si++) {
  37126. for (var p = 0; p < pathArray.length; p++) {
  37127. var path = pathArray[p];
  37128. var l = path.length;
  37129. minlg = (minlg < l) ? minlg : l;
  37130. var j = 0;
  37131. while (j < minlg) {
  37132. positions[i] = path[j].x;
  37133. positions[i + 1] = path[j].y;
  37134. positions[i + 2] = path[j].z;
  37135. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37136. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37137. }
  37138. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37139. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37140. }
  37141. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37142. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37143. }
  37144. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37145. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37146. }
  37147. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37148. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37149. }
  37150. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37151. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37152. }
  37153. j++;
  37154. i += 3;
  37155. }
  37156. if (instance._closePath) {
  37157. positions[i] = path[0].x;
  37158. positions[i + 1] = path[0].y;
  37159. positions[i + 2] = path[0].z;
  37160. i += 3;
  37161. }
  37162. }
  37163. }
  37164. };
  37165. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37166. positionFunction(positions);
  37167. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37168. instance._boundingInfo.update(instance._worldMatrix);
  37169. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37170. if (options.colors) {
  37171. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37172. for (var c = 0; c < options.colors.length; c++) {
  37173. colors[c * 4] = options.colors[c].r;
  37174. colors[c * 4 + 1] = options.colors[c].g;
  37175. colors[c * 4 + 2] = options.colors[c].b;
  37176. colors[c * 4 + 3] = options.colors[c].a;
  37177. }
  37178. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37179. }
  37180. if (options.uvs) {
  37181. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37182. for (var i = 0; i < options.uvs.length; i++) {
  37183. uvs[i * 2] = options.uvs[i].x;
  37184. uvs[i * 2 + 1] = options.uvs[i].y;
  37185. }
  37186. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37187. }
  37188. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37189. var indices = instance.getIndices();
  37190. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37191. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37192. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37193. if (instance._closePath) {
  37194. var indexFirst = 0;
  37195. var indexLast = 0;
  37196. for (var p = 0; p < pathArray.length; p++) {
  37197. indexFirst = instance._idx[p] * 3;
  37198. if (p + 1 < pathArray.length) {
  37199. indexLast = (instance._idx[p + 1] - 1) * 3;
  37200. }
  37201. else {
  37202. indexLast = normals.length - 3;
  37203. }
  37204. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37205. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37206. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37207. normals[indexLast] = normals[indexFirst];
  37208. normals[indexLast + 1] = normals[indexFirst + 1];
  37209. normals[indexLast + 2] = normals[indexFirst + 2];
  37210. }
  37211. }
  37212. if (!(instance.areNormalsFrozen)) {
  37213. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37214. }
  37215. }
  37216. return instance;
  37217. }
  37218. else {
  37219. var ribbon = new BABYLON.Mesh(name, scene);
  37220. ribbon.sideOrientation = sideOrientation;
  37221. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37222. if (closePath) {
  37223. ribbon._idx = vertexData._idx;
  37224. }
  37225. ribbon._closePath = closePath;
  37226. ribbon._closeArray = closeArray;
  37227. vertexData.applyToMesh(ribbon, updatable);
  37228. return ribbon;
  37229. }
  37230. };
  37231. /**
  37232. * Creates a cylinder or a cone mesh.
  37233. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37234. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37235. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37236. * 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.
  37237. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37238. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37239. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37240. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37241. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37242. * 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).
  37243. * 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
  37244. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37245. * 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
  37246. * 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.
  37247. * If `enclose` is false, a ring surface is one element.
  37248. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37249. * 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
  37250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37251. * 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).
  37252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37254. */
  37255. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37256. var cylinder = new BABYLON.Mesh(name, scene);
  37257. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37258. cylinder.sideOrientation = options.sideOrientation;
  37259. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37260. vertexData.applyToMesh(cylinder, options.updatable);
  37261. return cylinder;
  37262. };
  37263. /**
  37264. * Creates a torus mesh.
  37265. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37266. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37267. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37268. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37270. * 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).
  37271. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37272. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37273. */
  37274. MeshBuilder.CreateTorus = function (name, options, scene) {
  37275. var torus = new BABYLON.Mesh(name, scene);
  37276. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37277. torus.sideOrientation = options.sideOrientation;
  37278. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37279. vertexData.applyToMesh(torus, options.updatable);
  37280. return torus;
  37281. };
  37282. /**
  37283. * Creates a torus knot mesh.
  37284. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37285. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37286. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37287. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37288. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37290. * 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).
  37291. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37292. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37293. */
  37294. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37295. var torusKnot = new BABYLON.Mesh(name, scene);
  37296. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37297. torusKnot.sideOrientation = options.sideOrientation;
  37298. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37299. vertexData.applyToMesh(torusKnot, options.updatable);
  37300. return torusKnot;
  37301. };
  37302. /**
  37303. * Creates a line system mesh.
  37304. * A line system is a pool of many lines gathered in a single mesh.
  37305. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37306. * 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.
  37307. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37308. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  37309. * 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
  37310. * 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
  37311. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  37312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37313. */
  37314. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  37315. var instance = options.instance;
  37316. var lines = options.lines;
  37317. if (instance) {
  37318. var positionFunction = function (positions) {
  37319. var i = 0;
  37320. for (var l = 0; l < lines.length; l++) {
  37321. var points = lines[l];
  37322. for (var p = 0; p < points.length; p++) {
  37323. positions[i] = points[p].x;
  37324. positions[i + 1] = points[p].y;
  37325. positions[i + 2] = points[p].z;
  37326. i += 3;
  37327. }
  37328. }
  37329. };
  37330. instance.updateMeshPositions(positionFunction, false);
  37331. return instance;
  37332. }
  37333. // line system creation
  37334. var lineSystem = new BABYLON.LinesMesh(name, scene);
  37335. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  37336. vertexData.applyToMesh(lineSystem, options.updatable);
  37337. return lineSystem;
  37338. };
  37339. /**
  37340. * Creates a line mesh.
  37341. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  37342. * 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.
  37343. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37344. * The parameter `points` is an array successive Vector3.
  37345. * 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
  37346. * When updating an instance, remember that only point positions can change, not the number of points.
  37347. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37348. */
  37349. MeshBuilder.CreateLines = function (name, options, scene) {
  37350. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  37351. return lines;
  37352. };
  37353. /**
  37354. * Creates a dashed line mesh.
  37355. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  37356. * 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.
  37357. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37358. * The parameter `points` is an array successive Vector3.
  37359. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  37360. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  37361. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  37362. * 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
  37363. * When updating an instance, remember that only point positions can change, not the number of points.
  37364. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37365. */
  37366. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  37367. var points = options.points;
  37368. var instance = options.instance;
  37369. var gapSize = options.gapSize;
  37370. var dashNb = options.dashNb;
  37371. var dashSize = options.dashSize;
  37372. if (instance) {
  37373. var positionFunction = function (positions) {
  37374. var curvect = BABYLON.Vector3.Zero();
  37375. var nbSeg = positions.length / 6;
  37376. var lg = 0;
  37377. var nb = 0;
  37378. var shft = 0;
  37379. var dashshft = 0;
  37380. var curshft = 0;
  37381. var p = 0;
  37382. var i = 0;
  37383. var j = 0;
  37384. for (i = 0; i < points.length - 1; i++) {
  37385. points[i + 1].subtractToRef(points[i], curvect);
  37386. lg += curvect.length();
  37387. }
  37388. shft = lg / nbSeg;
  37389. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  37390. for (i = 0; i < points.length - 1; i++) {
  37391. points[i + 1].subtractToRef(points[i], curvect);
  37392. nb = Math.floor(curvect.length() / shft);
  37393. curvect.normalize();
  37394. j = 0;
  37395. while (j < nb && p < positions.length) {
  37396. curshft = shft * j;
  37397. positions[p] = points[i].x + curshft * curvect.x;
  37398. positions[p + 1] = points[i].y + curshft * curvect.y;
  37399. positions[p + 2] = points[i].z + curshft * curvect.z;
  37400. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  37401. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  37402. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  37403. p += 6;
  37404. j++;
  37405. }
  37406. }
  37407. while (p < positions.length) {
  37408. positions[p] = points[i].x;
  37409. positions[p + 1] = points[i].y;
  37410. positions[p + 2] = points[i].z;
  37411. p += 3;
  37412. }
  37413. };
  37414. instance.updateMeshPositions(positionFunction, false);
  37415. return instance;
  37416. }
  37417. // dashed lines creation
  37418. var dashedLines = new BABYLON.LinesMesh(name, scene);
  37419. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  37420. vertexData.applyToMesh(dashedLines, options.updatable);
  37421. dashedLines.dashSize = dashSize;
  37422. dashedLines.gapSize = gapSize;
  37423. return dashedLines;
  37424. };
  37425. /**
  37426. * Creates an extruded shape mesh.
  37427. * 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.
  37428. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  37429. *
  37430. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37431. * 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
  37432. * extruded along the Z axis.
  37433. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37434. * 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.
  37435. * The parameter `scale` (float, default 1) is the value to scale the shape.
  37436. * 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
  37437. * 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
  37438. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37440. * 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).
  37441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37442. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37444. */
  37445. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  37446. var path = options.path;
  37447. var shape = options.shape;
  37448. var scale = options.scale || 1;
  37449. var rotation = options.rotation || 0;
  37450. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37451. var updatable = options.updatable;
  37452. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37453. var instance = options.instance;
  37454. var invertUV = options.invertUV || false;
  37455. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37456. };
  37457. /**
  37458. * Creates an custom extruded shape mesh.
  37459. * 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.
  37460. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  37461. *
  37462. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37463. * 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
  37464. * extruded along the Z axis.
  37465. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37466. * 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
  37467. * and the distance of this point from the begining of the path :
  37468. * ```javascript
  37469. * var rotationFunction = function(i, distance) {
  37470. * // do things
  37471. * return rotationValue; }
  37472. * ```
  37473. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  37474. * 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
  37475. * and the distance of this point from the begining of the path :
  37476. * ```javascript
  37477. * var scaleFunction = function(i, distance) {
  37478. * // do things
  37479. * return scaleValue;}
  37480. * ```
  37481. * It must returns a float value that will be the scale value applied to the shape on each path point.
  37482. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  37483. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  37484. * 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
  37485. * 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
  37486. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37488. * 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).
  37489. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37490. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37492. */
  37493. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  37494. var path = options.path;
  37495. var shape = options.shape;
  37496. var scaleFunction = options.scaleFunction || (function () { return 1; });
  37497. var rotationFunction = options.rotationFunction || (function () { return 0; });
  37498. var ribbonCloseArray = options.ribbonCloseArray || false;
  37499. var ribbonClosePath = options.ribbonClosePath || false;
  37500. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37501. var updatable = options.updatable;
  37502. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37503. var instance = options.instance;
  37504. var invertUV = options.invertUV || false;
  37505. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37506. };
  37507. /**
  37508. * Creates lathe mesh.
  37509. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  37510. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  37511. *
  37512. * 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
  37513. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  37514. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  37515. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  37516. * 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.
  37517. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  37518. * 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
  37519. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37520. * 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).
  37521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37522. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37524. */
  37525. MeshBuilder.CreateLathe = function (name, options, scene) {
  37526. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  37527. var closed = (options.closed === undefined) ? true : options.closed;
  37528. var shape = options.shape;
  37529. var radius = options.radius || 1;
  37530. var tessellation = options.tessellation || 64;
  37531. var updatable = options.updatable;
  37532. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37533. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37534. var pi2 = Math.PI * 2;
  37535. var paths = new Array();
  37536. var invertUV = options.invertUV || false;
  37537. var i = 0;
  37538. var p = 0;
  37539. var step = pi2 / tessellation * arc;
  37540. var rotated;
  37541. var path = new Array();
  37542. ;
  37543. for (i = 0; i <= tessellation; i++) {
  37544. var path = [];
  37545. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  37546. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  37547. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  37548. }
  37549. for (p = 0; p < shape.length; p++) {
  37550. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  37551. path.push(rotated);
  37552. }
  37553. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  37554. 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));
  37555. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  37556. }
  37557. paths.push(path);
  37558. }
  37559. // lathe ribbon
  37560. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37561. return lathe;
  37562. };
  37563. /**
  37564. * Creates a plane mesh.
  37565. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37566. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  37567. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  37568. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  37569. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37570. * 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).
  37571. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37573. */
  37574. MeshBuilder.CreatePlane = function (name, options, scene) {
  37575. var plane = new BABYLON.Mesh(name, scene);
  37576. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37577. plane.sideOrientation = options.sideOrientation;
  37578. var vertexData = BABYLON.VertexData.CreatePlane(options);
  37579. vertexData.applyToMesh(plane, options.updatable);
  37580. if (options.sourcePlane) {
  37581. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  37582. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  37583. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  37584. plane.rotate(vectorProduct, product);
  37585. }
  37586. return plane;
  37587. };
  37588. /**
  37589. * Creates a ground mesh.
  37590. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37591. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  37592. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  37593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37594. */
  37595. MeshBuilder.CreateGround = function (name, options, scene) {
  37596. var ground = new BABYLON.GroundMesh(name, scene);
  37597. ground._setReady(false);
  37598. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37599. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37600. ground._width = options.width || 1;
  37601. ground._height = options.height || 1;
  37602. ground._maxX = ground._width / 2;
  37603. ground._maxZ = ground._height / 2;
  37604. ground._minX = -ground._maxX;
  37605. ground._minZ = -ground._maxZ;
  37606. var vertexData = BABYLON.VertexData.CreateGround(options);
  37607. vertexData.applyToMesh(ground, options.updatable);
  37608. ground._setReady(true);
  37609. return ground;
  37610. };
  37611. /**
  37612. * Creates a tiled ground mesh.
  37613. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  37614. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  37615. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  37616. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  37617. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  37618. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  37619. * numbers of subdivisions on the ground width and height of each tile.
  37620. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37621. */
  37622. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  37623. var tiledGround = new BABYLON.Mesh(name, scene);
  37624. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  37625. vertexData.applyToMesh(tiledGround, options.updatable);
  37626. return tiledGround;
  37627. };
  37628. /**
  37629. * Creates a ground mesh from a height map.
  37630. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  37631. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  37632. * The parameter `url` sets the URL of the height map image resource.
  37633. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  37634. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  37635. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  37636. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  37637. * 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.
  37638. * 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).
  37639. * This function is passed the newly built mesh :
  37640. * ```javascript
  37641. * function(mesh) { // do things
  37642. * return; }
  37643. * ```
  37644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37645. */
  37646. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  37647. var width = options.width || 10.0;
  37648. var height = options.height || 10.0;
  37649. var subdivisions = options.subdivisions || 1 | 0;
  37650. var minHeight = options.minHeight || 0.0;
  37651. var maxHeight = options.maxHeight || 10.0;
  37652. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37653. var updatable = options.updatable;
  37654. var onReady = options.onReady;
  37655. var ground = new BABYLON.GroundMesh(name, scene);
  37656. ground._subdivisionsX = subdivisions;
  37657. ground._subdivisionsY = subdivisions;
  37658. ground._width = width;
  37659. ground._height = height;
  37660. ground._maxX = ground._width / 2.0;
  37661. ground._maxZ = ground._height / 2.0;
  37662. ground._minX = -ground._maxX;
  37663. ground._minZ = -ground._maxZ;
  37664. ground._setReady(false);
  37665. var onload = function (img) {
  37666. // Getting height map data
  37667. var canvas = document.createElement("canvas");
  37668. var context = canvas.getContext("2d");
  37669. var bufferWidth = img.width;
  37670. var bufferHeight = img.height;
  37671. canvas.width = bufferWidth;
  37672. canvas.height = bufferHeight;
  37673. context.drawImage(img, 0, 0);
  37674. // Create VertexData from map data
  37675. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  37676. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  37677. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  37678. width: width, height: height,
  37679. subdivisions: subdivisions,
  37680. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  37681. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  37682. });
  37683. vertexData.applyToMesh(ground, updatable);
  37684. ground._setReady(true);
  37685. //execute ready callback, if set
  37686. if (onReady) {
  37687. onReady(ground);
  37688. }
  37689. };
  37690. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  37691. return ground;
  37692. };
  37693. /**
  37694. * Creates a polygon mesh.
  37695. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  37696. * 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.
  37697. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37698. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37699. * 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).
  37700. * Remember you can only change the shape positions, not their number when updating a polygon.
  37701. */
  37702. MeshBuilder.CreatePolygon = function (name, options, scene) {
  37703. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37704. var shape = options.shape;
  37705. var holes = options.holes || [];
  37706. var depth = options.depth || 0;
  37707. var contours = [];
  37708. var hole = [];
  37709. for (var i = 0; i < shape.length; i++) {
  37710. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  37711. }
  37712. var epsilon = 0.00000001;
  37713. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  37714. contours.pop();
  37715. }
  37716. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  37717. for (var hNb = 0; hNb < holes.length; hNb++) {
  37718. hole = [];
  37719. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  37720. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  37721. }
  37722. polygonTriangulation.addHole(hole);
  37723. }
  37724. var polygon = polygonTriangulation.build(options.updatable, depth);
  37725. polygon.sideOrientation = options.sideOrientation;
  37726. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  37727. vertexData.applyToMesh(polygon, options.updatable);
  37728. return polygon;
  37729. };
  37730. ;
  37731. /**
  37732. * Creates an extruded polygon mesh, with depth in the Y direction.
  37733. * 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).
  37734. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37735. */
  37736. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  37737. return MeshBuilder.CreatePolygon(name, options, scene);
  37738. };
  37739. ;
  37740. /**
  37741. * Creates a tube mesh.
  37742. * 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.
  37743. *
  37744. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  37745. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  37746. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  37747. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  37748. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  37749. * 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.
  37750. * It must return a radius value (positive float) :
  37751. * ```javascript
  37752. * var radiusFunction = function(i, distance) {
  37753. * // do things
  37754. * return radius; }
  37755. * ```
  37756. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  37757. * 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
  37758. * 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
  37759. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37760. * 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).
  37761. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37762. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37763. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37764. */
  37765. MeshBuilder.CreateTube = function (name, options, scene) {
  37766. var path = options.path;
  37767. var radius = options.radius || 1.0;
  37768. var tessellation = options.tessellation || 64 | 0;
  37769. var radiusFunction = options.radiusFunction;
  37770. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37771. var invertUV = options.invertUV || false;
  37772. var updatable = options.updatable;
  37773. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37774. var instance = options.instance;
  37775. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  37776. // tube geometry
  37777. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  37778. var tangents = path3D.getTangents();
  37779. var normals = path3D.getNormals();
  37780. var distances = path3D.getDistances();
  37781. var pi2 = Math.PI * 2;
  37782. var step = pi2 / tessellation * arc;
  37783. var returnRadius = function () { return radius; };
  37784. var radiusFunctionFinal = radiusFunction || returnRadius;
  37785. var circlePath;
  37786. var rad;
  37787. var normal;
  37788. var rotated;
  37789. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37790. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37791. for (var i = 0; i < path.length; i++) {
  37792. rad = radiusFunctionFinal(i, distances[i]); // current radius
  37793. circlePath = Array(); // current circle array
  37794. normal = normals[i]; // current normal
  37795. for (var t = 0; t < tessellation; t++) {
  37796. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  37797. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  37798. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  37799. rotated.scaleInPlace(rad).addInPlace(path[i]);
  37800. circlePath[t] = rotated;
  37801. }
  37802. circlePaths[index] = circlePath;
  37803. index++;
  37804. }
  37805. // cap
  37806. var capPath = function (nbPoints, pathIndex) {
  37807. var pointCap = Array();
  37808. for (var i = 0; i < nbPoints; i++) {
  37809. pointCap.push(path[pathIndex]);
  37810. }
  37811. return pointCap;
  37812. };
  37813. switch (cap) {
  37814. case BABYLON.Mesh.NO_CAP:
  37815. break;
  37816. case BABYLON.Mesh.CAP_START:
  37817. circlePaths[0] = capPath(tessellation, 0);
  37818. circlePaths[1] = circlePaths[2].slice(0);
  37819. break;
  37820. case BABYLON.Mesh.CAP_END:
  37821. circlePaths[index] = circlePaths[index - 1].slice(0);
  37822. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37823. break;
  37824. case BABYLON.Mesh.CAP_ALL:
  37825. circlePaths[0] = capPath(tessellation, 0);
  37826. circlePaths[1] = circlePaths[2].slice(0);
  37827. circlePaths[index] = circlePaths[index - 1].slice(0);
  37828. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37829. break;
  37830. default:
  37831. break;
  37832. }
  37833. return circlePaths;
  37834. };
  37835. var path3D;
  37836. var pathArray;
  37837. if (instance) {
  37838. var arc = options.arc || instance.arc;
  37839. path3D = (instance.path3D).update(path);
  37840. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  37841. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  37842. instance.path3D = path3D;
  37843. instance.pathArray = pathArray;
  37844. instance.arc = arc;
  37845. return instance;
  37846. }
  37847. // tube creation
  37848. path3D = new BABYLON.Path3D(path);
  37849. var newPathArray = new Array();
  37850. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37851. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  37852. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37853. tube.pathArray = pathArray;
  37854. tube.path3D = path3D;
  37855. tube.tessellation = tessellation;
  37856. tube.cap = cap;
  37857. tube.arc = options.arc;
  37858. return tube;
  37859. };
  37860. /**
  37861. * Creates a polyhedron mesh.
  37862. *
  37863. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  37864. * 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
  37865. * to choose the wanted type.
  37866. * The parameter `size` (positive float, default 1) sets the polygon size.
  37867. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  37868. * 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`.
  37869. * 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
  37870. * 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)`).
  37871. * 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
  37872. * 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.
  37873. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37874. * 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).
  37875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37877. */
  37878. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  37879. var polyhedron = new BABYLON.Mesh(name, scene);
  37880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37881. polyhedron.sideOrientation = options.sideOrientation;
  37882. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  37883. vertexData.applyToMesh(polyhedron, options.updatable);
  37884. return polyhedron;
  37885. };
  37886. /**
  37887. * Creates a decal mesh.
  37888. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  37889. * 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.
  37890. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  37891. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  37892. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  37893. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  37894. */
  37895. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  37896. var indices = sourceMesh.getIndices();
  37897. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37898. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37899. var position = options.position || BABYLON.Vector3.Zero();
  37900. var normal = options.normal || BABYLON.Vector3.Up();
  37901. var size = options.size || BABYLON.Vector3.One();
  37902. var angle = options.angle || 0;
  37903. // Getting correct rotation
  37904. if (!normal) {
  37905. var target = new BABYLON.Vector3(0, 0, 1);
  37906. var camera = sourceMesh.getScene().activeCamera;
  37907. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  37908. normal = camera.globalPosition.subtract(cameraWorldTarget);
  37909. }
  37910. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  37911. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  37912. var pitch = Math.atan2(normal.y, len);
  37913. // Matrix
  37914. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  37915. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  37916. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  37917. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  37918. var vertexData = new BABYLON.VertexData();
  37919. vertexData.indices = [];
  37920. vertexData.positions = [];
  37921. vertexData.normals = [];
  37922. vertexData.uvs = [];
  37923. var currentVertexDataIndex = 0;
  37924. var extractDecalVector3 = function (indexId) {
  37925. var vertexId = indices[indexId];
  37926. var result = new BABYLON.PositionNormalVertex();
  37927. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  37928. // Send vector to decal local world
  37929. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  37930. // Get normal
  37931. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  37932. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  37933. return result;
  37934. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  37935. var clip = function (vertices, axis) {
  37936. if (vertices.length === 0) {
  37937. return vertices;
  37938. }
  37939. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  37940. var clipVertices = function (v0, v1) {
  37941. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  37942. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  37943. };
  37944. var result = new Array();
  37945. for (var index = 0; index < vertices.length; index += 3) {
  37946. var v1Out;
  37947. var v2Out;
  37948. var v3Out;
  37949. var total = 0;
  37950. var nV1, nV2, nV3, nV4;
  37951. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  37952. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  37953. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  37954. v1Out = d1 > 0;
  37955. v2Out = d2 > 0;
  37956. v3Out = d3 > 0;
  37957. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  37958. switch (total) {
  37959. case 0:
  37960. result.push(vertices[index]);
  37961. result.push(vertices[index + 1]);
  37962. result.push(vertices[index + 2]);
  37963. break;
  37964. case 1:
  37965. if (v1Out) {
  37966. nV1 = vertices[index + 1];
  37967. nV2 = vertices[index + 2];
  37968. nV3 = clipVertices(vertices[index], nV1);
  37969. nV4 = clipVertices(vertices[index], nV2);
  37970. }
  37971. if (v2Out) {
  37972. nV1 = vertices[index];
  37973. nV2 = vertices[index + 2];
  37974. nV3 = clipVertices(vertices[index + 1], nV1);
  37975. nV4 = clipVertices(vertices[index + 1], nV2);
  37976. result.push(nV3);
  37977. result.push(nV2.clone());
  37978. result.push(nV1.clone());
  37979. result.push(nV2.clone());
  37980. result.push(nV3.clone());
  37981. result.push(nV4);
  37982. break;
  37983. }
  37984. if (v3Out) {
  37985. nV1 = vertices[index];
  37986. nV2 = vertices[index + 1];
  37987. nV3 = clipVertices(vertices[index + 2], nV1);
  37988. nV4 = clipVertices(vertices[index + 2], nV2);
  37989. }
  37990. result.push(nV1.clone());
  37991. result.push(nV2.clone());
  37992. result.push(nV3);
  37993. result.push(nV4);
  37994. result.push(nV3.clone());
  37995. result.push(nV2.clone());
  37996. break;
  37997. case 2:
  37998. if (!v1Out) {
  37999. nV1 = vertices[index].clone();
  38000. nV2 = clipVertices(nV1, vertices[index + 1]);
  38001. nV3 = clipVertices(nV1, vertices[index + 2]);
  38002. result.push(nV1);
  38003. result.push(nV2);
  38004. result.push(nV3);
  38005. }
  38006. if (!v2Out) {
  38007. nV1 = vertices[index + 1].clone();
  38008. nV2 = clipVertices(nV1, vertices[index + 2]);
  38009. nV3 = clipVertices(nV1, vertices[index]);
  38010. result.push(nV1);
  38011. result.push(nV2);
  38012. result.push(nV3);
  38013. }
  38014. if (!v3Out) {
  38015. nV1 = vertices[index + 2].clone();
  38016. nV2 = clipVertices(nV1, vertices[index]);
  38017. nV3 = clipVertices(nV1, vertices[index + 1]);
  38018. result.push(nV1);
  38019. result.push(nV2);
  38020. result.push(nV3);
  38021. }
  38022. break;
  38023. case 3:
  38024. break;
  38025. }
  38026. }
  38027. return result;
  38028. };
  38029. for (var index = 0; index < indices.length; index += 3) {
  38030. var faceVertices = new Array();
  38031. faceVertices.push(extractDecalVector3(index));
  38032. faceVertices.push(extractDecalVector3(index + 1));
  38033. faceVertices.push(extractDecalVector3(index + 2));
  38034. // Clip
  38035. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38036. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38037. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38038. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38039. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38040. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38041. if (faceVertices.length === 0) {
  38042. continue;
  38043. }
  38044. // Add UVs and get back to world
  38045. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38046. var vertex = faceVertices[vIndex];
  38047. //TODO check for Int32Array | Uint32Array | Uint16Array
  38048. vertexData.indices.push(currentVertexDataIndex);
  38049. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38050. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38051. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38052. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38053. currentVertexDataIndex++;
  38054. }
  38055. }
  38056. // Return mesh
  38057. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38058. vertexData.applyToMesh(decal);
  38059. decal.position = position.clone();
  38060. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38061. return decal;
  38062. };
  38063. // Privates
  38064. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  38065. // extrusion geometry
  38066. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38067. var tangents = path3D.getTangents();
  38068. var normals = path3D.getNormals();
  38069. var binormals = path3D.getBinormals();
  38070. var distances = path3D.getDistances();
  38071. var angle = 0;
  38072. var returnScale = function () { return scale; };
  38073. var returnRotation = function () { return rotation; };
  38074. var rotate = custom ? rotateFunction : returnRotation;
  38075. var scl = custom ? scaleFunction : returnScale;
  38076. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38077. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38078. for (var i = 0; i < curve.length; i++) {
  38079. var shapePath = new Array();
  38080. var angleStep = rotate(i, distances[i]);
  38081. var scaleRatio = scl(i, distances[i]);
  38082. for (var p = 0; p < shape.length; p++) {
  38083. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38084. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38085. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38086. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38087. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38088. shapePath[p] = rotated;
  38089. }
  38090. shapePaths[index] = shapePath;
  38091. angle += angleStep;
  38092. index++;
  38093. }
  38094. // cap
  38095. var capPath = function (shapePath) {
  38096. var pointCap = Array();
  38097. var barycenter = BABYLON.Vector3.Zero();
  38098. var i;
  38099. for (i = 0; i < shapePath.length; i++) {
  38100. barycenter.addInPlace(shapePath[i]);
  38101. }
  38102. barycenter.scaleInPlace(1.0 / shapePath.length);
  38103. for (i = 0; i < shapePath.length; i++) {
  38104. pointCap.push(barycenter);
  38105. }
  38106. return pointCap;
  38107. };
  38108. switch (cap) {
  38109. case BABYLON.Mesh.NO_CAP:
  38110. break;
  38111. case BABYLON.Mesh.CAP_START:
  38112. shapePaths[0] = capPath(shapePaths[2]);
  38113. shapePaths[1] = shapePaths[2];
  38114. break;
  38115. case BABYLON.Mesh.CAP_END:
  38116. shapePaths[index] = shapePaths[index - 1];
  38117. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38118. break;
  38119. case BABYLON.Mesh.CAP_ALL:
  38120. shapePaths[0] = capPath(shapePaths[2]);
  38121. shapePaths[1] = shapePaths[2];
  38122. shapePaths[index] = shapePaths[index - 1];
  38123. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38124. break;
  38125. default:
  38126. break;
  38127. }
  38128. return shapePaths;
  38129. };
  38130. var path3D;
  38131. var pathArray;
  38132. if (instance) {
  38133. path3D = (instance.path3D).update(curve);
  38134. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38135. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38136. return instance;
  38137. }
  38138. // extruded shape creation
  38139. path3D = new BABYLON.Path3D(curve);
  38140. var newShapePaths = new Array();
  38141. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38142. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38143. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  38144. extrudedGeneric.pathArray = pathArray;
  38145. extrudedGeneric.path3D = path3D;
  38146. extrudedGeneric.cap = cap;
  38147. return extrudedGeneric;
  38148. };
  38149. return MeshBuilder;
  38150. }());
  38151. BABYLON.MeshBuilder = MeshBuilder;
  38152. })(BABYLON || (BABYLON = {}));
  38153. //# sourceMappingURL=babylon.meshBuilder.js.map
  38154. var BABYLON;
  38155. (function (BABYLON) {
  38156. var Layer = (function () {
  38157. function Layer(name, imgUrl, scene, isBackground, color) {
  38158. this.name = name;
  38159. this.scale = new BABYLON.Vector2(1, 1);
  38160. this.offset = new BABYLON.Vector2(0, 0);
  38161. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  38162. this.layerMask = 0x0FFFFFFF;
  38163. this._vertexBuffers = {};
  38164. // Events
  38165. /**
  38166. * An event triggered when the layer is disposed.
  38167. * @type {BABYLON.Observable}
  38168. */
  38169. this.onDisposeObservable = new BABYLON.Observable();
  38170. /**
  38171. * An event triggered before rendering the scene
  38172. * @type {BABYLON.Observable}
  38173. */
  38174. this.onBeforeRenderObservable = new BABYLON.Observable();
  38175. /**
  38176. * An event triggered after rendering the scene
  38177. * @type {BABYLON.Observable}
  38178. */
  38179. this.onAfterRenderObservable = new BABYLON.Observable();
  38180. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  38181. this.isBackground = isBackground === undefined ? true : isBackground;
  38182. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  38183. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38184. this._scene.layers.push(this);
  38185. var engine = this._scene.getEngine();
  38186. // VBO
  38187. var vertices = [];
  38188. vertices.push(1, 1);
  38189. vertices.push(-1, 1);
  38190. vertices.push(-1, -1);
  38191. vertices.push(1, -1);
  38192. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38193. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38194. // Indices
  38195. var indices = [];
  38196. indices.push(0);
  38197. indices.push(1);
  38198. indices.push(2);
  38199. indices.push(0);
  38200. indices.push(2);
  38201. indices.push(3);
  38202. this._indexBuffer = engine.createIndexBuffer(indices);
  38203. // Effects
  38204. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  38205. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  38206. }
  38207. Object.defineProperty(Layer.prototype, "onDispose", {
  38208. set: function (callback) {
  38209. if (this._onDisposeObserver) {
  38210. this.onDisposeObservable.remove(this._onDisposeObserver);
  38211. }
  38212. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38213. },
  38214. enumerable: true,
  38215. configurable: true
  38216. });
  38217. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  38218. set: function (callback) {
  38219. if (this._onBeforeRenderObserver) {
  38220. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  38221. }
  38222. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  38223. },
  38224. enumerable: true,
  38225. configurable: true
  38226. });
  38227. Object.defineProperty(Layer.prototype, "onAfterRender", {
  38228. set: function (callback) {
  38229. if (this._onAfterRenderObserver) {
  38230. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  38231. }
  38232. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  38233. },
  38234. enumerable: true,
  38235. configurable: true
  38236. });
  38237. Layer.prototype.render = function () {
  38238. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  38239. // Check
  38240. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  38241. return;
  38242. var engine = this._scene.getEngine();
  38243. this.onBeforeRenderObservable.notifyObservers(this);
  38244. // Render
  38245. engine.enableEffect(currentEffect);
  38246. engine.setState(false);
  38247. // Texture
  38248. currentEffect.setTexture("textureSampler", this.texture);
  38249. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  38250. // Color
  38251. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  38252. // Scale / offset
  38253. currentEffect.setVector2("offset", this.offset);
  38254. currentEffect.setVector2("scale", this.scale);
  38255. // VBOs
  38256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38257. // Draw order
  38258. if (!this.alphaTest) {
  38259. engine.setAlphaMode(this.alphaBlendingMode);
  38260. engine.draw(true, 0, 6);
  38261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38262. }
  38263. else {
  38264. engine.draw(true, 0, 6);
  38265. }
  38266. this.onAfterRenderObservable.notifyObservers(this);
  38267. };
  38268. Layer.prototype.dispose = function () {
  38269. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38270. if (vertexBuffer) {
  38271. vertexBuffer.dispose();
  38272. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38273. }
  38274. if (this._indexBuffer) {
  38275. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38276. this._indexBuffer = null;
  38277. }
  38278. if (this.texture) {
  38279. this.texture.dispose();
  38280. this.texture = null;
  38281. }
  38282. // Remove from scene
  38283. var index = this._scene.layers.indexOf(this);
  38284. this._scene.layers.splice(index, 1);
  38285. // Callback
  38286. this.onDisposeObservable.notifyObservers(this);
  38287. this.onDisposeObservable.clear();
  38288. this.onAfterRenderObservable.clear();
  38289. this.onBeforeRenderObservable.clear();
  38290. };
  38291. return Layer;
  38292. }());
  38293. BABYLON.Layer = Layer;
  38294. })(BABYLON || (BABYLON = {}));
  38295. //# sourceMappingURL=babylon.layer.js.map
  38296. var BABYLON;
  38297. (function (BABYLON) {
  38298. var BlurPostProcess = (function (_super) {
  38299. __extends(BlurPostProcess, _super);
  38300. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  38301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38302. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38303. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  38304. _this.direction = direction;
  38305. _this._packedFloat = false;
  38306. _this.onApplyObservable.add(function (effect) {
  38307. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  38308. });
  38309. _this.kernel = kernel;
  38310. return _this;
  38311. }
  38312. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  38313. /**
  38314. * Gets the length in pixels of the blur sample region
  38315. */
  38316. get: function () {
  38317. return this._idealKernel;
  38318. },
  38319. /**
  38320. * Sets the length in pixels of the blur sample region
  38321. */
  38322. set: function (v) {
  38323. if (this._idealKernel === v) {
  38324. return;
  38325. }
  38326. v = Math.max(v, 1);
  38327. this._idealKernel = v;
  38328. this._kernel = this._nearestBestKernel(v);
  38329. this._updateParameters();
  38330. },
  38331. enumerable: true,
  38332. configurable: true
  38333. });
  38334. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  38335. /**
  38336. * Gets wether or not the blur is unpacking/repacking floats
  38337. */
  38338. get: function () {
  38339. return this._packedFloat;
  38340. },
  38341. /**
  38342. * Sets wether or not the blur needs to unpack/repack floats
  38343. */
  38344. set: function (v) {
  38345. if (this._packedFloat === v) {
  38346. return;
  38347. }
  38348. this._packedFloat = v;
  38349. this._updateParameters();
  38350. },
  38351. enumerable: true,
  38352. configurable: true
  38353. });
  38354. BlurPostProcess.prototype._updateParameters = function () {
  38355. // Generate sampling offsets and weights
  38356. var N = this._kernel;
  38357. var centerIndex = (N - 1) / 2;
  38358. // Generate Gaussian sampling weights over kernel
  38359. var offsets = [];
  38360. var weights = [];
  38361. var totalWeight = 0;
  38362. for (var i = 0; i < N; i++) {
  38363. var u = i / (N - 1);
  38364. var w = this._gaussianWeight(u * 2.0 - 1);
  38365. offsets[i] = (i - centerIndex);
  38366. weights[i] = w;
  38367. totalWeight += w;
  38368. }
  38369. // Normalize weights
  38370. for (var i = 0; i < weights.length; i++) {
  38371. weights[i] /= totalWeight;
  38372. }
  38373. // Optimize: combine samples to take advantage of hardware linear sampling
  38374. // Walk from left to center, combining pairs (symmetrically)
  38375. var linearSamplingWeights = [];
  38376. var linearSamplingOffsets = [];
  38377. var linearSamplingMap = [];
  38378. for (var i = 0; i <= centerIndex; i += 2) {
  38379. var j = Math.min(i + 1, Math.floor(centerIndex));
  38380. var singleCenterSample = i === j;
  38381. if (singleCenterSample) {
  38382. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38383. }
  38384. else {
  38385. var sharedCell = j === centerIndex;
  38386. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  38387. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  38388. if (offsetLinear === 0) {
  38389. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38390. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  38391. }
  38392. else {
  38393. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  38394. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  38395. }
  38396. }
  38397. }
  38398. for (var i = 0; i < linearSamplingMap.length; i++) {
  38399. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  38400. linearSamplingWeights[i] = linearSamplingMap[i].w;
  38401. }
  38402. // Replace with optimized
  38403. offsets = linearSamplingOffsets;
  38404. weights = linearSamplingWeights;
  38405. // Generate shaders
  38406. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  38407. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  38408. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  38409. var defines = "";
  38410. for (var i = 0; i < varyingCount; i++) {
  38411. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  38412. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  38413. }
  38414. var depCount = 0;
  38415. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  38416. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  38417. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  38418. depCount++;
  38419. }
  38420. if (this.packedFloat) {
  38421. defines += "#define PACKEDFLOAT 1";
  38422. }
  38423. this.updateEffect(defines, null, null, {
  38424. varyingCount: varyingCount,
  38425. depCount: depCount
  38426. });
  38427. };
  38428. /**
  38429. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  38430. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  38431. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  38432. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  38433. * The gaps between physical kernels are compensated for in the weighting of the samples
  38434. * @param idealKernel Ideal blur kernel.
  38435. * @return Nearest best kernel.
  38436. */
  38437. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  38438. var v = Math.round(idealKernel);
  38439. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  38440. var k = _a[_i];
  38441. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  38442. return Math.max(k, 3);
  38443. }
  38444. }
  38445. return Math.max(v, 3);
  38446. };
  38447. /**
  38448. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  38449. * @param x The point on the Gaussian distribution to sample.
  38450. * @return the value of the Gaussian function at x.
  38451. */
  38452. BlurPostProcess.prototype._gaussianWeight = function (x) {
  38453. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  38454. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  38455. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  38456. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  38457. // truncated at around 1.3% of peak strength.
  38458. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  38459. var sigma = (1 / 3);
  38460. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  38461. var exponent = -((x * x) / (2.0 * sigma * sigma));
  38462. var weight = (1.0 / denominator) * Math.exp(exponent);
  38463. return weight;
  38464. };
  38465. /**
  38466. * Generates a string that can be used as a floating point number in GLSL.
  38467. * @param x Value to print.
  38468. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  38469. * @return GLSL float string.
  38470. */
  38471. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  38472. if (decimalFigures === void 0) { decimalFigures = 8; }
  38473. return x.toFixed(decimalFigures).replace(/0+$/, '');
  38474. };
  38475. return BlurPostProcess;
  38476. }(BABYLON.PostProcess));
  38477. BABYLON.BlurPostProcess = BlurPostProcess;
  38478. })(BABYLON || (BABYLON = {}));
  38479. //# sourceMappingURL=babylon.blurPostProcess.js.map
  38480. var BABYLON;
  38481. (function (BABYLON) {
  38482. var FxaaPostProcess = (function (_super) {
  38483. __extends(FxaaPostProcess, _super);
  38484. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38485. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38486. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  38487. _this.onApplyObservable.add(function (effect) {
  38488. var texelSize = _this.texelSize;
  38489. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  38490. });
  38491. return _this;
  38492. }
  38493. return FxaaPostProcess;
  38494. }(BABYLON.PostProcess));
  38495. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38496. })(BABYLON || (BABYLON = {}));
  38497. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  38498. var BABYLON;
  38499. (function (BABYLON) {
  38500. var HighlightsPostProcess = (function (_super) {
  38501. __extends(HighlightsPostProcess, _super);
  38502. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38503. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38504. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  38505. }
  38506. return HighlightsPostProcess;
  38507. }(BABYLON.PostProcess));
  38508. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  38509. })(BABYLON || (BABYLON = {}));
  38510. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  38511. var BABYLON;
  38512. (function (BABYLON) {
  38513. var ImageProcessingPostProcess = (function (_super) {
  38514. __extends(ImageProcessingPostProcess, _super);
  38515. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38516. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38517. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  38518. _this._fromLinearSpace = true;
  38519. /**
  38520. * Defines cache preventing GC.
  38521. */
  38522. _this._defines = {
  38523. IMAGEPROCESSING: false,
  38524. VIGNETTE: false,
  38525. VIGNETTEBLENDMODEMULTIPLY: false,
  38526. VIGNETTEBLENDMODEOPAQUE: false,
  38527. TONEMAPPING: false,
  38528. CONTRAST: false,
  38529. COLORCURVES: false,
  38530. COLORGRADING: false,
  38531. FROMLINEARSPACE: false,
  38532. SAMPLER3DGREENDEPTH: false,
  38533. SAMPLER3DBGRMAP: false,
  38534. IMAGEPROCESSINGPOSTPROCESS: false,
  38535. EXPOSURE: false,
  38536. };
  38537. // Setup the default processing configuration to the scene.
  38538. _this._attachImageProcessingConfiguration(null);
  38539. _this.imageProcessingConfiguration.applyByPostProcess = true;
  38540. _this._updateParameters();
  38541. _this.onApply = function (effect) {
  38542. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  38543. };
  38544. return _this;
  38545. }
  38546. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  38547. /**
  38548. * Gets the image processing configuration used either in this material.
  38549. */
  38550. get: function () {
  38551. return this._imageProcessingConfiguration;
  38552. },
  38553. /**
  38554. * Sets the Default image processing configuration used either in the this material.
  38555. *
  38556. * If sets to null, the scene one is in use.
  38557. */
  38558. set: function (value) {
  38559. this._attachImageProcessingConfiguration(value);
  38560. },
  38561. enumerable: true,
  38562. configurable: true
  38563. });
  38564. /**
  38565. * Attaches a new image processing configuration to the PBR Material.
  38566. * @param configuration
  38567. */
  38568. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  38569. var _this = this;
  38570. if (configuration === this._imageProcessingConfiguration) {
  38571. return;
  38572. }
  38573. // Detaches observer.
  38574. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38575. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38576. }
  38577. // Pick the scene configuration if needed.
  38578. if (!configuration) {
  38579. var camera = this.getCamera();
  38580. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  38581. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  38582. }
  38583. else {
  38584. this._imageProcessingConfiguration = configuration;
  38585. }
  38586. // Attaches observer.
  38587. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38588. _this._updateParameters();
  38589. });
  38590. // Ensure the effect will be rebuilt.
  38591. this._updateParameters();
  38592. };
  38593. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  38594. /**
  38595. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38596. */
  38597. get: function () {
  38598. return this.imageProcessingConfiguration.colorCurves;
  38599. },
  38600. /**
  38601. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38602. */
  38603. set: function (value) {
  38604. this.imageProcessingConfiguration.colorCurves = value;
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  38610. /**
  38611. * Gets wether the color curves effect is enabled.
  38612. */
  38613. get: function () {
  38614. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38615. },
  38616. /**
  38617. * Sets wether the color curves effect is enabled.
  38618. */
  38619. set: function (value) {
  38620. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38621. },
  38622. enumerable: true,
  38623. configurable: true
  38624. });
  38625. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  38626. /**
  38627. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38628. */
  38629. get: function () {
  38630. return this.imageProcessingConfiguration.colorGradingTexture;
  38631. },
  38632. /**
  38633. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38634. */
  38635. set: function (value) {
  38636. this.imageProcessingConfiguration.colorGradingTexture = value;
  38637. },
  38638. enumerable: true,
  38639. configurable: true
  38640. });
  38641. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  38642. /**
  38643. * Gets wether the color grading effect is enabled.
  38644. */
  38645. get: function () {
  38646. return this.imageProcessingConfiguration.colorGradingEnabled;
  38647. },
  38648. /**
  38649. * Gets wether the color grading effect is enabled.
  38650. */
  38651. set: function (value) {
  38652. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38653. },
  38654. enumerable: true,
  38655. configurable: true
  38656. });
  38657. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  38658. /**
  38659. * Gets exposure used in the effect.
  38660. */
  38661. get: function () {
  38662. return this.imageProcessingConfiguration.exposure;
  38663. },
  38664. /**
  38665. * Sets exposure used in the effect.
  38666. */
  38667. set: function (value) {
  38668. this.imageProcessingConfiguration.exposure = value;
  38669. },
  38670. enumerable: true,
  38671. configurable: true
  38672. });
  38673. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  38674. /**
  38675. * Gets wether tonemapping is enabled or not.
  38676. */
  38677. get: function () {
  38678. return this._imageProcessingConfiguration.toneMappingEnabled;
  38679. },
  38680. /**
  38681. * Sets wether tonemapping is enabled or not
  38682. */
  38683. set: function (value) {
  38684. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38685. },
  38686. enumerable: true,
  38687. configurable: true
  38688. });
  38689. ;
  38690. ;
  38691. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  38692. /**
  38693. * Gets contrast used in the effect.
  38694. */
  38695. get: function () {
  38696. return this.imageProcessingConfiguration.contrast;
  38697. },
  38698. /**
  38699. * Sets contrast used in the effect.
  38700. */
  38701. set: function (value) {
  38702. this.imageProcessingConfiguration.contrast = value;
  38703. },
  38704. enumerable: true,
  38705. configurable: true
  38706. });
  38707. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  38708. /**
  38709. * Gets Vignette stretch size.
  38710. */
  38711. get: function () {
  38712. return this.imageProcessingConfiguration.vignetteStretch;
  38713. },
  38714. /**
  38715. * Sets Vignette stretch size.
  38716. */
  38717. set: function (value) {
  38718. this.imageProcessingConfiguration.vignetteStretch = value;
  38719. },
  38720. enumerable: true,
  38721. configurable: true
  38722. });
  38723. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  38724. /**
  38725. * Gets Vignette centre X Offset.
  38726. */
  38727. get: function () {
  38728. return this.imageProcessingConfiguration.vignetteCentreX;
  38729. },
  38730. /**
  38731. * Sets Vignette centre X Offset.
  38732. */
  38733. set: function (value) {
  38734. this.imageProcessingConfiguration.vignetteCentreX = value;
  38735. },
  38736. enumerable: true,
  38737. configurable: true
  38738. });
  38739. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  38740. /**
  38741. * Gets Vignette centre Y Offset.
  38742. */
  38743. get: function () {
  38744. return this.imageProcessingConfiguration.vignetteCentreY;
  38745. },
  38746. /**
  38747. * Sets Vignette centre Y Offset.
  38748. */
  38749. set: function (value) {
  38750. this.imageProcessingConfiguration.vignetteCentreY = value;
  38751. },
  38752. enumerable: true,
  38753. configurable: true
  38754. });
  38755. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  38756. /**
  38757. * Gets Vignette weight or intensity of the vignette effect.
  38758. */
  38759. get: function () {
  38760. return this.imageProcessingConfiguration.vignetteWeight;
  38761. },
  38762. /**
  38763. * Sets Vignette weight or intensity of the vignette effect.
  38764. */
  38765. set: function (value) {
  38766. this.imageProcessingConfiguration.vignetteWeight = value;
  38767. },
  38768. enumerable: true,
  38769. configurable: true
  38770. });
  38771. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  38772. /**
  38773. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38774. * if vignetteEnabled is set to true.
  38775. */
  38776. get: function () {
  38777. return this.imageProcessingConfiguration.vignetteColor;
  38778. },
  38779. /**
  38780. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38781. * if vignetteEnabled is set to true.
  38782. */
  38783. set: function (value) {
  38784. this.imageProcessingConfiguration.vignetteColor = value;
  38785. },
  38786. enumerable: true,
  38787. configurable: true
  38788. });
  38789. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  38790. /**
  38791. * Gets Camera field of view used by the Vignette effect.
  38792. */
  38793. get: function () {
  38794. return this.imageProcessingConfiguration.vignetteCameraFov;
  38795. },
  38796. /**
  38797. * Sets Camera field of view used by the Vignette effect.
  38798. */
  38799. set: function (value) {
  38800. this.imageProcessingConfiguration.vignetteCameraFov = value;
  38801. },
  38802. enumerable: true,
  38803. configurable: true
  38804. });
  38805. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  38806. /**
  38807. * Gets the vignette blend mode allowing different kind of effect.
  38808. */
  38809. get: function () {
  38810. return this.imageProcessingConfiguration.vignetteBlendMode;
  38811. },
  38812. /**
  38813. * Sets the vignette blend mode allowing different kind of effect.
  38814. */
  38815. set: function (value) {
  38816. this.imageProcessingConfiguration.vignetteBlendMode = value;
  38817. },
  38818. enumerable: true,
  38819. configurable: true
  38820. });
  38821. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  38822. /**
  38823. * Gets wether the vignette effect is enabled.
  38824. */
  38825. get: function () {
  38826. return this.imageProcessingConfiguration.vignetteEnabled;
  38827. },
  38828. /**
  38829. * Sets wether the vignette effect is enabled.
  38830. */
  38831. set: function (value) {
  38832. this.imageProcessingConfiguration.vignetteEnabled = value;
  38833. },
  38834. enumerable: true,
  38835. configurable: true
  38836. });
  38837. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  38838. /**
  38839. * Gets wether the input of the processing is in Gamma or Linear Space.
  38840. */
  38841. get: function () {
  38842. return this._fromLinearSpace;
  38843. },
  38844. /**
  38845. * Sets wether the input of the processing is in Gamma or Linear Space.
  38846. */
  38847. set: function (value) {
  38848. if (this._fromLinearSpace === value) {
  38849. return;
  38850. }
  38851. this._fromLinearSpace = value;
  38852. this._updateParameters();
  38853. },
  38854. enumerable: true,
  38855. configurable: true
  38856. });
  38857. ImageProcessingPostProcess.prototype._updateParameters = function () {
  38858. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  38859. this.imageProcessingConfiguration.prepareDefines(this._defines);
  38860. var defines = "";
  38861. for (var define in this._defines) {
  38862. if (this._defines[define]) {
  38863. defines += "#define " + define + ";\r\n";
  38864. }
  38865. }
  38866. var samplers = ["textureSampler"];
  38867. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  38868. var uniforms = ["scale"];
  38869. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  38870. this.updateEffect(defines, uniforms, samplers);
  38871. };
  38872. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  38873. _super.prototype.dispose.call(this, camera);
  38874. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38875. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38876. }
  38877. this.imageProcessingConfiguration.applyByPostProcess = false;
  38878. };
  38879. return ImageProcessingPostProcess;
  38880. }(BABYLON.PostProcess));
  38881. __decorate([
  38882. BABYLON.serialize()
  38883. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  38884. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  38885. })(BABYLON || (BABYLON = {}));
  38886. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  38887. var BABYLON;
  38888. (function (BABYLON) {
  38889. /**
  38890. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38891. * It can help converting any input color in a desired output one. This can then be used to create effects
  38892. * from sepia, black and white to sixties or futuristic rendering...
  38893. *
  38894. * The only supported format is currently 3dl.
  38895. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38896. */
  38897. var ColorGradingTexture = (function (_super) {
  38898. __extends(ColorGradingTexture, _super);
  38899. /**
  38900. * Instantiates a ColorGradingTexture from the following parameters.
  38901. *
  38902. * @param url The location of the color gradind data (currently only supporting 3dl)
  38903. * @param scene The scene the texture will be used in
  38904. */
  38905. function ColorGradingTexture(url, scene) {
  38906. var _this = _super.call(this, scene) || this;
  38907. if (!url) {
  38908. return _this;
  38909. }
  38910. _this._textureMatrix = BABYLON.Matrix.Identity();
  38911. _this.name = url;
  38912. _this.url = url;
  38913. _this.hasAlpha = false;
  38914. _this.isCube = false;
  38915. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38916. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38917. _this.anisotropicFilteringLevel = 1;
  38918. _this._texture = _this._getFromCache(url, true);
  38919. if (!_this._texture) {
  38920. if (!scene.useDelayedTextureLoading) {
  38921. _this.loadTexture();
  38922. }
  38923. else {
  38924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38925. }
  38926. }
  38927. return _this;
  38928. }
  38929. /**
  38930. * Returns the texture matrix used in most of the material.
  38931. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38932. */
  38933. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38934. return this._textureMatrix;
  38935. };
  38936. /**
  38937. * Occurs when the file being loaded is a .3dl LUT file.
  38938. */
  38939. ColorGradingTexture.prototype.load3dlTexture = function () {
  38940. var _this = this;
  38941. var mipLevels = 0;
  38942. var floatArrayView = null;
  38943. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38944. this._texture = texture;
  38945. var callback = function (text) {
  38946. var data;
  38947. var tempData;
  38948. var line;
  38949. var lines = text.split('\n');
  38950. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38951. var maxColor = 0;
  38952. for (var i = 0; i < lines.length; i++) {
  38953. line = lines[i];
  38954. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38955. continue;
  38956. if (line.indexOf('#') === 0)
  38957. continue;
  38958. var words = line.split(" ");
  38959. if (size === 0) {
  38960. // Number of space + one
  38961. size = words.length;
  38962. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38963. tempData = new Float32Array(size * size * size * 4);
  38964. continue;
  38965. }
  38966. if (size != 0) {
  38967. var r = Math.max(parseInt(words[0]), 0);
  38968. var g = Math.max(parseInt(words[1]), 0);
  38969. var b = Math.max(parseInt(words[2]), 0);
  38970. maxColor = Math.max(r, maxColor);
  38971. maxColor = Math.max(g, maxColor);
  38972. maxColor = Math.max(b, maxColor);
  38973. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38974. tempData[pixelStorageIndex + 0] = r;
  38975. tempData[pixelStorageIndex + 1] = g;
  38976. tempData[pixelStorageIndex + 2] = b;
  38977. pixelIndexSlice++;
  38978. if (pixelIndexSlice % size == 0) {
  38979. pixelIndexH++;
  38980. pixelIndexSlice = 0;
  38981. if (pixelIndexH % size == 0) {
  38982. pixelIndexW++;
  38983. pixelIndexH = 0;
  38984. }
  38985. }
  38986. }
  38987. }
  38988. for (var i = 0; i < tempData.length; i++) {
  38989. if (i > 0 && (i + 1) % 4 === 0) {
  38990. data[i] = 255;
  38991. }
  38992. else {
  38993. var value = tempData[i];
  38994. data[i] = (value / maxColor * 255);
  38995. }
  38996. }
  38997. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  38998. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38999. };
  39000. BABYLON.Tools.LoadFile(this.url, callback);
  39001. return this._texture;
  39002. };
  39003. /**
  39004. * Starts the loading process of the texture.
  39005. */
  39006. ColorGradingTexture.prototype.loadTexture = function () {
  39007. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  39008. this.load3dlTexture();
  39009. }
  39010. };
  39011. /**
  39012. * Clones the color gradind texture.
  39013. */
  39014. ColorGradingTexture.prototype.clone = function () {
  39015. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  39016. // Base texture
  39017. newTexture.level = this.level;
  39018. return newTexture;
  39019. };
  39020. /**
  39021. * Called during delayed load for textures.
  39022. */
  39023. ColorGradingTexture.prototype.delayLoad = function () {
  39024. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39025. return;
  39026. }
  39027. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39028. this._texture = this._getFromCache(this.url, true);
  39029. if (!this._texture) {
  39030. this.loadTexture();
  39031. }
  39032. };
  39033. /**
  39034. * Parses a color grading texture serialized by Babylon.
  39035. * @param parsedTexture The texture information being parsedTexture
  39036. * @param scene The scene to load the texture in
  39037. * @param rootUrl The root url of the data assets to load
  39038. * @return A color gradind texture
  39039. */
  39040. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39041. var texture = null;
  39042. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39043. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  39044. texture.name = parsedTexture.name;
  39045. texture.level = parsedTexture.level;
  39046. }
  39047. return texture;
  39048. };
  39049. /**
  39050. * Serializes the LUT texture to json format.
  39051. */
  39052. ColorGradingTexture.prototype.serialize = function () {
  39053. if (!this.name) {
  39054. return null;
  39055. }
  39056. var serializationObject = {};
  39057. serializationObject.name = this.name;
  39058. serializationObject.level = this.level;
  39059. serializationObject.customType = "BABYLON.ColorGradingTexture";
  39060. return serializationObject;
  39061. };
  39062. return ColorGradingTexture;
  39063. }(BABYLON.BaseTexture));
  39064. /**
  39065. * Empty line regex stored for GC.
  39066. */
  39067. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  39068. BABYLON.ColorGradingTexture = ColorGradingTexture;
  39069. })(BABYLON || (BABYLON = {}));
  39070. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  39071. var BABYLON;
  39072. (function (BABYLON) {
  39073. /**
  39074. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39075. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39076. * 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;
  39077. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39078. */
  39079. var ColorCurves = (function () {
  39080. function ColorCurves() {
  39081. this._dirty = true;
  39082. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  39083. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  39084. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39085. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  39086. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39087. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  39088. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  39089. this._globalHue = 30;
  39090. this._globalDensity = 0;
  39091. this._globalSaturation = 0;
  39092. this._globalExposure = 0;
  39093. this._highlightsHue = 30;
  39094. this._highlightsDensity = 0;
  39095. this._highlightsSaturation = 0;
  39096. this._highlightsExposure = 0;
  39097. this._midtonesHue = 30;
  39098. this._midtonesDensity = 0;
  39099. this._midtonesSaturation = 0;
  39100. this._midtonesExposure = 0;
  39101. this._shadowsHue = 30;
  39102. this._shadowsDensity = 0;
  39103. this._shadowsSaturation = 0;
  39104. this._shadowsExposure = 0;
  39105. }
  39106. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39107. /**
  39108. * Gets the global Hue value.
  39109. * 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).
  39110. */
  39111. get: function () {
  39112. return this._globalHue;
  39113. },
  39114. /**
  39115. * Sets the global Hue value.
  39116. * 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).
  39117. */
  39118. set: function (value) {
  39119. this._globalHue = value;
  39120. this._dirty = true;
  39121. },
  39122. enumerable: true,
  39123. configurable: true
  39124. });
  39125. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39126. /**
  39127. * Gets the global Density value.
  39128. * 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.
  39129. * Values less than zero provide a filter of opposite hue.
  39130. */
  39131. get: function () {
  39132. return this._globalDensity;
  39133. },
  39134. /**
  39135. * Sets the global Density value.
  39136. * 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.
  39137. * Values less than zero provide a filter of opposite hue.
  39138. */
  39139. set: function (value) {
  39140. this._globalDensity = value;
  39141. this._dirty = true;
  39142. },
  39143. enumerable: true,
  39144. configurable: true
  39145. });
  39146. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39147. /**
  39148. * Gets the global Saturation value.
  39149. * 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.
  39150. */
  39151. get: function () {
  39152. return this._globalSaturation;
  39153. },
  39154. /**
  39155. * Sets the global Saturation value.
  39156. * 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.
  39157. */
  39158. set: function (value) {
  39159. this._globalSaturation = value;
  39160. this._dirty = true;
  39161. },
  39162. enumerable: true,
  39163. configurable: true
  39164. });
  39165. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39166. /**
  39167. * Gets the highlights Hue value.
  39168. * 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).
  39169. */
  39170. get: function () {
  39171. return this._highlightsHue;
  39172. },
  39173. /**
  39174. * Sets the highlights Hue value.
  39175. * 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).
  39176. */
  39177. set: function (value) {
  39178. this._highlightsHue = value;
  39179. this._dirty = true;
  39180. },
  39181. enumerable: true,
  39182. configurable: true
  39183. });
  39184. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39185. /**
  39186. * Gets the highlights Density value.
  39187. * 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.
  39188. * Values less than zero provide a filter of opposite hue.
  39189. */
  39190. get: function () {
  39191. return this._highlightsDensity;
  39192. },
  39193. /**
  39194. * Sets the highlights Density value.
  39195. * 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.
  39196. * Values less than zero provide a filter of opposite hue.
  39197. */
  39198. set: function (value) {
  39199. this._highlightsDensity = value;
  39200. this._dirty = true;
  39201. },
  39202. enumerable: true,
  39203. configurable: true
  39204. });
  39205. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39206. /**
  39207. * Gets the highlights Saturation value.
  39208. * 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.
  39209. */
  39210. get: function () {
  39211. return this._highlightsSaturation;
  39212. },
  39213. /**
  39214. * Sets the highlights Saturation value.
  39215. * 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.
  39216. */
  39217. set: function (value) {
  39218. this._highlightsSaturation = value;
  39219. this._dirty = true;
  39220. },
  39221. enumerable: true,
  39222. configurable: true
  39223. });
  39224. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39225. /**
  39226. * Gets the highlights Exposure value.
  39227. * 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.
  39228. */
  39229. get: function () {
  39230. return this._highlightsExposure;
  39231. },
  39232. /**
  39233. * Sets the highlights Exposure value.
  39234. * 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.
  39235. */
  39236. set: function (value) {
  39237. this._highlightsExposure = value;
  39238. this._dirty = true;
  39239. },
  39240. enumerable: true,
  39241. configurable: true
  39242. });
  39243. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39244. /**
  39245. * Gets the midtones Hue value.
  39246. * 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).
  39247. */
  39248. get: function () {
  39249. return this._midtonesHue;
  39250. },
  39251. /**
  39252. * Sets the midtones Hue value.
  39253. * 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).
  39254. */
  39255. set: function (value) {
  39256. this._midtonesHue = value;
  39257. this._dirty = true;
  39258. },
  39259. enumerable: true,
  39260. configurable: true
  39261. });
  39262. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39263. /**
  39264. * Gets the midtones Density value.
  39265. * 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.
  39266. * Values less than zero provide a filter of opposite hue.
  39267. */
  39268. get: function () {
  39269. return this._midtonesDensity;
  39270. },
  39271. /**
  39272. * Sets the midtones Density value.
  39273. * 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.
  39274. * Values less than zero provide a filter of opposite hue.
  39275. */
  39276. set: function (value) {
  39277. this._midtonesDensity = value;
  39278. this._dirty = true;
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39284. /**
  39285. * Gets the midtones Saturation value.
  39286. * 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.
  39287. */
  39288. get: function () {
  39289. return this._midtonesSaturation;
  39290. },
  39291. /**
  39292. * Sets the midtones Saturation value.
  39293. * 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.
  39294. */
  39295. set: function (value) {
  39296. this._midtonesSaturation = value;
  39297. this._dirty = true;
  39298. },
  39299. enumerable: true,
  39300. configurable: true
  39301. });
  39302. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39303. /**
  39304. * Gets the midtones Exposure value.
  39305. * 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.
  39306. */
  39307. get: function () {
  39308. return this._midtonesExposure;
  39309. },
  39310. /**
  39311. * Sets the midtones Exposure value.
  39312. * 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.
  39313. */
  39314. set: function (value) {
  39315. this._midtonesExposure = value;
  39316. this._dirty = true;
  39317. },
  39318. enumerable: true,
  39319. configurable: true
  39320. });
  39321. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39322. /**
  39323. * Gets the shadows Hue value.
  39324. * 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).
  39325. */
  39326. get: function () {
  39327. return this._shadowsHue;
  39328. },
  39329. /**
  39330. * Sets the shadows Hue value.
  39331. * 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).
  39332. */
  39333. set: function (value) {
  39334. this._shadowsHue = value;
  39335. this._dirty = true;
  39336. },
  39337. enumerable: true,
  39338. configurable: true
  39339. });
  39340. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  39341. /**
  39342. * Gets the shadows Density value.
  39343. * 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.
  39344. * Values less than zero provide a filter of opposite hue.
  39345. */
  39346. get: function () {
  39347. return this._shadowsDensity;
  39348. },
  39349. /**
  39350. * Sets the shadows Density value.
  39351. * 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.
  39352. * Values less than zero provide a filter of opposite hue.
  39353. */
  39354. set: function (value) {
  39355. this._shadowsDensity = value;
  39356. this._dirty = true;
  39357. },
  39358. enumerable: true,
  39359. configurable: true
  39360. });
  39361. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  39362. /**
  39363. * Gets the shadows Saturation value.
  39364. * 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.
  39365. */
  39366. get: function () {
  39367. return this._shadowsSaturation;
  39368. },
  39369. /**
  39370. * Sets the shadows Saturation value.
  39371. * 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.
  39372. */
  39373. set: function (value) {
  39374. this._shadowsSaturation = value;
  39375. this._dirty = true;
  39376. },
  39377. enumerable: true,
  39378. configurable: true
  39379. });
  39380. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  39381. /**
  39382. * Gets the shadows Exposure value.
  39383. * 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.
  39384. */
  39385. get: function () {
  39386. return this._shadowsExposure;
  39387. },
  39388. /**
  39389. * Sets the shadows Exposure value.
  39390. * 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.
  39391. */
  39392. set: function (value) {
  39393. this._shadowsExposure = value;
  39394. this._dirty = true;
  39395. },
  39396. enumerable: true,
  39397. configurable: true
  39398. });
  39399. /**
  39400. * Binds the color curves to the shader.
  39401. * @param colorCurves The color curve to bind
  39402. * @param effect The effect to bind to
  39403. */
  39404. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39405. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39406. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39407. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39408. if (colorCurves._dirty) {
  39409. colorCurves._dirty = false;
  39410. // Fill in global info.
  39411. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39412. // Compute highlights info.
  39413. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39414. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39415. // Compute midtones info.
  39416. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39417. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39418. // Compute shadows info.
  39419. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39420. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39421. // Compute deltas (neutral is midtones).
  39422. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39423. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39424. }
  39425. if (effect) {
  39426. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39427. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39428. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39429. }
  39430. };
  39431. /**
  39432. * Prepare the list of uniforms associated with the ColorCurves effects.
  39433. * @param uniformsList The list of uniforms used in the effect
  39434. */
  39435. ColorCurves.PrepareUniforms = function (uniformsList) {
  39436. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39437. };
  39438. /**
  39439. * Returns color grading data based on a hue, density, saturation and exposure value.
  39440. * @param filterHue The hue of the color filter.
  39441. * @param filterDensity The density of the color filter.
  39442. * @param saturation The saturation.
  39443. * @param exposure The exposure.
  39444. * @param result The result data container.
  39445. */
  39446. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39447. if (hue == null) {
  39448. return;
  39449. }
  39450. hue = ColorCurves.clamp(hue, 0, 360);
  39451. density = ColorCurves.clamp(density, -100, 100);
  39452. saturation = ColorCurves.clamp(saturation, -100, 100);
  39453. exposure = ColorCurves.clamp(exposure, -100, 100);
  39454. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39455. // so that the maximum filter density is only 50% control. This provides fine control
  39456. // for small values and reasonable range.
  39457. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39458. density *= 0.5;
  39459. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39460. if (density < 0) {
  39461. density *= -1;
  39462. hue = (hue + 180) % 360;
  39463. }
  39464. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39465. result.scaleToRef(2, result);
  39466. result.a = 1 + 0.01 * saturation;
  39467. };
  39468. /**
  39469. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39470. * @param value The input slider value in range [-100,100].
  39471. * @returns Adjusted value.
  39472. */
  39473. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39474. value /= 100;
  39475. var x = Math.abs(value);
  39476. x = Math.pow(x, 2);
  39477. if (value < 0) {
  39478. x *= -1;
  39479. }
  39480. x *= 100;
  39481. return x;
  39482. };
  39483. /**
  39484. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39485. * @param hue The hue (H) input.
  39486. * @param saturation The saturation (S) input.
  39487. * @param brightness The brightness (B) input.
  39488. * @result An RGBA color represented as Vector4.
  39489. */
  39490. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39491. var h = ColorCurves.clamp(hue, 0, 360);
  39492. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39493. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39494. if (s === 0) {
  39495. result.r = v;
  39496. result.g = v;
  39497. result.b = v;
  39498. }
  39499. else {
  39500. // sector 0 to 5
  39501. h /= 60;
  39502. var i = Math.floor(h);
  39503. // fractional part of h
  39504. var f = h - i;
  39505. var p = v * (1 - s);
  39506. var q = v * (1 - s * f);
  39507. var t = v * (1 - s * (1 - f));
  39508. switch (i) {
  39509. case 0:
  39510. result.r = v;
  39511. result.g = t;
  39512. result.b = p;
  39513. break;
  39514. case 1:
  39515. result.r = q;
  39516. result.g = v;
  39517. result.b = p;
  39518. break;
  39519. case 2:
  39520. result.r = p;
  39521. result.g = v;
  39522. result.b = t;
  39523. break;
  39524. case 3:
  39525. result.r = p;
  39526. result.g = q;
  39527. result.b = v;
  39528. break;
  39529. case 4:
  39530. result.r = t;
  39531. result.g = p;
  39532. result.b = v;
  39533. break;
  39534. default:
  39535. result.r = v;
  39536. result.g = p;
  39537. result.b = q;
  39538. break;
  39539. }
  39540. }
  39541. result.a = 1;
  39542. };
  39543. /**
  39544. * Returns a value clamped between min and max
  39545. * @param value The value to clamp
  39546. * @param min The minimum of value
  39547. * @param max The maximum of value
  39548. * @returns The clamped value.
  39549. */
  39550. ColorCurves.clamp = function (value, min, max) {
  39551. return Math.min(Math.max(value, min), max);
  39552. };
  39553. /**
  39554. * Clones the current color curve instance.
  39555. * @return The cloned curves
  39556. */
  39557. ColorCurves.prototype.clone = function () {
  39558. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39559. };
  39560. /**
  39561. * Serializes the current color curve instance to a json representation.
  39562. * @return a JSON representation
  39563. */
  39564. ColorCurves.prototype.serialize = function () {
  39565. return BABYLON.SerializationHelper.Serialize(this);
  39566. };
  39567. /**
  39568. * Parses the color curve from a json representation.
  39569. * @param source the JSON source to parse
  39570. * @return The parsed curves
  39571. */
  39572. ColorCurves.Parse = function (source) {
  39573. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39574. };
  39575. return ColorCurves;
  39576. }());
  39577. __decorate([
  39578. BABYLON.serialize()
  39579. ], ColorCurves.prototype, "_globalHue", void 0);
  39580. __decorate([
  39581. BABYLON.serialize()
  39582. ], ColorCurves.prototype, "_globalDensity", void 0);
  39583. __decorate([
  39584. BABYLON.serialize()
  39585. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39586. __decorate([
  39587. BABYLON.serialize()
  39588. ], ColorCurves.prototype, "_globalExposure", void 0);
  39589. __decorate([
  39590. BABYLON.serialize()
  39591. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39592. __decorate([
  39593. BABYLON.serialize()
  39594. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39595. __decorate([
  39596. BABYLON.serialize()
  39597. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39598. __decorate([
  39599. BABYLON.serialize()
  39600. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39601. __decorate([
  39602. BABYLON.serialize()
  39603. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39604. __decorate([
  39605. BABYLON.serialize()
  39606. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39607. __decorate([
  39608. BABYLON.serialize()
  39609. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39610. __decorate([
  39611. BABYLON.serialize()
  39612. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39613. BABYLON.ColorCurves = ColorCurves;
  39614. })(BABYLON || (BABYLON = {}));
  39615. //# sourceMappingURL=babylon.colorCurves.js.map
  39616. var BABYLON;
  39617. (function (BABYLON) {
  39618. var PostProcessRenderPipelineManager = (function () {
  39619. function PostProcessRenderPipelineManager() {
  39620. this._renderPipelines = {};
  39621. }
  39622. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39623. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39624. };
  39625. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39626. var renderPipeline = this._renderPipelines[renderPipelineName];
  39627. if (!renderPipeline) {
  39628. return;
  39629. }
  39630. renderPipeline._attachCameras(cameras, unique);
  39631. };
  39632. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39633. var renderPipeline = this._renderPipelines[renderPipelineName];
  39634. if (!renderPipeline) {
  39635. return;
  39636. }
  39637. renderPipeline._detachCameras(cameras);
  39638. };
  39639. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39640. var renderPipeline = this._renderPipelines[renderPipelineName];
  39641. if (!renderPipeline) {
  39642. return;
  39643. }
  39644. renderPipeline._enableEffect(renderEffectName, cameras);
  39645. };
  39646. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39647. var renderPipeline = this._renderPipelines[renderPipelineName];
  39648. if (!renderPipeline) {
  39649. return;
  39650. }
  39651. renderPipeline._disableEffect(renderEffectName, cameras);
  39652. };
  39653. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39654. var renderPipeline = this._renderPipelines[renderPipelineName];
  39655. if (!renderPipeline) {
  39656. return;
  39657. }
  39658. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39659. };
  39660. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39661. var renderPipeline = this._renderPipelines[renderPipelineName];
  39662. if (!renderPipeline) {
  39663. return;
  39664. }
  39665. renderPipeline._disableDisplayOnlyPass(cameras);
  39666. };
  39667. PostProcessRenderPipelineManager.prototype.update = function () {
  39668. for (var renderPipelineName in this._renderPipelines) {
  39669. var pipeline = this._renderPipelines[renderPipelineName];
  39670. if (!pipeline.isSupported) {
  39671. pipeline.dispose();
  39672. delete this._renderPipelines[renderPipelineName];
  39673. }
  39674. else {
  39675. pipeline._update();
  39676. }
  39677. }
  39678. };
  39679. return PostProcessRenderPipelineManager;
  39680. }());
  39681. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39682. })(BABYLON || (BABYLON = {}));
  39683. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39684. var BABYLON;
  39685. (function (BABYLON) {
  39686. var PostProcessRenderPass = (function () {
  39687. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39688. this._enabled = true;
  39689. this._refCount = 0;
  39690. this._name = name;
  39691. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39692. this.setRenderList(renderList);
  39693. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39694. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39695. this._scene = scene;
  39696. this._renderList = renderList;
  39697. }
  39698. // private
  39699. PostProcessRenderPass.prototype._incRefCount = function () {
  39700. if (this._refCount === 0) {
  39701. this._scene.customRenderTargets.push(this._renderTexture);
  39702. }
  39703. return ++this._refCount;
  39704. };
  39705. PostProcessRenderPass.prototype._decRefCount = function () {
  39706. this._refCount--;
  39707. if (this._refCount <= 0) {
  39708. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39709. }
  39710. return this._refCount;
  39711. };
  39712. PostProcessRenderPass.prototype._update = function () {
  39713. this.setRenderList(this._renderList);
  39714. };
  39715. // public
  39716. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39717. this._renderTexture.renderList = renderList;
  39718. };
  39719. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39720. return this._renderTexture;
  39721. };
  39722. return PostProcessRenderPass;
  39723. }());
  39724. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39725. })(BABYLON || (BABYLON = {}));
  39726. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39727. var BABYLON;
  39728. (function (BABYLON) {
  39729. var PostProcessRenderEffect = (function () {
  39730. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39731. this._engine = engine;
  39732. this._name = name;
  39733. this._singleInstance = singleInstance || true;
  39734. this._getPostProcess = getPostProcess;
  39735. this._cameras = [];
  39736. this._indicesForCamera = [];
  39737. this._postProcesses = {};
  39738. this._renderPasses = {};
  39739. this._renderEffectAsPasses = {};
  39740. }
  39741. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39742. get: function () {
  39743. for (var index in this._postProcesses) {
  39744. if (!this._postProcesses[index].isSupported) {
  39745. return false;
  39746. }
  39747. }
  39748. return true;
  39749. },
  39750. enumerable: true,
  39751. configurable: true
  39752. });
  39753. PostProcessRenderEffect.prototype._update = function () {
  39754. for (var renderPassName in this._renderPasses) {
  39755. this._renderPasses[renderPassName]._update();
  39756. }
  39757. };
  39758. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39759. this._renderPasses[renderPass._name] = renderPass;
  39760. this._linkParameters();
  39761. };
  39762. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39763. delete this._renderPasses[renderPass._name];
  39764. this._linkParameters();
  39765. };
  39766. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39767. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39768. this._linkParameters();
  39769. };
  39770. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39771. for (var renderPassName in this._renderPasses) {
  39772. if (renderPassName === passName) {
  39773. return this._renderPasses[passName];
  39774. }
  39775. }
  39776. };
  39777. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39778. this._renderPasses = {};
  39779. this._linkParameters();
  39780. };
  39781. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39782. var cameraKey;
  39783. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39784. for (var i = 0; i < _cam.length; i++) {
  39785. var camera = _cam[i];
  39786. var cameraName = camera.name;
  39787. if (this._singleInstance) {
  39788. cameraKey = 0;
  39789. }
  39790. else {
  39791. cameraKey = cameraName;
  39792. }
  39793. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39794. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39795. if (!this._indicesForCamera[cameraName]) {
  39796. this._indicesForCamera[cameraName] = [];
  39797. }
  39798. this._indicesForCamera[cameraName].push(index);
  39799. if (this._cameras.indexOf(camera) === -1) {
  39800. this._cameras[cameraName] = camera;
  39801. }
  39802. for (var passName in this._renderPasses) {
  39803. this._renderPasses[passName]._incRefCount();
  39804. }
  39805. }
  39806. this._linkParameters();
  39807. };
  39808. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39809. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39810. for (var i = 0; i < _cam.length; i++) {
  39811. var camera = _cam[i];
  39812. var cameraName = camera.name;
  39813. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39814. var index = this._cameras.indexOf(cameraName);
  39815. this._indicesForCamera.splice(index, 1);
  39816. this._cameras.splice(index, 1);
  39817. for (var passName in this._renderPasses) {
  39818. this._renderPasses[passName]._decRefCount();
  39819. }
  39820. }
  39821. };
  39822. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39823. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39824. for (var i = 0; i < _cam.length; i++) {
  39825. var camera = _cam[i];
  39826. var cameraName = camera.name;
  39827. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39828. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39829. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39830. }
  39831. }
  39832. for (var passName in this._renderPasses) {
  39833. this._renderPasses[passName]._incRefCount();
  39834. }
  39835. }
  39836. };
  39837. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39838. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39839. for (var i = 0; i < _cam.length; i++) {
  39840. var camera = _cam[i];
  39841. var cameraName = camera.Name;
  39842. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39843. for (var passName in this._renderPasses) {
  39844. this._renderPasses[passName]._decRefCount();
  39845. }
  39846. }
  39847. };
  39848. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39849. if (this._singleInstance) {
  39850. return this._postProcesses[0];
  39851. }
  39852. else {
  39853. return this._postProcesses[camera.name];
  39854. }
  39855. };
  39856. PostProcessRenderEffect.prototype._linkParameters = function () {
  39857. var _this = this;
  39858. for (var index in this._postProcesses) {
  39859. if (this.applyParameters) {
  39860. this.applyParameters(this._postProcesses[index]);
  39861. }
  39862. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39863. _this._linkTextures(effect);
  39864. });
  39865. }
  39866. };
  39867. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39868. for (var renderPassName in this._renderPasses) {
  39869. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39870. }
  39871. for (var renderEffectName in this._renderEffectAsPasses) {
  39872. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39873. }
  39874. };
  39875. return PostProcessRenderEffect;
  39876. }());
  39877. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39878. })(BABYLON || (BABYLON = {}));
  39879. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39880. var BABYLON;
  39881. (function (BABYLON) {
  39882. var PostProcessRenderPipeline = (function () {
  39883. function PostProcessRenderPipeline(engine, name) {
  39884. this._engine = engine;
  39885. this._name = name;
  39886. this._renderEffects = new Array();
  39887. this._renderEffectsForIsolatedPass = new Array();
  39888. this._cameras = [];
  39889. }
  39890. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39891. get: function () {
  39892. for (var renderEffectName in this._renderEffects) {
  39893. if (!this._renderEffects[renderEffectName].isSupported) {
  39894. return false;
  39895. }
  39896. }
  39897. return true;
  39898. },
  39899. enumerable: true,
  39900. configurable: true
  39901. });
  39902. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39903. this._renderEffects[renderEffect._name] = renderEffect;
  39904. };
  39905. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39906. var renderEffects = this._renderEffects[renderEffectName];
  39907. if (!renderEffects) {
  39908. return;
  39909. }
  39910. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39911. };
  39912. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39913. var renderEffects = this._renderEffects[renderEffectName];
  39914. if (!renderEffects) {
  39915. return;
  39916. }
  39917. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39918. };
  39919. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39920. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39921. var indicesToDelete = [];
  39922. var i;
  39923. for (i = 0; i < _cam.length; i++) {
  39924. var camera = _cam[i];
  39925. var cameraName = camera.name;
  39926. if (this._cameras.indexOf(camera) === -1) {
  39927. this._cameras[cameraName] = camera;
  39928. }
  39929. else if (unique) {
  39930. indicesToDelete.push(i);
  39931. }
  39932. }
  39933. for (i = 0; i < indicesToDelete.length; i++) {
  39934. cameras.splice(indicesToDelete[i], 1);
  39935. }
  39936. for (var renderEffectName in this._renderEffects) {
  39937. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39938. }
  39939. };
  39940. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39941. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39942. for (var renderEffectName in this._renderEffects) {
  39943. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39944. }
  39945. for (var i = 0; i < _cam.length; i++) {
  39946. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39947. }
  39948. };
  39949. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39950. var _this = this;
  39951. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39952. var pass = null;
  39953. var renderEffectName;
  39954. for (renderEffectName in this._renderEffects) {
  39955. pass = this._renderEffects[renderEffectName].getPass(passName);
  39956. if (pass != null) {
  39957. break;
  39958. }
  39959. }
  39960. if (pass === null) {
  39961. return;
  39962. }
  39963. for (renderEffectName in this._renderEffects) {
  39964. this._renderEffects[renderEffectName]._disable(_cam);
  39965. }
  39966. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39967. for (var i = 0; i < _cam.length; i++) {
  39968. var camera = _cam[i];
  39969. var cameraName = camera.name;
  39970. 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); });
  39971. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39972. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39973. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39974. }
  39975. };
  39976. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39977. var _this = this;
  39978. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39979. for (var i = 0; i < _cam.length; i++) {
  39980. var camera = _cam[i];
  39981. var cameraName = camera.name;
  39982. 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); });
  39983. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39984. }
  39985. for (var renderEffectName in this._renderEffects) {
  39986. this._renderEffects[renderEffectName]._enable(_cam);
  39987. }
  39988. };
  39989. PostProcessRenderPipeline.prototype._update = function () {
  39990. for (var renderEffectName in this._renderEffects) {
  39991. this._renderEffects[renderEffectName]._update();
  39992. }
  39993. for (var i = 0; i < this._cameras.length; i++) {
  39994. var cameraName = this._cameras[i].name;
  39995. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39996. this._renderEffectsForIsolatedPass[cameraName]._update();
  39997. }
  39998. }
  39999. };
  40000. PostProcessRenderPipeline.prototype._reset = function () {
  40001. this._renderEffects = new Array();
  40002. this._renderEffectsForIsolatedPass = new Array();
  40003. };
  40004. PostProcessRenderPipeline.prototype.dispose = function () {
  40005. // Must be implemented by children
  40006. };
  40007. return PostProcessRenderPipeline;
  40008. }());
  40009. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40010. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40011. __decorate([
  40012. BABYLON.serialize()
  40013. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  40014. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40015. })(BABYLON || (BABYLON = {}));
  40016. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40017. var BABYLON;
  40018. (function (BABYLON) {
  40019. var DefaultRenderingPipeline = (function (_super) {
  40020. __extends(DefaultRenderingPipeline, _super);
  40021. /**
  40022. * @constructor
  40023. * @param {string} name - The rendering pipeline name
  40024. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40025. * @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)
  40026. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40027. */
  40028. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  40029. var _this = _super.call(this, scene.getEngine(), name) || this;
  40030. _this.PassPostProcessId = "PassPostProcessEffect";
  40031. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  40032. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  40033. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  40034. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  40035. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  40036. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  40037. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  40038. // IAnimatable
  40039. _this.animations = [];
  40040. // Values
  40041. _this._bloomEnabled = false;
  40042. _this._fxaaEnabled = false;
  40043. _this._imageProcessingEnabled = true;
  40044. _this._bloomScale = 0.6;
  40045. /**
  40046. * Specifies the size of the bloom blur kernel, relative to the final output size
  40047. */
  40048. _this.bloomKernel = 64;
  40049. /**
  40050. * Specifies the weight of the bloom in the final rendering
  40051. */
  40052. _this._bloomWeight = 0.15;
  40053. _this._cameras = cameras || [];
  40054. // Initialize
  40055. _this._scene = scene;
  40056. var caps = _this._scene.getEngine().getCaps();
  40057. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  40058. // Misc
  40059. if (_this._hdr) {
  40060. if (caps.textureHalfFloatRender) {
  40061. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  40062. }
  40063. else if (caps.textureFloatRender) {
  40064. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40065. }
  40066. }
  40067. else {
  40068. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40069. }
  40070. // Attach
  40071. scene.postProcessRenderPipelineManager.addPipeline(_this);
  40072. _this._buildPipeline();
  40073. return _this;
  40074. }
  40075. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  40076. get: function () {
  40077. return this._bloomWeight;
  40078. },
  40079. set: function (value) {
  40080. if (this._bloomWeight === value) {
  40081. return;
  40082. }
  40083. this._bloomWeight = value;
  40084. if (this._hdr && this.copyBack) {
  40085. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  40086. }
  40087. },
  40088. enumerable: true,
  40089. configurable: true
  40090. });
  40091. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  40092. get: function () {
  40093. return this._bloomScale;
  40094. },
  40095. set: function (value) {
  40096. if (this._bloomScale === value) {
  40097. return;
  40098. }
  40099. this._bloomScale = value;
  40100. this._buildPipeline();
  40101. },
  40102. enumerable: true,
  40103. configurable: true
  40104. });
  40105. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  40106. get: function () {
  40107. return this._bloomEnabled;
  40108. },
  40109. set: function (enabled) {
  40110. if (this._bloomEnabled === enabled) {
  40111. return;
  40112. }
  40113. this._bloomEnabled = enabled;
  40114. this._buildPipeline();
  40115. },
  40116. enumerable: true,
  40117. configurable: true
  40118. });
  40119. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  40120. get: function () {
  40121. return this._fxaaEnabled;
  40122. },
  40123. set: function (enabled) {
  40124. if (this._fxaaEnabled === enabled) {
  40125. return;
  40126. }
  40127. this._fxaaEnabled = enabled;
  40128. this._buildPipeline();
  40129. },
  40130. enumerable: true,
  40131. configurable: true
  40132. });
  40133. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  40134. get: function () {
  40135. return this._imageProcessingEnabled;
  40136. },
  40137. set: function (enabled) {
  40138. if (this._imageProcessingEnabled === enabled) {
  40139. return;
  40140. }
  40141. this._imageProcessingEnabled = enabled;
  40142. this._buildPipeline();
  40143. },
  40144. enumerable: true,
  40145. configurable: true
  40146. });
  40147. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  40148. var _this = this;
  40149. var engine = this._scene.getEngine();
  40150. this._disposePostProcesses();
  40151. this._reset();
  40152. if (this.bloomEnabled) {
  40153. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40154. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  40155. if (!this._hdr) {
  40156. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40157. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  40158. this.highlights.autoClear = false;
  40159. this.highlights.alwaysForcePOT = true;
  40160. }
  40161. 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);
  40162. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  40163. this.blurX.alwaysForcePOT = true;
  40164. this.blurX.autoClear = false;
  40165. this.blurX.onActivateObservable.add(function () {
  40166. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  40167. _this.blurX.kernel = _this.bloomKernel * dw;
  40168. });
  40169. 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);
  40170. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  40171. this.blurY.alwaysForcePOT = true;
  40172. this.blurY.autoClear = false;
  40173. this.blurY.onActivateObservable.add(function () {
  40174. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  40175. _this.blurY.kernel = _this.bloomKernel * dh;
  40176. });
  40177. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40178. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  40179. this.copyBack.alwaysForcePOT = true;
  40180. if (this._hdr) {
  40181. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  40182. var w = this.bloomWeight;
  40183. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  40184. }
  40185. else {
  40186. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  40187. }
  40188. this.copyBack.autoClear = false;
  40189. }
  40190. if (this._imageProcessingEnabled) {
  40191. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40192. if (this._hdr) {
  40193. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  40194. }
  40195. }
  40196. if (this.fxaaEnabled) {
  40197. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40198. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  40199. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40200. }
  40201. else {
  40202. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40203. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  40204. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40205. }
  40206. if (this.bloomEnabled) {
  40207. if (this._hdr) {
  40208. this.copyBack.shareOutputWith(this.blurX);
  40209. if (this.imageProcessing) {
  40210. this.imageProcessing.shareOutputWith(this.pass);
  40211. this.imageProcessing.autoClear = false;
  40212. }
  40213. else if (this.fxaa) {
  40214. this.fxaa.shareOutputWith(this.pass);
  40215. }
  40216. else {
  40217. this.finalMerge.shareOutputWith(this.pass);
  40218. }
  40219. }
  40220. else {
  40221. if (this.fxaa) {
  40222. this.fxaa.shareOutputWith(this.pass);
  40223. }
  40224. else {
  40225. this.finalMerge.shareOutputWith(this.pass);
  40226. }
  40227. }
  40228. }
  40229. if (this._cameras !== null) {
  40230. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  40231. }
  40232. };
  40233. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  40234. for (var i = 0; i < this._cameras.length; i++) {
  40235. var camera = this._cameras[i];
  40236. if (this.pass) {
  40237. this.pass.dispose(camera);
  40238. }
  40239. if (this.highlights) {
  40240. this.highlights.dispose(camera);
  40241. }
  40242. if (this.blurX) {
  40243. this.blurX.dispose(camera);
  40244. }
  40245. if (this.blurY) {
  40246. this.blurY.dispose(camera);
  40247. }
  40248. if (this.copyBack) {
  40249. this.copyBack.dispose(camera);
  40250. }
  40251. if (this.imageProcessing) {
  40252. this.imageProcessing.dispose(camera);
  40253. }
  40254. if (this.fxaa) {
  40255. this.fxaa.dispose(camera);
  40256. }
  40257. if (this.finalMerge) {
  40258. this.finalMerge.dispose(camera);
  40259. }
  40260. }
  40261. this.pass = null;
  40262. this.highlights = null;
  40263. this.blurX = null;
  40264. this.blurY = null;
  40265. this.copyBack = null;
  40266. this.imageProcessing = null;
  40267. this.fxaa = null;
  40268. this.finalMerge = null;
  40269. };
  40270. // Dispose
  40271. DefaultRenderingPipeline.prototype.dispose = function () {
  40272. this._disposePostProcesses();
  40273. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  40274. _super.prototype.dispose.call(this);
  40275. };
  40276. // Serialize rendering pipeline
  40277. DefaultRenderingPipeline.prototype.serialize = function () {
  40278. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40279. serializationObject.customType = "DefaultRenderingPipeline";
  40280. return serializationObject;
  40281. };
  40282. // Parse serialized pipeline
  40283. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  40284. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  40285. };
  40286. return DefaultRenderingPipeline;
  40287. }(BABYLON.PostProcessRenderPipeline));
  40288. __decorate([
  40289. BABYLON.serialize()
  40290. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  40291. __decorate([
  40292. BABYLON.serialize()
  40293. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  40294. __decorate([
  40295. BABYLON.serialize()
  40296. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  40297. __decorate([
  40298. BABYLON.serialize()
  40299. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  40300. __decorate([
  40301. BABYLON.serialize()
  40302. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  40303. __decorate([
  40304. BABYLON.serialize()
  40305. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  40306. __decorate([
  40307. BABYLON.serialize()
  40308. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  40309. __decorate([
  40310. BABYLON.serialize()
  40311. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  40312. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  40313. })(BABYLON || (BABYLON = {}));
  40314. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  40315. var BABYLON;
  40316. (function (BABYLON) {
  40317. /**
  40318. * This groups together the common properties used for image processing either in direct forward pass
  40319. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40320. * or not.
  40321. */
  40322. var ImageProcessingConfiguration = (function () {
  40323. function ImageProcessingConfiguration() {
  40324. /**
  40325. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40326. */
  40327. this.colorCurves = new BABYLON.ColorCurves();
  40328. this._colorCurvesEnabled = false;
  40329. this._colorGradingEnabled = false;
  40330. this._colorGradingWithGreenDepth = false;
  40331. this._colorGradingBGR = false;
  40332. this._exposure = 1.0;
  40333. this._toneMappingEnabled = false;
  40334. this._contrast = 1.0;
  40335. /**
  40336. * Vignette stretch size.
  40337. */
  40338. this.vignetteStretch = 0;
  40339. /**
  40340. * Vignette centre X Offset.
  40341. */
  40342. this.vignetteCentreX = 0;
  40343. /**
  40344. * Vignette centre Y Offset.
  40345. */
  40346. this.vignetteCentreY = 0;
  40347. /**
  40348. * Vignette weight or intensity of the vignette effect.
  40349. */
  40350. this.vignetteWeight = 1.5;
  40351. /**
  40352. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40353. * if vignetteEnabled is set to true.
  40354. */
  40355. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40356. /**
  40357. * Camera field of view used by the Vignette effect.
  40358. */
  40359. this.vignetteCameraFov = 0.5;
  40360. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40361. this._vignetteEnabled = false;
  40362. this._applyByPostProcess = false;
  40363. /**
  40364. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40365. * @type {BABYLON.Observable}
  40366. */
  40367. this.onUpdateParameters = new BABYLON.Observable();
  40368. }
  40369. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40370. /**
  40371. * Gets wether the color curves effect is enabled.
  40372. */
  40373. get: function () {
  40374. return this._colorCurvesEnabled;
  40375. },
  40376. /**
  40377. * Sets wether the color curves effect is enabled.
  40378. */
  40379. set: function (value) {
  40380. if (this._colorCurvesEnabled === value) {
  40381. return;
  40382. }
  40383. this._colorCurvesEnabled = value;
  40384. this._updateParameters();
  40385. },
  40386. enumerable: true,
  40387. configurable: true
  40388. });
  40389. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40390. /**
  40391. * Gets wether the color grading effect is enabled.
  40392. */
  40393. get: function () {
  40394. return this._colorGradingEnabled;
  40395. },
  40396. /**
  40397. * Sets wether the color grading effect is enabled.
  40398. */
  40399. set: function (value) {
  40400. if (this._colorGradingEnabled === value) {
  40401. return;
  40402. }
  40403. this._colorGradingEnabled = value;
  40404. this._updateParameters();
  40405. },
  40406. enumerable: true,
  40407. configurable: true
  40408. });
  40409. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40410. /**
  40411. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40412. */
  40413. get: function () {
  40414. return this._colorGradingWithGreenDepth;
  40415. },
  40416. /**
  40417. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40418. */
  40419. set: function (value) {
  40420. if (this._colorGradingWithGreenDepth === value) {
  40421. return;
  40422. }
  40423. this._colorGradingWithGreenDepth = value;
  40424. this._updateParameters();
  40425. },
  40426. enumerable: true,
  40427. configurable: true
  40428. });
  40429. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40430. /**
  40431. * Gets wether the color grading texture contains BGR values.
  40432. */
  40433. get: function () {
  40434. return this._colorGradingBGR;
  40435. },
  40436. /**
  40437. * Sets wether the color grading texture contains BGR values.
  40438. */
  40439. set: function (value) {
  40440. if (this._colorGradingBGR === value) {
  40441. return;
  40442. }
  40443. this._colorGradingBGR = value;
  40444. this._updateParameters();
  40445. },
  40446. enumerable: true,
  40447. configurable: true
  40448. });
  40449. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40450. /**
  40451. * Gets the Exposure used in the effect.
  40452. */
  40453. get: function () {
  40454. return this._exposure;
  40455. },
  40456. /**
  40457. * Sets the Exposure used in the effect.
  40458. */
  40459. set: function (value) {
  40460. if (this._exposure === value) {
  40461. return;
  40462. }
  40463. this._exposure = value;
  40464. this._updateParameters();
  40465. },
  40466. enumerable: true,
  40467. configurable: true
  40468. });
  40469. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40470. /**
  40471. * Gets wether the tone mapping effect is enabled.
  40472. */
  40473. get: function () {
  40474. return this._toneMappingEnabled;
  40475. },
  40476. /**
  40477. * Sets wether the tone mapping effect is enabled.
  40478. */
  40479. set: function (value) {
  40480. if (this._toneMappingEnabled === value) {
  40481. return;
  40482. }
  40483. this._toneMappingEnabled = value;
  40484. this._updateParameters();
  40485. },
  40486. enumerable: true,
  40487. configurable: true
  40488. });
  40489. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40490. /**
  40491. * Gets the contrast used in the effect.
  40492. */
  40493. get: function () {
  40494. return this._contrast;
  40495. },
  40496. /**
  40497. * Sets the contrast used in the effect.
  40498. */
  40499. set: function (value) {
  40500. if (this._contrast === value) {
  40501. return;
  40502. }
  40503. this._contrast = value;
  40504. this._updateParameters();
  40505. },
  40506. enumerable: true,
  40507. configurable: true
  40508. });
  40509. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40510. /**
  40511. * Gets the vignette blend mode allowing different kind of effect.
  40512. */
  40513. get: function () {
  40514. return this._vignetteBlendMode;
  40515. },
  40516. /**
  40517. * Sets the vignette blend mode allowing different kind of effect.
  40518. */
  40519. set: function (value) {
  40520. if (this._vignetteBlendMode === value) {
  40521. return;
  40522. }
  40523. this._vignetteBlendMode = value;
  40524. this._updateParameters();
  40525. },
  40526. enumerable: true,
  40527. configurable: true
  40528. });
  40529. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40530. /**
  40531. * Gets wether the vignette effect is enabled.
  40532. */
  40533. get: function () {
  40534. return this._vignetteEnabled;
  40535. },
  40536. /**
  40537. * Sets wether the vignette effect is enabled.
  40538. */
  40539. set: function (value) {
  40540. if (this._vignetteEnabled === value) {
  40541. return;
  40542. }
  40543. this._vignetteEnabled = value;
  40544. this._updateParameters();
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40550. /**
  40551. * Gets wether the image processing is applied through a post process or not.
  40552. */
  40553. get: function () {
  40554. return this._applyByPostProcess;
  40555. },
  40556. /**
  40557. * Sets wether the image processing is applied through a post process or not.
  40558. */
  40559. set: function (value) {
  40560. if (this._applyByPostProcess === value) {
  40561. return;
  40562. }
  40563. this._applyByPostProcess = value;
  40564. this._updateParameters();
  40565. },
  40566. enumerable: true,
  40567. configurable: true
  40568. });
  40569. /**
  40570. * Method called each time the image processing information changes requires to recompile the effect.
  40571. */
  40572. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40573. this.onUpdateParameters.notifyObservers(this);
  40574. };
  40575. /**
  40576. * Prepare the list of uniforms associated with the Image Processing effects.
  40577. * @param uniformsList The list of uniforms used in the effect
  40578. * @param defines the list of defines currently in use
  40579. */
  40580. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40581. if (defines.EXPOSURE) {
  40582. uniforms.push("exposureLinear");
  40583. }
  40584. if (defines.CONTRAST) {
  40585. uniforms.push("contrast");
  40586. }
  40587. if (defines.COLORGRADING) {
  40588. uniforms.push("colorTransformSettings");
  40589. }
  40590. if (defines.VIGNETTE) {
  40591. uniforms.push("vInverseScreenSize");
  40592. uniforms.push("vignetteSettings1");
  40593. uniforms.push("vignetteSettings2");
  40594. }
  40595. if (defines.COLORCURVES) {
  40596. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40597. }
  40598. };
  40599. /**
  40600. * Prepare the list of samplers associated with the Image Processing effects.
  40601. * @param uniformsList The list of uniforms used in the effect
  40602. * @param defines the list of defines currently in use
  40603. */
  40604. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40605. if (defines.COLORGRADING) {
  40606. samplersList.push("txColorTransform");
  40607. }
  40608. };
  40609. /**
  40610. * Prepare the list of defines associated to the shader.
  40611. * @param defines the list of defines to complete
  40612. */
  40613. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  40614. defines.VIGNETTE = this.vignetteEnabled;
  40615. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40616. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40617. defines.TONEMAPPING = this.toneMappingEnabled;
  40618. defines.CONTRAST = (this.contrast !== 1.0);
  40619. defines.EXPOSURE = (this.exposure !== 1.0);
  40620. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40621. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40622. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40623. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40624. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40625. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40626. };
  40627. /**
  40628. * Returns true if all the image processing information are ready.
  40629. */
  40630. ImageProcessingConfiguration.prototype.isReady = function () {
  40631. // Color Grading texure can not be none blocking.
  40632. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40633. };
  40634. /**
  40635. * Binds the image processing to the shader.
  40636. * @param effect The effect to bind to
  40637. */
  40638. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40639. if (aspectRatio === void 0) { aspectRatio = 1; }
  40640. // Color Curves
  40641. if (this._colorCurvesEnabled) {
  40642. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40643. }
  40644. // Vignette
  40645. if (this._vignetteEnabled) {
  40646. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40647. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40648. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40649. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40650. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40651. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40652. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40653. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40654. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40655. var vignettePower = -2.0 * this.vignetteWeight;
  40656. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40657. }
  40658. // Exposure
  40659. effect.setFloat("exposureLinear", this.exposure);
  40660. // Contrast
  40661. effect.setFloat("contrast", this.contrast);
  40662. // Color transform settings
  40663. if (this.colorGradingTexture) {
  40664. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40665. var textureSize = this.colorGradingTexture.getSize().height;
  40666. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40667. 0.5 / textureSize, // textureOffset
  40668. textureSize, // textureSize
  40669. this.colorGradingTexture.level // weight
  40670. );
  40671. }
  40672. };
  40673. /**
  40674. * Clones the current image processing instance.
  40675. * @return The cloned image processing
  40676. */
  40677. ImageProcessingConfiguration.prototype.clone = function () {
  40678. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40679. };
  40680. /**
  40681. * Serializes the current image processing instance to a json representation.
  40682. * @return a JSON representation
  40683. */
  40684. ImageProcessingConfiguration.prototype.serialize = function () {
  40685. return BABYLON.SerializationHelper.Serialize(this);
  40686. };
  40687. /**
  40688. * Parses the image processing from a json representation.
  40689. * @param source the JSON source to parse
  40690. * @return The parsed image processing
  40691. */
  40692. ImageProcessingConfiguration.Parse = function (source) {
  40693. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40694. };
  40695. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40696. /**
  40697. * Used to apply the vignette as a mix with the pixel color.
  40698. */
  40699. get: function () {
  40700. return this._VIGNETTEMODE_MULTIPLY;
  40701. },
  40702. enumerable: true,
  40703. configurable: true
  40704. });
  40705. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40706. /**
  40707. * Used to apply the vignette as a replacement of the pixel color.
  40708. */
  40709. get: function () {
  40710. return this._VIGNETTEMODE_OPAQUE;
  40711. },
  40712. enumerable: true,
  40713. configurable: true
  40714. });
  40715. return ImageProcessingConfiguration;
  40716. }());
  40717. // Static constants associated to the image processing.
  40718. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40719. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40720. __decorate([
  40721. BABYLON.serializeAsColorCurves()
  40722. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40723. __decorate([
  40724. BABYLON.serialize()
  40725. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40726. __decorate([
  40727. BABYLON.serializeAsTexture()
  40728. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40729. __decorate([
  40730. BABYLON.serialize()
  40731. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40732. __decorate([
  40733. BABYLON.serialize()
  40734. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40735. __decorate([
  40736. BABYLON.serialize()
  40737. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40738. __decorate([
  40739. BABYLON.serialize()
  40740. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40741. __decorate([
  40742. BABYLON.serialize()
  40743. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40744. __decorate([
  40745. BABYLON.serialize()
  40746. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40747. __decorate([
  40748. BABYLON.serialize()
  40749. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40750. __decorate([
  40751. BABYLON.serialize()
  40752. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40753. __decorate([
  40754. BABYLON.serialize()
  40755. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40756. __decorate([
  40757. BABYLON.serialize()
  40758. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40759. __decorate([
  40760. BABYLON.serializeAsColor4()
  40761. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40762. __decorate([
  40763. BABYLON.serialize()
  40764. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40765. __decorate([
  40766. BABYLON.serialize()
  40767. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40768. __decorate([
  40769. BABYLON.serialize()
  40770. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40771. __decorate([
  40772. BABYLON.serialize()
  40773. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40774. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40775. })(BABYLON || (BABYLON = {}));
  40776. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40777. /// <reference path="babylon.mesh.ts" />
  40778. var BABYLON;
  40779. (function (BABYLON) {
  40780. var GroundMesh = (function (_super) {
  40781. __extends(GroundMesh, _super);
  40782. function GroundMesh(name, scene) {
  40783. var _this = _super.call(this, name, scene) || this;
  40784. _this.generateOctree = false;
  40785. _this._worldInverse = new BABYLON.Matrix();
  40786. return _this;
  40787. }
  40788. GroundMesh.prototype.getClassName = function () {
  40789. return "GroundMesh";
  40790. };
  40791. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40792. get: function () {
  40793. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40794. },
  40795. enumerable: true,
  40796. configurable: true
  40797. });
  40798. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40799. get: function () {
  40800. return this._subdivisionsX;
  40801. },
  40802. enumerable: true,
  40803. configurable: true
  40804. });
  40805. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40806. get: function () {
  40807. return this._subdivisionsY;
  40808. },
  40809. enumerable: true,
  40810. configurable: true
  40811. });
  40812. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40813. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40814. this._subdivisionsX = chunksCount;
  40815. this._subdivisionsY = chunksCount;
  40816. this.subdivide(chunksCount);
  40817. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40818. };
  40819. /**
  40820. * Returns a height (y) value in the Worl system :
  40821. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40822. * Returns the ground y position if (x, z) are outside the ground surface.
  40823. */
  40824. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40825. var world = this.getWorldMatrix();
  40826. var invMat = BABYLON.Tmp.Matrix[5];
  40827. world.invertToRef(invMat);
  40828. var tmpVect = BABYLON.Tmp.Vector3[8];
  40829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40830. x = tmpVect.x;
  40831. z = tmpVect.z;
  40832. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40833. return this.position.y;
  40834. }
  40835. if (!this._heightQuads || this._heightQuads.length == 0) {
  40836. this._initHeightQuads();
  40837. this._computeHeightQuads();
  40838. }
  40839. var facet = this._getFacetAt(x, z);
  40840. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40841. // return y in the World system
  40842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40843. return tmpVect.y;
  40844. };
  40845. /**
  40846. * Returns a normalized vector (Vector3) orthogonal to the ground
  40847. * at the ground coordinates (x, z) expressed in the World system.
  40848. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40849. */
  40850. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40851. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40852. this.getNormalAtCoordinatesToRef(x, z, normal);
  40853. return normal;
  40854. };
  40855. /**
  40856. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40857. * at the ground coordinates (x, z) expressed in the World system.
  40858. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40859. * Returns the GroundMesh.
  40860. */
  40861. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40862. var world = this.getWorldMatrix();
  40863. var tmpMat = BABYLON.Tmp.Matrix[5];
  40864. world.invertToRef(tmpMat);
  40865. var tmpVect = BABYLON.Tmp.Vector3[8];
  40866. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40867. x = tmpVect.x;
  40868. z = tmpVect.z;
  40869. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40870. return this;
  40871. }
  40872. if (!this._heightQuads || this._heightQuads.length == 0) {
  40873. this._initHeightQuads();
  40874. this._computeHeightQuads();
  40875. }
  40876. var facet = this._getFacetAt(x, z);
  40877. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40878. return this;
  40879. };
  40880. /**
  40881. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40882. * if the ground has been updated.
  40883. * This can be used in the render loop.
  40884. * Returns the GroundMesh.
  40885. */
  40886. GroundMesh.prototype.updateCoordinateHeights = function () {
  40887. if (!this._heightQuads || this._heightQuads.length == 0) {
  40888. this._initHeightQuads();
  40889. }
  40890. this._computeHeightQuads();
  40891. return this;
  40892. };
  40893. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40894. GroundMesh.prototype._getFacetAt = function (x, z) {
  40895. // retrieve col and row from x, z coordinates in the ground local system
  40896. var subdivisionsX = this._subdivisionsX;
  40897. var subdivisionsY = this._subdivisionsY;
  40898. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40899. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40900. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40901. var facet;
  40902. if (z < quad.slope.x * x + quad.slope.y) {
  40903. facet = quad.facet1;
  40904. }
  40905. else {
  40906. facet = quad.facet2;
  40907. }
  40908. return facet;
  40909. };
  40910. // Creates and populates the heightMap array with "facet" elements :
  40911. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40912. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40913. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40914. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40915. // Returns the GroundMesh.
  40916. GroundMesh.prototype._initHeightQuads = function () {
  40917. var subdivisionsX = this._subdivisionsX;
  40918. var subdivisionsY = this._subdivisionsY;
  40919. this._heightQuads = new Array();
  40920. for (var row = 0; row < subdivisionsY; row++) {
  40921. for (var col = 0; col < subdivisionsX; col++) {
  40922. 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) };
  40923. this._heightQuads[row * subdivisionsX + col] = quad;
  40924. }
  40925. }
  40926. return this;
  40927. };
  40928. // Compute each quad element values and update the the heightMap array :
  40929. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40930. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40931. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40932. // Returns the GroundMesh.
  40933. GroundMesh.prototype._computeHeightQuads = function () {
  40934. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40935. var v1 = BABYLON.Tmp.Vector3[3];
  40936. var v2 = BABYLON.Tmp.Vector3[2];
  40937. var v3 = BABYLON.Tmp.Vector3[1];
  40938. var v4 = BABYLON.Tmp.Vector3[0];
  40939. var v1v2 = BABYLON.Tmp.Vector3[4];
  40940. var v1v3 = BABYLON.Tmp.Vector3[5];
  40941. var v1v4 = BABYLON.Tmp.Vector3[6];
  40942. var norm1 = BABYLON.Tmp.Vector3[7];
  40943. var norm2 = BABYLON.Tmp.Vector3[8];
  40944. var i = 0;
  40945. var j = 0;
  40946. var k = 0;
  40947. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40948. var h = 0;
  40949. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40950. var d2 = 0;
  40951. var subdivisionsX = this._subdivisionsX;
  40952. var subdivisionsY = this._subdivisionsY;
  40953. for (var row = 0; row < subdivisionsY; row++) {
  40954. for (var col = 0; col < subdivisionsX; col++) {
  40955. i = col * 3;
  40956. j = row * (subdivisionsX + 1) * 3;
  40957. k = (row + 1) * (subdivisionsX + 1) * 3;
  40958. v1.x = positions[j + i];
  40959. v1.y = positions[j + i + 1];
  40960. v1.z = positions[j + i + 2];
  40961. v2.x = positions[j + i + 3];
  40962. v2.y = positions[j + i + 4];
  40963. v2.z = positions[j + i + 5];
  40964. v3.x = positions[k + i];
  40965. v3.y = positions[k + i + 1];
  40966. v3.z = positions[k + i + 2];
  40967. v4.x = positions[k + i + 3];
  40968. v4.y = positions[k + i + 4];
  40969. v4.z = positions[k + i + 5];
  40970. // 2D slope V1V4
  40971. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40972. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40973. // facet equations :
  40974. // we compute each facet normal vector
  40975. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40976. // we compute the value d by applying the equation to v1 which belongs to the plane
  40977. // then we store the facet equation in a Vector4
  40978. v2.subtractToRef(v1, v1v2);
  40979. v3.subtractToRef(v1, v1v3);
  40980. v4.subtractToRef(v1, v1v4);
  40981. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40982. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40983. norm1.normalize();
  40984. norm2.normalize();
  40985. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40986. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40987. var quad = this._heightQuads[row * subdivisionsX + col];
  40988. quad.slope.copyFromFloats(cd, h);
  40989. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  40990. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  40991. }
  40992. }
  40993. return this;
  40994. };
  40995. GroundMesh.prototype.serialize = function (serializationObject) {
  40996. _super.prototype.serialize.call(this, serializationObject);
  40997. serializationObject.subdivisionsX = this._subdivisionsX;
  40998. serializationObject.subdivisionsY = this._subdivisionsY;
  40999. serializationObject.minX = this._minX;
  41000. serializationObject.maxX = this._maxX;
  41001. serializationObject.minZ = this._minZ;
  41002. serializationObject.maxZ = this._maxZ;
  41003. serializationObject.width = this._width;
  41004. serializationObject.height = this._height;
  41005. };
  41006. GroundMesh.Parse = function (parsedMesh, scene) {
  41007. var result = new GroundMesh(parsedMesh.name, scene);
  41008. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41009. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41010. result._minX = parsedMesh.minX;
  41011. result._maxX = parsedMesh.maxX;
  41012. result._minZ = parsedMesh.minZ;
  41013. result._maxZ = parsedMesh.maxZ;
  41014. result._width = parsedMesh.width;
  41015. result._height = parsedMesh.height;
  41016. return result;
  41017. };
  41018. return GroundMesh;
  41019. }(BABYLON.Mesh));
  41020. BABYLON.GroundMesh = GroundMesh;
  41021. })(BABYLON || (BABYLON = {}));
  41022. //# sourceMappingURL=babylon.groundMesh.js.map
  41023. var BABYLON;
  41024. (function (BABYLON) {
  41025. /**
  41026. * Creates an instance based on a source mesh.
  41027. */
  41028. var InstancedMesh = (function (_super) {
  41029. __extends(InstancedMesh, _super);
  41030. function InstancedMesh(name, source) {
  41031. var _this = _super.call(this, name, source.getScene()) || this;
  41032. source.instances.push(_this);
  41033. _this._sourceMesh = source;
  41034. _this.position.copyFrom(source.position);
  41035. _this.rotation.copyFrom(source.rotation);
  41036. _this.scaling.copyFrom(source.scaling);
  41037. if (source.rotationQuaternion) {
  41038. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41039. }
  41040. _this.infiniteDistance = source.infiniteDistance;
  41041. _this.setPivotMatrix(source.getPivotMatrix());
  41042. _this.refreshBoundingInfo();
  41043. _this._syncSubMeshes();
  41044. return _this;
  41045. }
  41046. /**
  41047. * Returns the string "InstancedMesh".
  41048. */
  41049. InstancedMesh.prototype.getClassName = function () {
  41050. return "InstancedMesh";
  41051. };
  41052. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41053. // Methods
  41054. get: function () {
  41055. return this._sourceMesh.receiveShadows;
  41056. },
  41057. enumerable: true,
  41058. configurable: true
  41059. });
  41060. Object.defineProperty(InstancedMesh.prototype, "material", {
  41061. get: function () {
  41062. return this._sourceMesh.material;
  41063. },
  41064. enumerable: true,
  41065. configurable: true
  41066. });
  41067. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41068. get: function () {
  41069. return this._sourceMesh.visibility;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41075. get: function () {
  41076. return this._sourceMesh.skeleton;
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41082. get: function () {
  41083. return this._sourceMesh.renderingGroupId;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. /**
  41089. * Returns the total number of vertices (integer).
  41090. */
  41091. InstancedMesh.prototype.getTotalVertices = function () {
  41092. return this._sourceMesh.getTotalVertices();
  41093. };
  41094. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41095. get: function () {
  41096. return this._sourceMesh;
  41097. },
  41098. enumerable: true,
  41099. configurable: true
  41100. });
  41101. /**
  41102. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41103. */
  41104. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41105. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41106. };
  41107. /**
  41108. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41109. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41110. * The `data` are either a numeric array either a Float32Array.
  41111. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41112. * 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).
  41113. * Note that a new underlying VertexBuffer object is created each call.
  41114. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41115. *
  41116. * Possible `kind` values :
  41117. * - BABYLON.VertexBuffer.PositionKind
  41118. * - BABYLON.VertexBuffer.UVKind
  41119. * - BABYLON.VertexBuffer.UV2Kind
  41120. * - BABYLON.VertexBuffer.UV3Kind
  41121. * - BABYLON.VertexBuffer.UV4Kind
  41122. * - BABYLON.VertexBuffer.UV5Kind
  41123. * - BABYLON.VertexBuffer.UV6Kind
  41124. * - BABYLON.VertexBuffer.ColorKind
  41125. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41126. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41127. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41128. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41129. *
  41130. * Returns the Mesh.
  41131. */
  41132. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41133. if (this.sourceMesh) {
  41134. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41135. }
  41136. return this.sourceMesh;
  41137. };
  41138. /**
  41139. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41140. * If the mesh has no geometry, it is simply returned as it is.
  41141. * The `data` are either a numeric array either a Float32Array.
  41142. * No new underlying VertexBuffer object is created.
  41143. * 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.
  41144. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41145. *
  41146. * Possible `kind` values :
  41147. * - BABYLON.VertexBuffer.PositionKind
  41148. * - BABYLON.VertexBuffer.UVKind
  41149. * - BABYLON.VertexBuffer.UV2Kind
  41150. * - BABYLON.VertexBuffer.UV3Kind
  41151. * - BABYLON.VertexBuffer.UV4Kind
  41152. * - BABYLON.VertexBuffer.UV5Kind
  41153. * - BABYLON.VertexBuffer.UV6Kind
  41154. * - BABYLON.VertexBuffer.ColorKind
  41155. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41156. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41157. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41158. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41159. *
  41160. * Returns the Mesh.
  41161. */
  41162. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41163. if (this.sourceMesh) {
  41164. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41165. }
  41166. return this.sourceMesh;
  41167. };
  41168. /**
  41169. * Sets the mesh indices.
  41170. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41171. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41172. * This method creates a new index buffer each call.
  41173. * Returns the Mesh.
  41174. */
  41175. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41176. if (this.sourceMesh) {
  41177. this.sourceMesh.setIndices(indices, totalVertices);
  41178. }
  41179. return this.sourceMesh;
  41180. };
  41181. /**
  41182. * Boolean : True if the mesh owns the requested kind of data.
  41183. */
  41184. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41185. return this._sourceMesh.isVerticesDataPresent(kind);
  41186. };
  41187. /**
  41188. * Returns an array of indices (IndicesArray).
  41189. */
  41190. InstancedMesh.prototype.getIndices = function () {
  41191. return this._sourceMesh.getIndices();
  41192. };
  41193. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41194. get: function () {
  41195. return this._sourceMesh._positions;
  41196. },
  41197. enumerable: true,
  41198. configurable: true
  41199. });
  41200. /**
  41201. * Sets a new updated BoundingInfo to the mesh.
  41202. * Returns the mesh.
  41203. */
  41204. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41205. var meshBB = this._sourceMesh.getBoundingInfo();
  41206. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41207. this._updateBoundingInfo();
  41208. return this;
  41209. };
  41210. InstancedMesh.prototype._preActivate = function () {
  41211. if (this._currentLOD) {
  41212. this._currentLOD._preActivate();
  41213. }
  41214. return this;
  41215. };
  41216. InstancedMesh.prototype._activate = function (renderId) {
  41217. if (this._currentLOD) {
  41218. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41219. }
  41220. return this;
  41221. };
  41222. /**
  41223. * Returns the current associated LOD AbstractMesh.
  41224. */
  41225. InstancedMesh.prototype.getLOD = function (camera) {
  41226. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41227. if (this._currentLOD === this.sourceMesh) {
  41228. return this;
  41229. }
  41230. return this._currentLOD;
  41231. };
  41232. InstancedMesh.prototype._syncSubMeshes = function () {
  41233. this.releaseSubMeshes();
  41234. if (this._sourceMesh.subMeshes) {
  41235. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41236. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41237. }
  41238. }
  41239. return this;
  41240. };
  41241. InstancedMesh.prototype._generatePointsArray = function () {
  41242. return this._sourceMesh._generatePointsArray();
  41243. };
  41244. /**
  41245. * Creates a new InstancedMesh from the current mesh.
  41246. * - name (string) : the cloned mesh name
  41247. * - newParent (optional Node) : the optional Node to parent the clone to.
  41248. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41249. *
  41250. * Returns the clone.
  41251. */
  41252. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41253. var result = this._sourceMesh.createInstance(name);
  41254. // Deep copy
  41255. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41256. // Bounding info
  41257. this.refreshBoundingInfo();
  41258. // Parent
  41259. if (newParent) {
  41260. result.parent = newParent;
  41261. }
  41262. if (!doNotCloneChildren) {
  41263. // Children
  41264. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41265. var mesh = this.getScene().meshes[index];
  41266. if (mesh.parent === this) {
  41267. mesh.clone(mesh.name, result);
  41268. }
  41269. }
  41270. }
  41271. result.computeWorldMatrix(true);
  41272. return result;
  41273. };
  41274. /**
  41275. * Disposes the InstancedMesh.
  41276. * Returns nothing.
  41277. */
  41278. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41279. // Remove from mesh
  41280. var index = this._sourceMesh.instances.indexOf(this);
  41281. this._sourceMesh.instances.splice(index, 1);
  41282. _super.prototype.dispose.call(this, doNotRecurse);
  41283. };
  41284. return InstancedMesh;
  41285. }(BABYLON.AbstractMesh));
  41286. BABYLON.InstancedMesh = InstancedMesh;
  41287. })(BABYLON || (BABYLON = {}));
  41288. //# sourceMappingURL=babylon.instancedMesh.js.map
  41289. /// <reference path="babylon.mesh.ts" />
  41290. var BABYLON;
  41291. (function (BABYLON) {
  41292. var LinesMesh = (function (_super) {
  41293. __extends(LinesMesh, _super);
  41294. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41295. if (parent === void 0) { parent = null; }
  41296. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41297. _this.useVertexColor = useVertexColor;
  41298. _this.color = new BABYLON.Color3(1, 1, 1);
  41299. _this.alpha = 1;
  41300. if (source) {
  41301. _this.color = source.color.clone();
  41302. _this.alpha = source.alpha;
  41303. _this.useVertexColor = source.useVertexColor;
  41304. }
  41305. _this._intersectionThreshold = 0.1;
  41306. var options = {
  41307. attributes: [BABYLON.VertexBuffer.PositionKind],
  41308. uniforms: ["world", "viewProjection"],
  41309. needAlphaBlending: false,
  41310. };
  41311. if (!useVertexColor) {
  41312. options.uniforms.push("color");
  41313. options.needAlphaBlending = true;
  41314. }
  41315. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41316. return _this;
  41317. }
  41318. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41319. /**
  41320. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41321. * This margin is expressed in world space coordinates, so its value may vary.
  41322. * Default value is 0.1
  41323. * @returns the intersection Threshold value.
  41324. */
  41325. get: function () {
  41326. return this._intersectionThreshold;
  41327. },
  41328. /**
  41329. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41330. * This margin is expressed in world space coordinates, so its value may vary.
  41331. * @param value the new threshold to apply
  41332. */
  41333. set: function (value) {
  41334. if (this._intersectionThreshold === value) {
  41335. return;
  41336. }
  41337. this._intersectionThreshold = value;
  41338. if (this.geometry) {
  41339. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41340. }
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. /**
  41346. * Returns the string "LineMesh"
  41347. */
  41348. LinesMesh.prototype.getClassName = function () {
  41349. return "LinesMesh";
  41350. };
  41351. Object.defineProperty(LinesMesh.prototype, "material", {
  41352. get: function () {
  41353. return this._colorShader;
  41354. },
  41355. enumerable: true,
  41356. configurable: true
  41357. });
  41358. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41359. get: function () {
  41360. return false;
  41361. },
  41362. enumerable: true,
  41363. configurable: true
  41364. });
  41365. LinesMesh.prototype.createInstance = function (name) {
  41366. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41367. return null;
  41368. };
  41369. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41370. // VBOs
  41371. this._geometry._bind(this._colorShader.getEffect());
  41372. // Color
  41373. if (!this.useVertexColor) {
  41374. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41375. }
  41376. return this;
  41377. };
  41378. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41379. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41380. return this;
  41381. }
  41382. var engine = this.getScene().getEngine();
  41383. // Draw order
  41384. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41385. return this;
  41386. };
  41387. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41388. this._colorShader.dispose();
  41389. _super.prototype.dispose.call(this, doNotRecurse);
  41390. };
  41391. /**
  41392. * Returns a new LineMesh object cloned from the current one.
  41393. */
  41394. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41395. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41396. };
  41397. return LinesMesh;
  41398. }(BABYLON.Mesh));
  41399. BABYLON.LinesMesh = LinesMesh;
  41400. })(BABYLON || (BABYLON = {}));
  41401. //# sourceMappingURL=babylon.linesMesh.js.map
  41402. var BABYLON;
  41403. (function (BABYLON) {
  41404. var StandardMaterialDefines = (function (_super) {
  41405. __extends(StandardMaterialDefines, _super);
  41406. function StandardMaterialDefines() {
  41407. var _this = _super.call(this) || this;
  41408. _this.DIFFUSE = false;
  41409. _this.AMBIENT = false;
  41410. _this.OPACITY = false;
  41411. _this.OPACITYRGB = false;
  41412. _this.REFLECTION = false;
  41413. _this.EMISSIVE = false;
  41414. _this.SPECULAR = false;
  41415. _this.BUMP = false;
  41416. _this.PARALLAX = false;
  41417. _this.PARALLAXOCCLUSION = false;
  41418. _this.SPECULAROVERALPHA = false;
  41419. _this.CLIPPLANE = false;
  41420. _this.ALPHATEST = false;
  41421. _this.ALPHAFROMDIFFUSE = false;
  41422. _this.POINTSIZE = false;
  41423. _this.FOG = false;
  41424. _this.SPECULARTERM = false;
  41425. _this.DIFFUSEFRESNEL = false;
  41426. _this.OPACITYFRESNEL = false;
  41427. _this.REFLECTIONFRESNEL = false;
  41428. _this.REFRACTIONFRESNEL = false;
  41429. _this.EMISSIVEFRESNEL = false;
  41430. _this.FRESNEL = false;
  41431. _this.NORMAL = false;
  41432. _this.UV1 = false;
  41433. _this.UV2 = false;
  41434. _this.VERTEXCOLOR = false;
  41435. _this.VERTEXALPHA = false;
  41436. _this.NUM_BONE_INFLUENCERS = 0;
  41437. _this.BonesPerMesh = 0;
  41438. _this.INSTANCES = false;
  41439. _this.GLOSSINESS = false;
  41440. _this.ROUGHNESS = false;
  41441. _this.EMISSIVEASILLUMINATION = false;
  41442. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41443. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41444. _this.LIGHTMAP = false;
  41445. _this.USELIGHTMAPASSHADOWMAP = false;
  41446. _this.REFLECTIONMAP_3D = false;
  41447. _this.REFLECTIONMAP_SPHERICAL = false;
  41448. _this.REFLECTIONMAP_PLANAR = false;
  41449. _this.REFLECTIONMAP_CUBIC = false;
  41450. _this.REFLECTIONMAP_PROJECTION = false;
  41451. _this.REFLECTIONMAP_SKYBOX = false;
  41452. _this.REFLECTIONMAP_EXPLICIT = false;
  41453. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41454. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41455. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41456. _this.INVERTCUBICMAP = false;
  41457. _this.LOGARITHMICDEPTH = false;
  41458. _this.REFRACTION = false;
  41459. _this.REFRACTIONMAP_3D = false;
  41460. _this.REFLECTIONOVERALPHA = false;
  41461. _this.INVERTNORMALMAPX = false;
  41462. _this.INVERTNORMALMAPY = false;
  41463. _this.TWOSIDEDLIGHTING = false;
  41464. _this.SHADOWFLOAT = false;
  41465. _this.MORPHTARGETS = false;
  41466. _this.MORPHTARGETS_NORMAL = false;
  41467. _this.MORPHTARGETS_TANGENT = false;
  41468. _this.NUM_MORPH_INFLUENCERS = 0;
  41469. _this.USERIGHTHANDEDSYSTEM = false;
  41470. _this.IMAGEPROCESSING = false;
  41471. _this.VIGNETTE = false;
  41472. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41473. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41474. _this.TONEMAPPING = false;
  41475. _this.CONTRAST = false;
  41476. _this.COLORCURVES = false;
  41477. _this.COLORGRADING = false;
  41478. _this.SAMPLER3DGREENDEPTH = false;
  41479. _this.SAMPLER3DBGRMAP = false;
  41480. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41481. _this.EXPOSURE = false;
  41482. _this.rebuild();
  41483. return _this;
  41484. }
  41485. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41486. var modes = [
  41487. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41488. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41489. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41490. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41491. ];
  41492. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41493. var mode = modes_1[_i];
  41494. this[mode] = (mode === modeToEnable);
  41495. }
  41496. };
  41497. return StandardMaterialDefines;
  41498. }(BABYLON.MaterialDefines));
  41499. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41500. var StandardMaterial = (function (_super) {
  41501. __extends(StandardMaterial, _super);
  41502. function StandardMaterial(name, scene) {
  41503. var _this = _super.call(this, name, scene) || this;
  41504. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41505. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41506. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41507. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41508. _this.specularPower = 64;
  41509. _this._useAlphaFromDiffuseTexture = false;
  41510. _this._useEmissiveAsIllumination = false;
  41511. _this._linkEmissiveWithDiffuse = false;
  41512. _this._useSpecularOverAlpha = false;
  41513. _this._useReflectionOverAlpha = false;
  41514. _this._disableLighting = false;
  41515. _this._useParallax = false;
  41516. _this._useParallaxOcclusion = false;
  41517. _this.parallaxScaleBias = 0.05;
  41518. _this._roughness = 0;
  41519. _this.indexOfRefraction = 0.98;
  41520. _this.invertRefractionY = true;
  41521. _this._useLightmapAsShadowmap = false;
  41522. _this._useReflectionFresnelFromSpecular = false;
  41523. _this._useGlossinessFromSpecularMapAlpha = false;
  41524. _this._maxSimultaneousLights = 4;
  41525. /**
  41526. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41527. */
  41528. _this._invertNormalMapX = false;
  41529. /**
  41530. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41531. */
  41532. _this._invertNormalMapY = false;
  41533. /**
  41534. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41535. */
  41536. _this._twoSidedLighting = false;
  41537. _this._renderTargets = new BABYLON.SmartArray(16);
  41538. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41539. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41540. // Setup the default processing configuration to the scene.
  41541. _this._attachImageProcessingConfiguration(null);
  41542. _this.getRenderTargetTextures = function () {
  41543. _this._renderTargets.reset();
  41544. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41545. _this._renderTargets.push(_this._reflectionTexture);
  41546. }
  41547. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41548. _this._renderTargets.push(_this._refractionTexture);
  41549. }
  41550. return _this._renderTargets;
  41551. };
  41552. return _this;
  41553. }
  41554. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41555. /**
  41556. * Gets the image processing configuration used either in this material.
  41557. */
  41558. get: function () {
  41559. return this._imageProcessingConfiguration;
  41560. },
  41561. /**
  41562. * Sets the Default image processing configuration used either in the this material.
  41563. *
  41564. * If sets to null, the scene one is in use.
  41565. */
  41566. set: function (value) {
  41567. this._attachImageProcessingConfiguration(value);
  41568. // Ensure the effect will be rebuilt.
  41569. this._markAllSubMeshesAsTexturesDirty();
  41570. },
  41571. enumerable: true,
  41572. configurable: true
  41573. });
  41574. /**
  41575. * Attaches a new image processing configuration to the Standard Material.
  41576. * @param configuration
  41577. */
  41578. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41579. var _this = this;
  41580. if (configuration === this._imageProcessingConfiguration) {
  41581. return;
  41582. }
  41583. // Detaches observer.
  41584. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41585. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41586. }
  41587. // Pick the scene configuration if needed.
  41588. if (!configuration) {
  41589. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41590. }
  41591. else {
  41592. this._imageProcessingConfiguration = configuration;
  41593. }
  41594. // Attaches observer.
  41595. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41596. _this._markAllSubMeshesAsTexturesDirty();
  41597. });
  41598. };
  41599. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41600. /**
  41601. * Gets wether the color curves effect is enabled.
  41602. */
  41603. get: function () {
  41604. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41605. },
  41606. /**
  41607. * Sets wether the color curves effect is enabled.
  41608. */
  41609. set: function (value) {
  41610. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41611. },
  41612. enumerable: true,
  41613. configurable: true
  41614. });
  41615. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41616. /**
  41617. * Gets wether the color grading effect is enabled.
  41618. */
  41619. get: function () {
  41620. return this.imageProcessingConfiguration.colorGradingEnabled;
  41621. },
  41622. /**
  41623. * Gets wether the color grading effect is enabled.
  41624. */
  41625. set: function (value) {
  41626. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41627. },
  41628. enumerable: true,
  41629. configurable: true
  41630. });
  41631. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41632. /**
  41633. * Gets wether tonemapping is enabled or not.
  41634. */
  41635. get: function () {
  41636. return this._imageProcessingConfiguration.toneMappingEnabled;
  41637. },
  41638. /**
  41639. * Sets wether tonemapping is enabled or not
  41640. */
  41641. set: function (value) {
  41642. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41643. },
  41644. enumerable: true,
  41645. configurable: true
  41646. });
  41647. ;
  41648. ;
  41649. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41650. /**
  41651. * The camera exposure used on this material.
  41652. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41653. * This corresponds to a photographic exposure.
  41654. */
  41655. get: function () {
  41656. return this._imageProcessingConfiguration.exposure;
  41657. },
  41658. /**
  41659. * The camera exposure used on this material.
  41660. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41661. * This corresponds to a photographic exposure.
  41662. */
  41663. set: function (value) {
  41664. this._imageProcessingConfiguration.exposure = value;
  41665. },
  41666. enumerable: true,
  41667. configurable: true
  41668. });
  41669. ;
  41670. ;
  41671. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41672. /**
  41673. * Gets The camera contrast used on this material.
  41674. */
  41675. get: function () {
  41676. return this._imageProcessingConfiguration.contrast;
  41677. },
  41678. /**
  41679. * Sets The camera contrast used on this material.
  41680. */
  41681. set: function (value) {
  41682. this._imageProcessingConfiguration.contrast = value;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41688. /**
  41689. * Gets the Color Grading 2D Lookup Texture.
  41690. */
  41691. get: function () {
  41692. return this._imageProcessingConfiguration.colorGradingTexture;
  41693. },
  41694. /**
  41695. * Sets the Color Grading 2D Lookup Texture.
  41696. */
  41697. set: function (value) {
  41698. this._imageProcessingConfiguration.colorGradingTexture = value;
  41699. },
  41700. enumerable: true,
  41701. configurable: true
  41702. });
  41703. StandardMaterial.prototype.getClassName = function () {
  41704. return "StandardMaterial";
  41705. };
  41706. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41707. get: function () {
  41708. return this._useLogarithmicDepth;
  41709. },
  41710. set: function (value) {
  41711. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41712. this._markAllSubMeshesAsMiscDirty();
  41713. },
  41714. enumerable: true,
  41715. configurable: true
  41716. });
  41717. StandardMaterial.prototype.needAlphaBlending = function () {
  41718. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41719. };
  41720. StandardMaterial.prototype.needAlphaTesting = function () {
  41721. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41722. };
  41723. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41724. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41725. };
  41726. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41727. return this._diffuseTexture;
  41728. };
  41729. /**
  41730. * Child classes can use it to update shaders
  41731. */
  41732. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41733. if (this.isFrozen) {
  41734. if (this._wasPreviouslyReady && subMesh.effect) {
  41735. return true;
  41736. }
  41737. }
  41738. if (!subMesh._materialDefines) {
  41739. subMesh._materialDefines = new StandardMaterialDefines();
  41740. }
  41741. var scene = this.getScene();
  41742. var defines = subMesh._materialDefines;
  41743. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41744. if (defines._renderId === scene.getRenderId()) {
  41745. return true;
  41746. }
  41747. }
  41748. var engine = scene.getEngine();
  41749. // Lights
  41750. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41751. // Textures
  41752. if (defines._areTexturesDirty) {
  41753. defines._needUVs = false;
  41754. if (scene.texturesEnabled) {
  41755. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41756. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41757. return false;
  41758. }
  41759. else {
  41760. defines._needUVs = true;
  41761. defines.DIFFUSE = true;
  41762. }
  41763. }
  41764. else {
  41765. defines.DIFFUSE = false;
  41766. }
  41767. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41768. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41769. return false;
  41770. }
  41771. else {
  41772. defines._needUVs = true;
  41773. defines.AMBIENT = true;
  41774. }
  41775. }
  41776. else {
  41777. defines.AMBIENT = false;
  41778. }
  41779. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41780. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41781. return false;
  41782. }
  41783. else {
  41784. defines._needUVs = true;
  41785. defines.OPACITY = true;
  41786. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41787. }
  41788. }
  41789. else {
  41790. defines.OPACITY = false;
  41791. }
  41792. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41793. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41794. return false;
  41795. }
  41796. else {
  41797. defines._needNormals = true;
  41798. defines.REFLECTION = true;
  41799. defines.ROUGHNESS = (this._roughness > 0);
  41800. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41801. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41802. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41803. switch (this._reflectionTexture.coordinatesMode) {
  41804. case BABYLON.Texture.CUBIC_MODE:
  41805. case BABYLON.Texture.INVCUBIC_MODE:
  41806. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41807. break;
  41808. case BABYLON.Texture.EXPLICIT_MODE:
  41809. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41810. break;
  41811. case BABYLON.Texture.PLANAR_MODE:
  41812. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41813. break;
  41814. case BABYLON.Texture.PROJECTION_MODE:
  41815. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41816. break;
  41817. case BABYLON.Texture.SKYBOX_MODE:
  41818. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41819. break;
  41820. case BABYLON.Texture.SPHERICAL_MODE:
  41821. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41822. break;
  41823. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41824. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41825. break;
  41826. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41827. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41828. break;
  41829. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41830. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41831. break;
  41832. }
  41833. }
  41834. }
  41835. else {
  41836. defines.REFLECTION = false;
  41837. }
  41838. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41839. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41840. return false;
  41841. }
  41842. else {
  41843. defines._needUVs = true;
  41844. defines.EMISSIVE = true;
  41845. }
  41846. }
  41847. else {
  41848. defines.EMISSIVE = false;
  41849. }
  41850. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41851. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41852. return false;
  41853. }
  41854. else {
  41855. defines._needUVs = true;
  41856. defines.LIGHTMAP = true;
  41857. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41858. }
  41859. }
  41860. else {
  41861. defines.LIGHTMAP = false;
  41862. }
  41863. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41864. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41865. return false;
  41866. }
  41867. else {
  41868. defines._needUVs = true;
  41869. defines.SPECULAR = true;
  41870. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41871. }
  41872. }
  41873. else {
  41874. defines.SPECULAR = false;
  41875. }
  41876. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41877. // Bump texure can not be not blocking.
  41878. if (!this._bumpTexture.isReady()) {
  41879. return false;
  41880. }
  41881. else {
  41882. defines._needUVs = true;
  41883. defines.BUMP = true;
  41884. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  41885. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  41886. defines.PARALLAX = this._useParallax;
  41887. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41888. }
  41889. }
  41890. else {
  41891. defines.BUMP = false;
  41892. }
  41893. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41894. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41895. return false;
  41896. }
  41897. else {
  41898. defines._needUVs = true;
  41899. defines.REFRACTION = true;
  41900. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41901. }
  41902. }
  41903. else {
  41904. defines.REFRACTION = false;
  41905. }
  41906. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41907. }
  41908. else {
  41909. defines.DIFFUSE = false;
  41910. defines.AMBIENT = false;
  41911. defines.OPACITY = false;
  41912. defines.REFLECTION = false;
  41913. defines.EMISSIVE = false;
  41914. defines.LIGHTMAP = false;
  41915. defines.BUMP = false;
  41916. defines.REFRACTION = false;
  41917. }
  41918. if (!this.imageProcessingConfiguration.isReady()) {
  41919. return false;
  41920. }
  41921. this.imageProcessingConfiguration.prepareDefines(defines);
  41922. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41923. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41924. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41925. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41926. }
  41927. if (defines._areFresnelDirty) {
  41928. if (StandardMaterial.FresnelEnabled) {
  41929. // Fresnel
  41930. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41931. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41932. this._reflectionFresnelParameters) {
  41933. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41934. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41935. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41936. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41937. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41938. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41939. defines._needNormals = true;
  41940. defines.FRESNEL = true;
  41941. }
  41942. }
  41943. else {
  41944. defines.FRESNEL = false;
  41945. }
  41946. }
  41947. // Misc.
  41948. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  41949. // Attribs
  41950. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41951. // Values that need to be evaluated on every frame
  41952. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41953. if (scene._mirroredCameraPosition && defines.BUMP) {
  41954. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  41955. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  41956. defines.markAsUnprocessed();
  41957. }
  41958. // Get correct effect
  41959. if (defines.isDirty) {
  41960. defines.markAsProcessed();
  41961. scene.resetCachedMaterial();
  41962. // Fallbacks
  41963. var fallbacks = new BABYLON.EffectFallbacks();
  41964. if (defines.REFLECTION) {
  41965. fallbacks.addFallback(0, "REFLECTION");
  41966. }
  41967. if (defines.SPECULAR) {
  41968. fallbacks.addFallback(0, "SPECULAR");
  41969. }
  41970. if (defines.BUMP) {
  41971. fallbacks.addFallback(0, "BUMP");
  41972. }
  41973. if (defines.PARALLAX) {
  41974. fallbacks.addFallback(1, "PARALLAX");
  41975. }
  41976. if (defines.PARALLAXOCCLUSION) {
  41977. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41978. }
  41979. if (defines.SPECULAROVERALPHA) {
  41980. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41981. }
  41982. if (defines.FOG) {
  41983. fallbacks.addFallback(1, "FOG");
  41984. }
  41985. if (defines.POINTSIZE) {
  41986. fallbacks.addFallback(0, "POINTSIZE");
  41987. }
  41988. if (defines.LOGARITHMICDEPTH) {
  41989. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  41990. }
  41991. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  41992. if (defines.SPECULARTERM) {
  41993. fallbacks.addFallback(0, "SPECULARTERM");
  41994. }
  41995. if (defines.DIFFUSEFRESNEL) {
  41996. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  41997. }
  41998. if (defines.OPACITYFRESNEL) {
  41999. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42000. }
  42001. if (defines.REFLECTIONFRESNEL) {
  42002. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42003. }
  42004. if (defines.EMISSIVEFRESNEL) {
  42005. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42006. }
  42007. if (defines.FRESNEL) {
  42008. fallbacks.addFallback(4, "FRESNEL");
  42009. }
  42010. //Attributes
  42011. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42012. if (defines.NORMAL) {
  42013. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42014. }
  42015. if (defines.UV1) {
  42016. attribs.push(BABYLON.VertexBuffer.UVKind);
  42017. }
  42018. if (defines.UV2) {
  42019. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42020. }
  42021. if (defines.VERTEXCOLOR) {
  42022. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42023. }
  42024. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42025. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42026. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42027. var shaderName = "default";
  42028. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42029. "vFogInfos", "vFogColor", "pointSize",
  42030. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42031. "mBones",
  42032. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42033. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42034. "logarithmicDepthConstant"
  42035. ];
  42036. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42037. var uniformBuffers = ["Material", "Scene"];
  42038. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42039. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42040. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42041. uniformsNames: uniforms,
  42042. uniformBuffersNames: uniformBuffers,
  42043. samplers: samplers,
  42044. defines: defines,
  42045. maxSimultaneousLights: this._maxSimultaneousLights
  42046. });
  42047. if (this.customShaderNameResolve) {
  42048. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42049. }
  42050. var join = defines.toString();
  42051. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42052. attributes: attribs,
  42053. uniformsNames: uniforms,
  42054. uniformBuffersNames: uniformBuffers,
  42055. samplers: samplers,
  42056. defines: join,
  42057. fallbacks: fallbacks,
  42058. onCompiled: this.onCompiled,
  42059. onError: this.onError,
  42060. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42061. }, engine), defines);
  42062. this.buildUniformLayout();
  42063. }
  42064. if (!subMesh.effect.isReady()) {
  42065. return false;
  42066. }
  42067. defines._renderId = scene.getRenderId();
  42068. this._wasPreviouslyReady = true;
  42069. return true;
  42070. };
  42071. StandardMaterial.prototype.buildUniformLayout = function () {
  42072. // Order is important !
  42073. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42074. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42075. this._uniformBuffer.addUniform("opacityParts", 4);
  42076. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42077. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42078. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42079. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42080. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42081. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42082. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42083. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42084. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42085. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42086. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42087. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42088. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42089. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42090. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42091. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42092. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42093. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42094. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42095. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42096. this._uniformBuffer.addUniform("specularMatrix", 16);
  42097. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42098. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42099. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42100. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42101. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42102. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42103. this._uniformBuffer.addUniform("pointSize", 1);
  42104. this._uniformBuffer.create();
  42105. };
  42106. StandardMaterial.prototype.unbind = function () {
  42107. if (this._activeEffect) {
  42108. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42109. this._activeEffect.setTexture("reflection2DSampler", null);
  42110. }
  42111. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42112. this._activeEffect.setTexture("refraction2DSampler", null);
  42113. }
  42114. }
  42115. _super.prototype.unbind.call(this);
  42116. };
  42117. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42118. var scene = this.getScene();
  42119. var defines = subMesh._materialDefines;
  42120. if (!defines) {
  42121. return;
  42122. }
  42123. var effect = subMesh.effect;
  42124. this._activeEffect = effect;
  42125. // Matrices
  42126. this.bindOnlyWorldMatrix(world);
  42127. // Bones
  42128. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42129. if (this._mustRebind(scene, effect, mesh.visibility)) {
  42130. this._uniformBuffer.bindToEffect(effect, "Material");
  42131. this.bindViewProjection(effect);
  42132. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42133. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42134. // Fresnel
  42135. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42136. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42137. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42138. }
  42139. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42140. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42141. }
  42142. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42143. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42144. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42145. }
  42146. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42147. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42148. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42149. }
  42150. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42151. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42152. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42153. }
  42154. }
  42155. // Textures
  42156. if (scene.texturesEnabled) {
  42157. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42158. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42159. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  42160. }
  42161. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42162. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42163. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  42164. }
  42165. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42166. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42167. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  42168. }
  42169. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42170. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42171. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42172. }
  42173. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42174. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42175. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  42176. }
  42177. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42178. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42179. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  42180. }
  42181. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42182. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42183. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  42184. }
  42185. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42186. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42187. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  42188. }
  42189. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42190. var depth = 1.0;
  42191. if (!this._refractionTexture.isCube) {
  42192. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42193. if (this._refractionTexture.depth) {
  42194. depth = this._refractionTexture.depth;
  42195. }
  42196. }
  42197. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42198. }
  42199. }
  42200. // Point size
  42201. if (this.pointsCloud) {
  42202. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42203. }
  42204. if (defines.SPECULARTERM) {
  42205. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42206. }
  42207. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42208. // Diffuse
  42209. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42210. }
  42211. // Textures
  42212. if (scene.texturesEnabled) {
  42213. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42214. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42215. }
  42216. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42217. effect.setTexture("ambientSampler", this._ambientTexture);
  42218. }
  42219. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42220. effect.setTexture("opacitySampler", this._opacityTexture);
  42221. }
  42222. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42223. if (this._reflectionTexture.isCube) {
  42224. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42225. }
  42226. else {
  42227. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42228. }
  42229. }
  42230. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42231. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42232. }
  42233. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42234. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42235. }
  42236. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42237. effect.setTexture("specularSampler", this._specularTexture);
  42238. }
  42239. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42240. effect.setTexture("bumpSampler", this._bumpTexture);
  42241. }
  42242. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42243. var depth = 1.0;
  42244. if (this._refractionTexture.isCube) {
  42245. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42246. }
  42247. else {
  42248. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42249. }
  42250. }
  42251. }
  42252. // Clip plane
  42253. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42254. // Colors
  42255. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42256. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  42257. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42258. }
  42259. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  42260. // Lights
  42261. if (scene.lightsEnabled && !this._disableLighting) {
  42262. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42263. }
  42264. // View
  42265. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42266. this.bindView(effect);
  42267. }
  42268. // Fog
  42269. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42270. // Morph targets
  42271. if (defines.NUM_MORPH_INFLUENCERS) {
  42272. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42273. }
  42274. // Log. depth
  42275. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42276. // image processing
  42277. this._imageProcessingConfiguration.bind(this._activeEffect);
  42278. }
  42279. this._uniformBuffer.update();
  42280. this._afterBind(mesh, this._activeEffect);
  42281. };
  42282. StandardMaterial.prototype.getAnimatables = function () {
  42283. var results = [];
  42284. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42285. results.push(this._diffuseTexture);
  42286. }
  42287. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42288. results.push(this._ambientTexture);
  42289. }
  42290. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42291. results.push(this._opacityTexture);
  42292. }
  42293. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42294. results.push(this._reflectionTexture);
  42295. }
  42296. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42297. results.push(this._emissiveTexture);
  42298. }
  42299. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42300. results.push(this._specularTexture);
  42301. }
  42302. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42303. results.push(this._bumpTexture);
  42304. }
  42305. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42306. results.push(this._lightmapTexture);
  42307. }
  42308. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42309. results.push(this._refractionTexture);
  42310. }
  42311. return results;
  42312. };
  42313. StandardMaterial.prototype.getActiveTextures = function () {
  42314. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42315. if (this._diffuseTexture) {
  42316. activeTextures.push(this._diffuseTexture);
  42317. }
  42318. if (this._ambientTexture) {
  42319. activeTextures.push(this._ambientTexture);
  42320. }
  42321. if (this._opacityTexture) {
  42322. activeTextures.push(this._opacityTexture);
  42323. }
  42324. if (this._reflectionTexture) {
  42325. activeTextures.push(this._reflectionTexture);
  42326. }
  42327. if (this._emissiveTexture) {
  42328. activeTextures.push(this._emissiveTexture);
  42329. }
  42330. if (this._specularTexture) {
  42331. activeTextures.push(this._specularTexture);
  42332. }
  42333. if (this._bumpTexture) {
  42334. activeTextures.push(this._bumpTexture);
  42335. }
  42336. if (this._lightmapTexture) {
  42337. activeTextures.push(this._lightmapTexture);
  42338. }
  42339. if (this._refractionTexture) {
  42340. activeTextures.push(this._refractionTexture);
  42341. }
  42342. return activeTextures;
  42343. };
  42344. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42345. if (forceDisposeTextures) {
  42346. if (this._diffuseTexture) {
  42347. this._diffuseTexture.dispose();
  42348. }
  42349. if (this._ambientTexture) {
  42350. this._ambientTexture.dispose();
  42351. }
  42352. if (this._opacityTexture) {
  42353. this._opacityTexture.dispose();
  42354. }
  42355. if (this._reflectionTexture) {
  42356. this._reflectionTexture.dispose();
  42357. }
  42358. if (this._emissiveTexture) {
  42359. this._emissiveTexture.dispose();
  42360. }
  42361. if (this._specularTexture) {
  42362. this._specularTexture.dispose();
  42363. }
  42364. if (this._bumpTexture) {
  42365. this._bumpTexture.dispose();
  42366. }
  42367. if (this._lightmapTexture) {
  42368. this._lightmapTexture.dispose();
  42369. }
  42370. if (this._refractionTexture) {
  42371. this._refractionTexture.dispose();
  42372. }
  42373. }
  42374. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42375. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42376. }
  42377. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42378. };
  42379. StandardMaterial.prototype.clone = function (name) {
  42380. var _this = this;
  42381. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42382. result.name = name;
  42383. result.id = name;
  42384. return result;
  42385. };
  42386. StandardMaterial.prototype.serialize = function () {
  42387. return BABYLON.SerializationHelper.Serialize(this);
  42388. };
  42389. // Statics
  42390. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42391. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42392. };
  42393. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42394. get: function () {
  42395. return StandardMaterial._DiffuseTextureEnabled;
  42396. },
  42397. set: function (value) {
  42398. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42399. return;
  42400. }
  42401. StandardMaterial._DiffuseTextureEnabled = value;
  42402. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42403. },
  42404. enumerable: true,
  42405. configurable: true
  42406. });
  42407. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42408. get: function () {
  42409. return StandardMaterial._AmbientTextureEnabled;
  42410. },
  42411. set: function (value) {
  42412. if (StandardMaterial._AmbientTextureEnabled === value) {
  42413. return;
  42414. }
  42415. StandardMaterial._AmbientTextureEnabled = value;
  42416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42422. get: function () {
  42423. return StandardMaterial._OpacityTextureEnabled;
  42424. },
  42425. set: function (value) {
  42426. if (StandardMaterial._OpacityTextureEnabled === value) {
  42427. return;
  42428. }
  42429. StandardMaterial._OpacityTextureEnabled = value;
  42430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42436. get: function () {
  42437. return StandardMaterial._ReflectionTextureEnabled;
  42438. },
  42439. set: function (value) {
  42440. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42441. return;
  42442. }
  42443. StandardMaterial._ReflectionTextureEnabled = value;
  42444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42445. },
  42446. enumerable: true,
  42447. configurable: true
  42448. });
  42449. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42450. get: function () {
  42451. return StandardMaterial._EmissiveTextureEnabled;
  42452. },
  42453. set: function (value) {
  42454. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42455. return;
  42456. }
  42457. StandardMaterial._EmissiveTextureEnabled = value;
  42458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42459. },
  42460. enumerable: true,
  42461. configurable: true
  42462. });
  42463. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42464. get: function () {
  42465. return StandardMaterial._SpecularTextureEnabled;
  42466. },
  42467. set: function (value) {
  42468. if (StandardMaterial._SpecularTextureEnabled === value) {
  42469. return;
  42470. }
  42471. StandardMaterial._SpecularTextureEnabled = value;
  42472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42478. get: function () {
  42479. return StandardMaterial._BumpTextureEnabled;
  42480. },
  42481. set: function (value) {
  42482. if (StandardMaterial._BumpTextureEnabled === value) {
  42483. return;
  42484. }
  42485. StandardMaterial._BumpTextureEnabled = value;
  42486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42492. get: function () {
  42493. return StandardMaterial._LightmapTextureEnabled;
  42494. },
  42495. set: function (value) {
  42496. if (StandardMaterial._LightmapTextureEnabled === value) {
  42497. return;
  42498. }
  42499. StandardMaterial._LightmapTextureEnabled = value;
  42500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42501. },
  42502. enumerable: true,
  42503. configurable: true
  42504. });
  42505. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42506. get: function () {
  42507. return StandardMaterial._RefractionTextureEnabled;
  42508. },
  42509. set: function (value) {
  42510. if (StandardMaterial._RefractionTextureEnabled === value) {
  42511. return;
  42512. }
  42513. StandardMaterial._RefractionTextureEnabled = value;
  42514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42515. },
  42516. enumerable: true,
  42517. configurable: true
  42518. });
  42519. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42520. get: function () {
  42521. return StandardMaterial._ColorGradingTextureEnabled;
  42522. },
  42523. set: function (value) {
  42524. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42525. return;
  42526. }
  42527. StandardMaterial._ColorGradingTextureEnabled = value;
  42528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42529. },
  42530. enumerable: true,
  42531. configurable: true
  42532. });
  42533. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42534. get: function () {
  42535. return StandardMaterial._FresnelEnabled;
  42536. },
  42537. set: function (value) {
  42538. if (StandardMaterial._FresnelEnabled === value) {
  42539. return;
  42540. }
  42541. StandardMaterial._FresnelEnabled = value;
  42542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42543. },
  42544. enumerable: true,
  42545. configurable: true
  42546. });
  42547. return StandardMaterial;
  42548. }(BABYLON.PushMaterial));
  42549. // Flags used to enable or disable a type of texture for all Standard Materials
  42550. StandardMaterial._DiffuseTextureEnabled = true;
  42551. StandardMaterial._AmbientTextureEnabled = true;
  42552. StandardMaterial._OpacityTextureEnabled = true;
  42553. StandardMaterial._ReflectionTextureEnabled = true;
  42554. StandardMaterial._EmissiveTextureEnabled = true;
  42555. StandardMaterial._SpecularTextureEnabled = true;
  42556. StandardMaterial._BumpTextureEnabled = true;
  42557. StandardMaterial._LightmapTextureEnabled = true;
  42558. StandardMaterial._RefractionTextureEnabled = true;
  42559. StandardMaterial._ColorGradingTextureEnabled = true;
  42560. StandardMaterial._FresnelEnabled = true;
  42561. __decorate([
  42562. BABYLON.serializeAsTexture("diffuseTexture")
  42563. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42564. __decorate([
  42565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42566. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42567. __decorate([
  42568. BABYLON.serializeAsTexture("ambientTexture")
  42569. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42570. __decorate([
  42571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42572. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42573. __decorate([
  42574. BABYLON.serializeAsTexture("opacityTexture")
  42575. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42576. __decorate([
  42577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42578. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42579. __decorate([
  42580. BABYLON.serializeAsTexture("reflectionTexture")
  42581. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42582. __decorate([
  42583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42584. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42585. __decorate([
  42586. BABYLON.serializeAsTexture("emissiveTexture")
  42587. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42588. __decorate([
  42589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42590. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42591. __decorate([
  42592. BABYLON.serializeAsTexture("specularTexture")
  42593. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42594. __decorate([
  42595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42596. ], StandardMaterial.prototype, "specularTexture", void 0);
  42597. __decorate([
  42598. BABYLON.serializeAsTexture("bumpTexture")
  42599. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42600. __decorate([
  42601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42602. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42603. __decorate([
  42604. BABYLON.serializeAsTexture("lightmapTexture")
  42605. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42606. __decorate([
  42607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42608. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42609. __decorate([
  42610. BABYLON.serializeAsTexture("refractionTexture")
  42611. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42612. __decorate([
  42613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42614. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42615. __decorate([
  42616. BABYLON.serializeAsColor3("ambient")
  42617. ], StandardMaterial.prototype, "ambientColor", void 0);
  42618. __decorate([
  42619. BABYLON.serializeAsColor3("diffuse")
  42620. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42621. __decorate([
  42622. BABYLON.serializeAsColor3("specular")
  42623. ], StandardMaterial.prototype, "specularColor", void 0);
  42624. __decorate([
  42625. BABYLON.serializeAsColor3("emissive")
  42626. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42627. __decorate([
  42628. BABYLON.serialize()
  42629. ], StandardMaterial.prototype, "specularPower", void 0);
  42630. __decorate([
  42631. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42632. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42633. __decorate([
  42634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42635. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42636. __decorate([
  42637. BABYLON.serialize("useEmissiveAsIllumination")
  42638. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42639. __decorate([
  42640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42641. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42642. __decorate([
  42643. BABYLON.serialize("linkEmissiveWithDiffuse")
  42644. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42645. __decorate([
  42646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42647. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42648. __decorate([
  42649. BABYLON.serialize("useSpecularOverAlpha")
  42650. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42651. __decorate([
  42652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42653. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42654. __decorate([
  42655. BABYLON.serialize("useReflectionOverAlpha")
  42656. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42657. __decorate([
  42658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42659. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42660. __decorate([
  42661. BABYLON.serialize("disableLighting")
  42662. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42663. __decorate([
  42664. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42665. ], StandardMaterial.prototype, "disableLighting", void 0);
  42666. __decorate([
  42667. BABYLON.serialize("useParallax")
  42668. ], StandardMaterial.prototype, "_useParallax", void 0);
  42669. __decorate([
  42670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42671. ], StandardMaterial.prototype, "useParallax", void 0);
  42672. __decorate([
  42673. BABYLON.serialize("useParallaxOcclusion")
  42674. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42675. __decorate([
  42676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42677. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42678. __decorate([
  42679. BABYLON.serialize()
  42680. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42681. __decorate([
  42682. BABYLON.serialize("roughness")
  42683. ], StandardMaterial.prototype, "_roughness", void 0);
  42684. __decorate([
  42685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42686. ], StandardMaterial.prototype, "roughness", void 0);
  42687. __decorate([
  42688. BABYLON.serialize()
  42689. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42690. __decorate([
  42691. BABYLON.serialize()
  42692. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42693. __decorate([
  42694. BABYLON.serialize("useLightmapAsShadowmap")
  42695. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42696. __decorate([
  42697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42698. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42699. __decorate([
  42700. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42701. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42702. __decorate([
  42703. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42704. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42705. __decorate([
  42706. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42707. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42708. __decorate([
  42709. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42710. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42711. __decorate([
  42712. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42713. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42714. __decorate([
  42715. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42716. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42717. __decorate([
  42718. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42719. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42720. __decorate([
  42721. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42722. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42723. __decorate([
  42724. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42725. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42726. __decorate([
  42727. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42728. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42729. __decorate([
  42730. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42731. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42732. __decorate([
  42733. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42734. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42735. __decorate([
  42736. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42737. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42738. __decorate([
  42739. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42740. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42741. __decorate([
  42742. BABYLON.serialize("maxSimultaneousLights")
  42743. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42744. __decorate([
  42745. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42746. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42747. __decorate([
  42748. BABYLON.serialize("invertNormalMapX")
  42749. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42750. __decorate([
  42751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42752. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42753. __decorate([
  42754. BABYLON.serialize("invertNormalMapY")
  42755. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42756. __decorate([
  42757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42758. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42759. __decorate([
  42760. BABYLON.serialize("twoSidedLighting")
  42761. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42762. __decorate([
  42763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42764. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42765. __decorate([
  42766. BABYLON.serialize()
  42767. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42768. BABYLON.StandardMaterial = StandardMaterial;
  42769. })(BABYLON || (BABYLON = {}));
  42770. //# sourceMappingURL=babylon.standardMaterial.js.map
  42771. var BABYLON;
  42772. (function (BABYLON) {
  42773. /**
  42774. * This class implement a typical dictionary using a string as key and the generic type T as value.
  42775. * The underlying implementation relies on an associative array to ensure the best performances.
  42776. * The value can be anything including 'null' but except 'undefined'
  42777. */
  42778. var StringDictionary = (function () {
  42779. function StringDictionary() {
  42780. this._count = 0;
  42781. this._data = {};
  42782. }
  42783. /**
  42784. * This will clear this dictionary and copy the content from the 'source' one.
  42785. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  42786. * @param source the dictionary to take the content from and copy to this dictionary
  42787. */
  42788. StringDictionary.prototype.copyFrom = function (source) {
  42789. var _this = this;
  42790. this.clear();
  42791. source.forEach(function (t, v) { return _this.add(t, v); });
  42792. };
  42793. /**
  42794. * Get a value based from its key
  42795. * @param key the given key to get the matching value from
  42796. * @return the value if found, otherwise undefined is returned
  42797. */
  42798. StringDictionary.prototype.get = function (key) {
  42799. var val = this._data[key];
  42800. if (val !== undefined) {
  42801. return val;
  42802. }
  42803. return undefined;
  42804. };
  42805. /**
  42806. * Get a value from its key or add it if it doesn't exist.
  42807. * This method will ensure you that a given key/data will be present in the dictionary.
  42808. * @param key the given key to get the matching value from
  42809. * @param factory the factory that will create the value if the key is not present in the dictionary.
  42810. * The factory will only be invoked if there's no data for the given key.
  42811. * @return the value corresponding to the key.
  42812. */
  42813. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  42814. var val = this.get(key);
  42815. if (val !== undefined) {
  42816. return val;
  42817. }
  42818. val = factory(key);
  42819. if (val) {
  42820. this.add(key, val);
  42821. }
  42822. return val;
  42823. };
  42824. /**
  42825. * Get a value from its key if present in the dictionary otherwise add it
  42826. * @param key the key to get the value from
  42827. * @param val if there's no such key/value pair in the dictionary add it with this value
  42828. * @return the value corresponding to the key
  42829. */
  42830. StringDictionary.prototype.getOrAdd = function (key, val) {
  42831. var curVal = this.get(key);
  42832. if (curVal !== undefined) {
  42833. return curVal;
  42834. }
  42835. this.add(key, val);
  42836. return val;
  42837. };
  42838. /**
  42839. * Check if there's a given key in the dictionary
  42840. * @param key the key to check for
  42841. * @return true if the key is present, false otherwise
  42842. */
  42843. StringDictionary.prototype.contains = function (key) {
  42844. return this._data[key] !== undefined;
  42845. };
  42846. /**
  42847. * Add a new key and its corresponding value
  42848. * @param key the key to add
  42849. * @param value the value corresponding to the key
  42850. * @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
  42851. */
  42852. StringDictionary.prototype.add = function (key, value) {
  42853. if (this._data[key] !== undefined) {
  42854. return false;
  42855. }
  42856. this._data[key] = value;
  42857. ++this._count;
  42858. return true;
  42859. };
  42860. StringDictionary.prototype.set = function (key, value) {
  42861. if (this._data[key] === undefined) {
  42862. return false;
  42863. }
  42864. this._data[key] = value;
  42865. return true;
  42866. };
  42867. /**
  42868. * Get the element of the given key and remove it from the dictionary
  42869. * @param key
  42870. */
  42871. StringDictionary.prototype.getAndRemove = function (key) {
  42872. var val = this.get(key);
  42873. if (val !== undefined) {
  42874. delete this._data[key];
  42875. --this._count;
  42876. return val;
  42877. }
  42878. return null;
  42879. };
  42880. /**
  42881. * Remove a key/value from the dictionary.
  42882. * @param key the key to remove
  42883. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  42884. */
  42885. StringDictionary.prototype.remove = function (key) {
  42886. if (this.contains(key)) {
  42887. delete this._data[key];
  42888. --this._count;
  42889. return true;
  42890. }
  42891. return false;
  42892. };
  42893. /**
  42894. * Clear the whole content of the dictionary
  42895. */
  42896. StringDictionary.prototype.clear = function () {
  42897. this._data = {};
  42898. this._count = 0;
  42899. };
  42900. Object.defineProperty(StringDictionary.prototype, "count", {
  42901. get: function () {
  42902. return this._count;
  42903. },
  42904. enumerable: true,
  42905. configurable: true
  42906. });
  42907. /**
  42908. * Execute a callback on each key/val of the dictionary.
  42909. * Note that you can remove any element in this dictionary in the callback implementation
  42910. * @param callback the callback to execute on a given key/value pair
  42911. */
  42912. StringDictionary.prototype.forEach = function (callback) {
  42913. for (var cur in this._data) {
  42914. var val = this._data[cur];
  42915. callback(cur, val);
  42916. }
  42917. };
  42918. /**
  42919. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  42920. * If the callback returns null or undefined the method will iterate to the next key/value pair
  42921. * Note that you can remove any element in this dictionary in the callback implementation
  42922. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  42923. */
  42924. StringDictionary.prototype.first = function (callback) {
  42925. for (var cur in this._data) {
  42926. var val = this._data[cur];
  42927. var res = callback(cur, val);
  42928. if (res) {
  42929. return res;
  42930. }
  42931. }
  42932. return null;
  42933. };
  42934. return StringDictionary;
  42935. }());
  42936. BABYLON.StringDictionary = StringDictionary;
  42937. })(BABYLON || (BABYLON = {}));
  42938. //# sourceMappingURL=babylon.stringDictionary.js.map
  42939. var BABYLON;
  42940. (function (BABYLON) {
  42941. var DynamicFloatArrayElementInfo = (function () {
  42942. function DynamicFloatArrayElementInfo() {
  42943. }
  42944. return DynamicFloatArrayElementInfo;
  42945. }());
  42946. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  42947. /**
  42948. * 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.
  42949. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  42950. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  42951. * 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.
  42952. * 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.
  42953. * 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".
  42954. */
  42955. var DynamicFloatArray = (function () {
  42956. /**
  42957. * Construct an instance of the dynamic float array
  42958. * @param stride size of one element in float (i.e. not bytes!)
  42959. * @param initialElementCount the number of available entries at construction
  42960. */
  42961. function DynamicFloatArray(stride, initialElementCount) {
  42962. this.compareValueOffset = null;
  42963. this.sortingAscending = true;
  42964. this._stride = stride;
  42965. this.buffer = new Float32Array(stride * initialElementCount);
  42966. this._lastUsed = 0;
  42967. this._firstFree = 0;
  42968. this._allEntries = new Array(initialElementCount);
  42969. this._freeEntries = new Array(initialElementCount);
  42970. for (var i = 0; i < initialElementCount; i++) {
  42971. var element = new DynamicFloatArrayElementInfo();
  42972. element.offset = i * stride;
  42973. this._allEntries[i] = element;
  42974. this._freeEntries[initialElementCount - i - 1] = element;
  42975. }
  42976. }
  42977. /**
  42978. * Allocate an element in the array.
  42979. * @return the element info instance that contains the offset into the main buffer of the element's location.
  42980. * Beware, this offset may change when you call pack()
  42981. */
  42982. DynamicFloatArray.prototype.allocElement = function () {
  42983. if (this._freeEntries.length === 0) {
  42984. this._growBuffer();
  42985. }
  42986. var el = this._freeEntries.pop();
  42987. this._lastUsed = Math.max(el.offset, this._lastUsed);
  42988. if (el.offset === this._firstFree) {
  42989. if (this._freeEntries.length > 0) {
  42990. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  42991. }
  42992. else {
  42993. this._firstFree += this._stride;
  42994. }
  42995. }
  42996. return el;
  42997. };
  42998. /**
  42999. * Free the element corresponding to the given element info
  43000. * @param elInfo the element that describe the allocated element
  43001. */
  43002. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43003. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43004. this._freeEntries.push(elInfo);
  43005. };
  43006. /**
  43007. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43008. * 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().
  43009. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43010. */
  43011. DynamicFloatArray.prototype.pack = function () {
  43012. // no free slot? no need to pack
  43013. if (this._freeEntries.length === 0) {
  43014. return this.buffer;
  43015. }
  43016. // If the buffer is already packed the last used will always be lower than the first free
  43017. // 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.
  43018. if (this._lastUsed < this._firstFree) {
  43019. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43020. return elementsBuffer_1;
  43021. }
  43022. var s = this._stride;
  43023. // 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
  43024. var lastFree = new DynamicFloatArrayElementInfo();
  43025. lastFree.offset = this.totalElementCount * s;
  43026. this._freeEntries.push(lastFree);
  43027. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43028. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43029. var firstFreeSlotOffset = sortedFree[0].offset;
  43030. var freeZoneSize = 1;
  43031. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43032. var prevOffset = sortedFree[0].offset;
  43033. for (var i = 1; i < sortedFree.length; i++) {
  43034. // 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
  43035. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43036. break;
  43037. }
  43038. var curFree = sortedFree[i];
  43039. var curOffset = curFree.offset;
  43040. // Compute the distance between this offset and the previous
  43041. var distance = curOffset - prevOffset;
  43042. // If the distance is the stride size, they are adjacent, it good, move to the next
  43043. if (distance === s) {
  43044. // Free zone is one element bigger
  43045. ++freeZoneSize;
  43046. // as we're about to iterate to the next, the cur becomes the previous...
  43047. prevOffset = curOffset;
  43048. continue;
  43049. }
  43050. // Distance is bigger, which means there's x element between the previous free and this one
  43051. var usedRange = (distance / s) - 1;
  43052. // Two cases the free zone is smaller than the data to move or bigger
  43053. // Copy what can fit in the free zone
  43054. var curMoveOffset = curOffset - s;
  43055. var copyCount = Math.min(freeZoneSize, usedRange);
  43056. for (var j = 0; j < copyCount; j++) {
  43057. var freeI = firstFreeSlotOffset / s;
  43058. var curI = curMoveOffset / s;
  43059. var moveEl = sortedAll[curI];
  43060. this._moveElement(moveEl, firstFreeSlotOffset);
  43061. var replacedEl = sortedAll[freeI];
  43062. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43063. replacedEl.offset = curMoveOffset;
  43064. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43065. sortedAll[freeI] = moveEl;
  43066. sortedAll[curI] = replacedEl;
  43067. curMoveOffset -= s;
  43068. firstFreeSlotOffset += s;
  43069. }
  43070. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43071. if (freeZoneSize <= usedRange) {
  43072. firstFreeSlotOffset = curMoveOffset + s;
  43073. freeZoneSize = 1 + copyCount;
  43074. }
  43075. else {
  43076. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43077. }
  43078. // as we're about to iterate to the next, the cur becomes the previous...
  43079. prevOffset = curOffset;
  43080. }
  43081. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43082. this._lastUsed = firstFreeSlotOffset - s;
  43083. this._firstFree = firstFreeSlotOffset;
  43084. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43085. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43086. this._allEntries = sortedAll;
  43087. return elementsBuffer;
  43088. };
  43089. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43090. for (var i = 0; i < this._stride; i++) {
  43091. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43092. }
  43093. element.offset = destOffset;
  43094. };
  43095. DynamicFloatArray.prototype._growBuffer = function () {
  43096. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43097. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43098. var newBuffer = new Float32Array(newElCount * this._stride);
  43099. newBuffer.set(this.buffer);
  43100. var curCount = this.totalElementCount;
  43101. var addedCount = newElCount - this.totalElementCount;
  43102. for (var i = 0; i < addedCount; i++) {
  43103. var element = new DynamicFloatArrayElementInfo();
  43104. element.offset = (curCount + i) * this.stride;
  43105. this._allEntries.push(element);
  43106. this._freeEntries[addedCount - i - 1] = element;
  43107. }
  43108. this._firstFree = curCount * this.stride;
  43109. this.buffer = newBuffer;
  43110. };
  43111. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43112. /**
  43113. * Get the total count of entries that can fit in the current buffer
  43114. * @returns the elements count
  43115. */
  43116. get: function () {
  43117. return this._allEntries.length;
  43118. },
  43119. enumerable: true,
  43120. configurable: true
  43121. });
  43122. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43123. /**
  43124. * Get the count of free entries that can still be allocated without resizing the buffer
  43125. * @returns the free elements count
  43126. */
  43127. get: function () {
  43128. return this._freeEntries.length;
  43129. },
  43130. enumerable: true,
  43131. configurable: true
  43132. });
  43133. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43134. /**
  43135. * Get the count of allocated elements
  43136. * @returns the allocated elements count
  43137. */
  43138. get: function () {
  43139. return this._allEntries.length - this._freeEntries.length;
  43140. },
  43141. enumerable: true,
  43142. configurable: true
  43143. });
  43144. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43145. /**
  43146. * Return the size of one element in float
  43147. * @returns the size in float
  43148. */
  43149. get: function () {
  43150. return this._stride;
  43151. },
  43152. enumerable: true,
  43153. configurable: true
  43154. });
  43155. DynamicFloatArray.prototype.sort = function () {
  43156. var _this = this;
  43157. if (!this.compareValueOffset) {
  43158. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43159. }
  43160. var count = this.usedElementCount;
  43161. // Do we have to (re)create the sort table?
  43162. if (!this._sortTable || this._sortTable.length < count) {
  43163. // 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...
  43164. var newCount = Math.min(this.totalElementCount, count * 2);
  43165. this._sortTable = new Array(newCount);
  43166. }
  43167. if (!this._sortedTable || this._sortedTable.length !== count) {
  43168. this._sortedTable = new Array(count);
  43169. }
  43170. // Because, you know...
  43171. this.pack();
  43172. //let stride = this.stride;
  43173. //for (let i = 0; i < count; i++) {
  43174. // let si = this._sortTable[i];
  43175. // if (!si) {
  43176. // si = new SortInfo();
  43177. // this._sortTable[i] = si;
  43178. // }
  43179. // si.entry = this._allEntries[i];
  43180. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43181. // si.swapedOffset = null;
  43182. // this._sortedTable[i] = si;
  43183. //}
  43184. var curOffset = 0;
  43185. var stride = this.stride;
  43186. for (var i = 0; i < count; i++, curOffset += stride) {
  43187. var si = this._sortTable[i];
  43188. if (!si) {
  43189. si = new SortInfo();
  43190. this._sortTable[i] = si;
  43191. }
  43192. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43193. si.offset = curOffset;
  43194. si.swapedOffset = null;
  43195. this._sortedTable[i] = si;
  43196. }
  43197. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43198. if (this.sortingAscending) {
  43199. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43200. }
  43201. else {
  43202. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43203. }
  43204. var swapElements = function (src, dst) {
  43205. for (var i = 0; i < stride; i++) {
  43206. var tps = _this.buffer[dst + i];
  43207. _this.buffer[dst + i] = _this.buffer[src + i];
  43208. _this.buffer[src + i] = tps;
  43209. }
  43210. };
  43211. // 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:
  43212. // 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),
  43213. // and I still want something with a good algorithm complexity.
  43214. // 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,
  43215. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43216. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43217. // 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
  43218. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43219. // 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
  43220. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43221. for (var i = 0; i < count; i++) {
  43222. // Get the element to move
  43223. var sourceSI = this._sortedTable[i];
  43224. var destSI = this._sortTable[i];
  43225. var sourceOff = sourceSI.offset;
  43226. // If the source changed location, find the new one
  43227. if (sourceSI.swapedOffset) {
  43228. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43229. var curSI = sourceSI;
  43230. while (curSI.swapedOffset) {
  43231. curSI = this._sortTable[curSI.swapedOffset / stride];
  43232. }
  43233. // Finally get the right location
  43234. sourceOff = curSI.offset;
  43235. }
  43236. // Tag the element being replaced with its new location
  43237. destSI.swapedOffset = sourceOff;
  43238. // Swap elements (only if needed)
  43239. if (sourceOff !== destSI.offset) {
  43240. swapElements(sourceOff, destSI.offset);
  43241. }
  43242. // Update the offset in the corresponding DFAE
  43243. //sourceSI.entry.offset = destSI.entry.offset;
  43244. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43245. }
  43246. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43247. return true;
  43248. };
  43249. return DynamicFloatArray;
  43250. }());
  43251. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43252. var SortInfo = (function () {
  43253. function SortInfo() {
  43254. this.compareData = this.offset = this.swapedOffset = null;
  43255. }
  43256. return SortInfo;
  43257. }());
  43258. })(BABYLON || (BABYLON = {}));
  43259. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43260. var BABYLON;
  43261. (function (BABYLON) {
  43262. var Condition = (function () {
  43263. function Condition(actionManager) {
  43264. this._actionManager = actionManager;
  43265. }
  43266. Condition.prototype.isValid = function () {
  43267. return true;
  43268. };
  43269. Condition.prototype._getProperty = function (propertyPath) {
  43270. return this._actionManager._getProperty(propertyPath);
  43271. };
  43272. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43273. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43274. };
  43275. Condition.prototype.serialize = function () {
  43276. };
  43277. Condition.prototype._serialize = function (serializedCondition) {
  43278. return {
  43279. type: 2,
  43280. children: [],
  43281. name: serializedCondition.name,
  43282. properties: serializedCondition.properties
  43283. };
  43284. };
  43285. return Condition;
  43286. }());
  43287. BABYLON.Condition = Condition;
  43288. var ValueCondition = (function (_super) {
  43289. __extends(ValueCondition, _super);
  43290. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43291. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43292. var _this = _super.call(this, actionManager) || this;
  43293. _this.propertyPath = propertyPath;
  43294. _this.value = value;
  43295. _this.operator = operator;
  43296. _this._target = target;
  43297. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43298. _this._property = _this._getProperty(_this.propertyPath);
  43299. return _this;
  43300. }
  43301. Object.defineProperty(ValueCondition, "IsEqual", {
  43302. get: function () {
  43303. return ValueCondition._IsEqual;
  43304. },
  43305. enumerable: true,
  43306. configurable: true
  43307. });
  43308. Object.defineProperty(ValueCondition, "IsDifferent", {
  43309. get: function () {
  43310. return ValueCondition._IsDifferent;
  43311. },
  43312. enumerable: true,
  43313. configurable: true
  43314. });
  43315. Object.defineProperty(ValueCondition, "IsGreater", {
  43316. get: function () {
  43317. return ValueCondition._IsGreater;
  43318. },
  43319. enumerable: true,
  43320. configurable: true
  43321. });
  43322. Object.defineProperty(ValueCondition, "IsLesser", {
  43323. get: function () {
  43324. return ValueCondition._IsLesser;
  43325. },
  43326. enumerable: true,
  43327. configurable: true
  43328. });
  43329. // Methods
  43330. ValueCondition.prototype.isValid = function () {
  43331. switch (this.operator) {
  43332. case ValueCondition.IsGreater:
  43333. return this._effectiveTarget[this._property] > this.value;
  43334. case ValueCondition.IsLesser:
  43335. return this._effectiveTarget[this._property] < this.value;
  43336. case ValueCondition.IsEqual:
  43337. case ValueCondition.IsDifferent:
  43338. var check;
  43339. if (this.value.equals) {
  43340. check = this.value.equals(this._effectiveTarget[this._property]);
  43341. }
  43342. else {
  43343. check = this.value === this._effectiveTarget[this._property];
  43344. }
  43345. return this.operator === ValueCondition.IsEqual ? check : !check;
  43346. }
  43347. return false;
  43348. };
  43349. ValueCondition.prototype.serialize = function () {
  43350. return this._serialize({
  43351. name: "ValueCondition",
  43352. properties: [
  43353. BABYLON.Action._GetTargetProperty(this._target),
  43354. { name: "propertyPath", value: this.propertyPath },
  43355. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43356. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43357. ]
  43358. });
  43359. };
  43360. ValueCondition.GetOperatorName = function (operator) {
  43361. switch (operator) {
  43362. case ValueCondition._IsEqual: return "IsEqual";
  43363. case ValueCondition._IsDifferent: return "IsDifferent";
  43364. case ValueCondition._IsGreater: return "IsGreater";
  43365. case ValueCondition._IsLesser: return "IsLesser";
  43366. default: return "";
  43367. }
  43368. };
  43369. return ValueCondition;
  43370. }(Condition));
  43371. // Statics
  43372. ValueCondition._IsEqual = 0;
  43373. ValueCondition._IsDifferent = 1;
  43374. ValueCondition._IsGreater = 2;
  43375. ValueCondition._IsLesser = 3;
  43376. BABYLON.ValueCondition = ValueCondition;
  43377. var PredicateCondition = (function (_super) {
  43378. __extends(PredicateCondition, _super);
  43379. function PredicateCondition(actionManager, predicate) {
  43380. var _this = _super.call(this, actionManager) || this;
  43381. _this.predicate = predicate;
  43382. return _this;
  43383. }
  43384. PredicateCondition.prototype.isValid = function () {
  43385. return this.predicate();
  43386. };
  43387. return PredicateCondition;
  43388. }(Condition));
  43389. BABYLON.PredicateCondition = PredicateCondition;
  43390. var StateCondition = (function (_super) {
  43391. __extends(StateCondition, _super);
  43392. function StateCondition(actionManager, target, value) {
  43393. var _this = _super.call(this, actionManager) || this;
  43394. _this.value = value;
  43395. _this._target = target;
  43396. return _this;
  43397. }
  43398. // Methods
  43399. StateCondition.prototype.isValid = function () {
  43400. return this._target.state === this.value;
  43401. };
  43402. StateCondition.prototype.serialize = function () {
  43403. return this._serialize({
  43404. name: "StateCondition",
  43405. properties: [
  43406. BABYLON.Action._GetTargetProperty(this._target),
  43407. { name: "value", value: this.value }
  43408. ]
  43409. });
  43410. };
  43411. return StateCondition;
  43412. }(Condition));
  43413. BABYLON.StateCondition = StateCondition;
  43414. })(BABYLON || (BABYLON = {}));
  43415. //# sourceMappingURL=babylon.condition.js.map
  43416. var BABYLON;
  43417. (function (BABYLON) {
  43418. var Action = (function () {
  43419. function Action(triggerOptions, condition) {
  43420. this.triggerOptions = triggerOptions;
  43421. if (triggerOptions.parameter) {
  43422. this.trigger = triggerOptions.trigger;
  43423. this._triggerParameter = triggerOptions.parameter;
  43424. }
  43425. else {
  43426. this.trigger = triggerOptions;
  43427. }
  43428. this._nextActiveAction = this;
  43429. this._condition = condition;
  43430. }
  43431. // Methods
  43432. Action.prototype._prepare = function () {
  43433. };
  43434. Action.prototype.getTriggerParameter = function () {
  43435. return this._triggerParameter;
  43436. };
  43437. Action.prototype._executeCurrent = function (evt) {
  43438. if (this._nextActiveAction._condition) {
  43439. var condition = this._nextActiveAction._condition;
  43440. var currentRenderId = this._actionManager.getScene().getRenderId();
  43441. // We cache the current evaluation for the current frame
  43442. if (condition._evaluationId === currentRenderId) {
  43443. if (!condition._currentResult) {
  43444. return;
  43445. }
  43446. }
  43447. else {
  43448. condition._evaluationId = currentRenderId;
  43449. if (!condition.isValid()) {
  43450. condition._currentResult = false;
  43451. return;
  43452. }
  43453. condition._currentResult = true;
  43454. }
  43455. }
  43456. this._nextActiveAction.execute(evt);
  43457. this.skipToNextActiveAction();
  43458. };
  43459. Action.prototype.execute = function (evt) {
  43460. };
  43461. Action.prototype.skipToNextActiveAction = function () {
  43462. if (this._nextActiveAction._child) {
  43463. if (!this._nextActiveAction._child._actionManager) {
  43464. this._nextActiveAction._child._actionManager = this._actionManager;
  43465. }
  43466. this._nextActiveAction = this._nextActiveAction._child;
  43467. }
  43468. else {
  43469. this._nextActiveAction = this;
  43470. }
  43471. };
  43472. Action.prototype.then = function (action) {
  43473. this._child = action;
  43474. action._actionManager = this._actionManager;
  43475. action._prepare();
  43476. return action;
  43477. };
  43478. Action.prototype._getProperty = function (propertyPath) {
  43479. return this._actionManager._getProperty(propertyPath);
  43480. };
  43481. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43482. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43483. };
  43484. Action.prototype.serialize = function (parent) {
  43485. };
  43486. // Called by BABYLON.Action objects in serialize(...). Internal use
  43487. Action.prototype._serialize = function (serializedAction, parent) {
  43488. var serializationObject = {
  43489. type: 1,
  43490. children: [],
  43491. name: serializedAction.name,
  43492. properties: serializedAction.properties || []
  43493. };
  43494. // Serialize child
  43495. if (this._child) {
  43496. this._child.serialize(serializationObject);
  43497. }
  43498. // Check if "this" has a condition
  43499. if (this._condition) {
  43500. var serializedCondition = this._condition.serialize();
  43501. serializedCondition.children.push(serializationObject);
  43502. if (parent) {
  43503. parent.children.push(serializedCondition);
  43504. }
  43505. return serializedCondition;
  43506. }
  43507. if (parent) {
  43508. parent.children.push(serializationObject);
  43509. }
  43510. return serializationObject;
  43511. };
  43512. return Action;
  43513. }());
  43514. Action._SerializeValueAsString = function (value) {
  43515. if (typeof value === "number") {
  43516. return value.toString();
  43517. }
  43518. if (typeof value === "boolean") {
  43519. return value ? "true" : "false";
  43520. }
  43521. if (value instanceof BABYLON.Vector2) {
  43522. return value.x + ", " + value.y;
  43523. }
  43524. if (value instanceof BABYLON.Vector3) {
  43525. return value.x + ", " + value.y + ", " + value.z;
  43526. }
  43527. if (value instanceof BABYLON.Color3) {
  43528. return value.r + ", " + value.g + ", " + value.b;
  43529. }
  43530. if (value instanceof BABYLON.Color4) {
  43531. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43532. }
  43533. return value; // string
  43534. };
  43535. Action._GetTargetProperty = function (target) {
  43536. return {
  43537. name: "target",
  43538. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43539. : target instanceof BABYLON.Light ? "LightProperties"
  43540. : target instanceof BABYLON.Camera ? "CameraProperties"
  43541. : "SceneProperties",
  43542. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43543. };
  43544. };
  43545. BABYLON.Action = Action;
  43546. })(BABYLON || (BABYLON = {}));
  43547. //# sourceMappingURL=babylon.action.js.map
  43548. var BABYLON;
  43549. (function (BABYLON) {
  43550. /**
  43551. * ActionEvent is the event beint sent when an action is triggered.
  43552. */
  43553. var ActionEvent = (function () {
  43554. /**
  43555. * @constructor
  43556. * @param source The mesh or sprite that triggered the action.
  43557. * @param pointerX The X mouse cursor position at the time of the event
  43558. * @param pointerY The Y mouse cursor position at the time of the event
  43559. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43560. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43561. */
  43562. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43563. this.source = source;
  43564. this.pointerX = pointerX;
  43565. this.pointerY = pointerY;
  43566. this.meshUnderPointer = meshUnderPointer;
  43567. this.sourceEvent = sourceEvent;
  43568. this.additionalData = additionalData;
  43569. }
  43570. /**
  43571. * Helper function to auto-create an ActionEvent from a source mesh.
  43572. * @param source The source mesh that triggered the event
  43573. * @param evt {Event} The original (browser) event
  43574. */
  43575. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43576. var scene = source.getScene();
  43577. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43578. };
  43579. /**
  43580. * Helper function to auto-create an ActionEvent from a source mesh.
  43581. * @param source The source sprite that triggered the event
  43582. * @param scene Scene associated with the sprite
  43583. * @param evt {Event} The original (browser) event
  43584. */
  43585. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43586. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43587. };
  43588. /**
  43589. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43590. * @param scene the scene where the event occurred
  43591. * @param evt {Event} The original (browser) event
  43592. */
  43593. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43594. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43595. };
  43596. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43597. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43598. };
  43599. return ActionEvent;
  43600. }());
  43601. BABYLON.ActionEvent = ActionEvent;
  43602. /**
  43603. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43604. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43605. */
  43606. var ActionManager = (function () {
  43607. function ActionManager(scene) {
  43608. // Members
  43609. this.actions = new Array();
  43610. this.hoverCursor = '';
  43611. this._scene = scene;
  43612. scene._actionManagers.push(this);
  43613. }
  43614. Object.defineProperty(ActionManager, "NothingTrigger", {
  43615. get: function () {
  43616. return ActionManager._NothingTrigger;
  43617. },
  43618. enumerable: true,
  43619. configurable: true
  43620. });
  43621. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43622. get: function () {
  43623. return ActionManager._OnPickTrigger;
  43624. },
  43625. enumerable: true,
  43626. configurable: true
  43627. });
  43628. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43629. get: function () {
  43630. return ActionManager._OnLeftPickTrigger;
  43631. },
  43632. enumerable: true,
  43633. configurable: true
  43634. });
  43635. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43636. get: function () {
  43637. return ActionManager._OnRightPickTrigger;
  43638. },
  43639. enumerable: true,
  43640. configurable: true
  43641. });
  43642. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43643. get: function () {
  43644. return ActionManager._OnCenterPickTrigger;
  43645. },
  43646. enumerable: true,
  43647. configurable: true
  43648. });
  43649. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43650. get: function () {
  43651. return ActionManager._OnPickDownTrigger;
  43652. },
  43653. enumerable: true,
  43654. configurable: true
  43655. });
  43656. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43657. get: function () {
  43658. return ActionManager._OnDoublePickTrigger;
  43659. },
  43660. enumerable: true,
  43661. configurable: true
  43662. });
  43663. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43664. get: function () {
  43665. return ActionManager._OnPickUpTrigger;
  43666. },
  43667. enumerable: true,
  43668. configurable: true
  43669. });
  43670. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43671. /// This trigger will only be raised if you also declared a OnPickDown
  43672. get: function () {
  43673. return ActionManager._OnPickOutTrigger;
  43674. },
  43675. enumerable: true,
  43676. configurable: true
  43677. });
  43678. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43679. get: function () {
  43680. return ActionManager._OnLongPressTrigger;
  43681. },
  43682. enumerable: true,
  43683. configurable: true
  43684. });
  43685. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43686. get: function () {
  43687. return ActionManager._OnPointerOverTrigger;
  43688. },
  43689. enumerable: true,
  43690. configurable: true
  43691. });
  43692. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43693. get: function () {
  43694. return ActionManager._OnPointerOutTrigger;
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43700. get: function () {
  43701. return ActionManager._OnEveryFrameTrigger;
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43707. get: function () {
  43708. return ActionManager._OnIntersectionEnterTrigger;
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43714. get: function () {
  43715. return ActionManager._OnIntersectionExitTrigger;
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43721. get: function () {
  43722. return ActionManager._OnKeyDownTrigger;
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43728. get: function () {
  43729. return ActionManager._OnKeyUpTrigger;
  43730. },
  43731. enumerable: true,
  43732. configurable: true
  43733. });
  43734. // Methods
  43735. ActionManager.prototype.dispose = function () {
  43736. var index = this._scene._actionManagers.indexOf(this);
  43737. for (var i = 0; i < this.actions.length; i++) {
  43738. var action = this.actions[i];
  43739. ActionManager.Triggers[action.trigger]--;
  43740. if (ActionManager.Triggers[action.trigger] === 0) {
  43741. delete ActionManager.Triggers[action.trigger];
  43742. }
  43743. }
  43744. if (index > -1) {
  43745. this._scene._actionManagers.splice(index, 1);
  43746. }
  43747. };
  43748. ActionManager.prototype.getScene = function () {
  43749. return this._scene;
  43750. };
  43751. /**
  43752. * Does this action manager handles actions of any of the given triggers
  43753. * @param {number[]} triggers - the triggers to be tested
  43754. * @return {boolean} whether one (or more) of the triggers is handeled
  43755. */
  43756. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43757. for (var index = 0; index < this.actions.length; index++) {
  43758. var action = this.actions[index];
  43759. if (triggers.indexOf(action.trigger) > -1) {
  43760. return true;
  43761. }
  43762. }
  43763. return false;
  43764. };
  43765. /**
  43766. * Does this action manager handles actions of a given trigger
  43767. * @param {number} trigger - the trigger to be tested
  43768. * @return {boolean} whether the trigger is handeled
  43769. */
  43770. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43771. for (var index = 0; index < this.actions.length; index++) {
  43772. var action = this.actions[index];
  43773. if (action.trigger === trigger) {
  43774. return true;
  43775. }
  43776. }
  43777. return false;
  43778. };
  43779. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43780. /**
  43781. * Does this action manager has pointer triggers
  43782. * @return {boolean} whether or not it has pointer triggers
  43783. */
  43784. get: function () {
  43785. for (var index = 0; index < this.actions.length; index++) {
  43786. var action = this.actions[index];
  43787. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43788. return true;
  43789. }
  43790. }
  43791. return false;
  43792. },
  43793. enumerable: true,
  43794. configurable: true
  43795. });
  43796. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43797. /**
  43798. * Does this action manager has pick triggers
  43799. * @return {boolean} whether or not it has pick triggers
  43800. */
  43801. get: function () {
  43802. for (var index = 0; index < this.actions.length; index++) {
  43803. var action = this.actions[index];
  43804. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43805. return true;
  43806. }
  43807. }
  43808. return false;
  43809. },
  43810. enumerable: true,
  43811. configurable: true
  43812. });
  43813. Object.defineProperty(ActionManager, "HasTriggers", {
  43814. /**
  43815. * Does exist one action manager with at least one trigger
  43816. * @return {boolean} whether or not it exists one action manager with one trigger
  43817. **/
  43818. get: function () {
  43819. for (var t in ActionManager.Triggers) {
  43820. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43821. return true;
  43822. }
  43823. }
  43824. return false;
  43825. },
  43826. enumerable: true,
  43827. configurable: true
  43828. });
  43829. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43830. /**
  43831. * Does exist one action manager with at least one pick trigger
  43832. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43833. **/
  43834. get: function () {
  43835. for (var t in ActionManager.Triggers) {
  43836. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43837. var t_int = parseInt(t);
  43838. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43839. return true;
  43840. }
  43841. }
  43842. }
  43843. return false;
  43844. },
  43845. enumerable: true,
  43846. configurable: true
  43847. });
  43848. /**
  43849. * Does exist one action manager that handles actions of a given trigger
  43850. * @param {number} trigger - the trigger to be tested
  43851. * @return {boolean} whether the trigger is handeled by at least one action manager
  43852. **/
  43853. ActionManager.HasSpecificTrigger = function (trigger) {
  43854. for (var t in ActionManager.Triggers) {
  43855. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43856. var t_int = parseInt(t);
  43857. if (t_int === trigger) {
  43858. return true;
  43859. }
  43860. }
  43861. }
  43862. return false;
  43863. };
  43864. /**
  43865. * Registers an action to this action manager
  43866. * @param {BABYLON.Action} action - the action to be registered
  43867. * @return {BABYLON.Action} the action amended (prepared) after registration
  43868. */
  43869. ActionManager.prototype.registerAction = function (action) {
  43870. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43871. if (this.getScene().actionManager !== this) {
  43872. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43873. return null;
  43874. }
  43875. }
  43876. this.actions.push(action);
  43877. if (ActionManager.Triggers[action.trigger]) {
  43878. ActionManager.Triggers[action.trigger]++;
  43879. }
  43880. else {
  43881. ActionManager.Triggers[action.trigger] = 1;
  43882. }
  43883. action._actionManager = this;
  43884. action._prepare();
  43885. return action;
  43886. };
  43887. /**
  43888. * Process a specific trigger
  43889. * @param {number} trigger - the trigger to process
  43890. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43891. */
  43892. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43893. for (var index = 0; index < this.actions.length; index++) {
  43894. var action = this.actions[index];
  43895. if (action.trigger === trigger) {
  43896. if (trigger === ActionManager.OnKeyUpTrigger
  43897. || trigger === ActionManager.OnKeyDownTrigger) {
  43898. var parameter = action.getTriggerParameter();
  43899. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43900. if (!parameter.toLowerCase) {
  43901. continue;
  43902. }
  43903. var lowerCase = parameter.toLowerCase();
  43904. if (lowerCase !== evt.sourceEvent.key) {
  43905. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43906. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43907. if (actualkey !== lowerCase) {
  43908. continue;
  43909. }
  43910. }
  43911. }
  43912. }
  43913. action._executeCurrent(evt);
  43914. }
  43915. }
  43916. };
  43917. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43918. var properties = propertyPath.split(".");
  43919. for (var index = 0; index < properties.length - 1; index++) {
  43920. target = target[properties[index]];
  43921. }
  43922. return target;
  43923. };
  43924. ActionManager.prototype._getProperty = function (propertyPath) {
  43925. var properties = propertyPath.split(".");
  43926. return properties[properties.length - 1];
  43927. };
  43928. ActionManager.prototype.serialize = function (name) {
  43929. var root = {
  43930. children: [],
  43931. name: name,
  43932. type: 3,
  43933. properties: [] // Empty for root but required
  43934. };
  43935. for (var i = 0; i < this.actions.length; i++) {
  43936. var triggerObject = {
  43937. type: 0,
  43938. children: [],
  43939. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43940. properties: []
  43941. };
  43942. var triggerOptions = this.actions[i].triggerOptions;
  43943. if (triggerOptions && typeof triggerOptions !== "number") {
  43944. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43945. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43946. }
  43947. else {
  43948. var parameter = {};
  43949. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43950. if (triggerOptions.parameter.mesh) {
  43951. parameter._meshId = triggerOptions.parameter.mesh.id;
  43952. }
  43953. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43954. }
  43955. }
  43956. // Serialize child action, recursively
  43957. this.actions[i].serialize(triggerObject);
  43958. // Add serialized trigger
  43959. root.children.push(triggerObject);
  43960. }
  43961. return root;
  43962. };
  43963. ActionManager.Parse = function (parsedActions, object, scene) {
  43964. var actionManager = new BABYLON.ActionManager(scene);
  43965. if (object === null)
  43966. scene.actionManager = actionManager;
  43967. else
  43968. object.actionManager = actionManager;
  43969. // instanciate a new object
  43970. var instanciate = function (name, params) {
  43971. var newInstance = Object.create(BABYLON[name].prototype);
  43972. newInstance.constructor.apply(newInstance, params);
  43973. return newInstance;
  43974. };
  43975. var parseParameter = function (name, value, target, propertyPath) {
  43976. if (propertyPath === null) {
  43977. // String, boolean or float
  43978. var floatValue = parseFloat(value);
  43979. if (value === "true" || value === "false")
  43980. return value === "true";
  43981. else
  43982. return isNaN(floatValue) ? value : floatValue;
  43983. }
  43984. var effectiveTarget = propertyPath.split(".");
  43985. var values = value.split(",");
  43986. // Get effective Target
  43987. for (var i = 0; i < effectiveTarget.length; i++) {
  43988. target = target[effectiveTarget[i]];
  43989. }
  43990. // Return appropriate value with its type
  43991. if (typeof (target) === "boolean")
  43992. return values[0] === "true";
  43993. if (typeof (target) === "string")
  43994. return values[0];
  43995. // Parameters with multiple values such as Vector3 etc.
  43996. var split = new Array();
  43997. for (var i = 0; i < values.length; i++)
  43998. split.push(parseFloat(values[i]));
  43999. if (target instanceof BABYLON.Vector3)
  44000. return BABYLON.Vector3.FromArray(split);
  44001. if (target instanceof BABYLON.Vector4)
  44002. return BABYLON.Vector4.FromArray(split);
  44003. if (target instanceof BABYLON.Color3)
  44004. return BABYLON.Color3.FromArray(split);
  44005. if (target instanceof BABYLON.Color4)
  44006. return BABYLON.Color4.FromArray(split);
  44007. return parseFloat(values[0]);
  44008. };
  44009. // traverse graph per trigger
  44010. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44011. if (combineArray === void 0) { combineArray = null; }
  44012. if (parsedAction.detached)
  44013. return;
  44014. var parameters = new Array();
  44015. var target = null;
  44016. var propertyPath = null;
  44017. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44018. // Parameters
  44019. if (parsedAction.type === 2)
  44020. parameters.push(actionManager);
  44021. else
  44022. parameters.push(trigger);
  44023. if (combine) {
  44024. var actions = new Array();
  44025. for (var j = 0; j < parsedAction.combine.length; j++) {
  44026. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44027. }
  44028. parameters.push(actions);
  44029. }
  44030. else {
  44031. for (var i = 0; i < parsedAction.properties.length; i++) {
  44032. var value = parsedAction.properties[i].value;
  44033. var name = parsedAction.properties[i].name;
  44034. var targetType = parsedAction.properties[i].targetType;
  44035. if (name === "target")
  44036. if (targetType !== null && targetType === "SceneProperties")
  44037. value = target = scene;
  44038. else
  44039. value = target = scene.getNodeByName(value);
  44040. else if (name === "parent")
  44041. value = scene.getNodeByName(value);
  44042. else if (name === "sound")
  44043. value = scene.getSoundByName(value);
  44044. else if (name !== "propertyPath") {
  44045. if (parsedAction.type === 2 && name === "operator")
  44046. value = BABYLON.ValueCondition[value];
  44047. else
  44048. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44049. }
  44050. else {
  44051. propertyPath = value;
  44052. }
  44053. parameters.push(value);
  44054. }
  44055. }
  44056. if (combineArray === null) {
  44057. parameters.push(condition);
  44058. }
  44059. else {
  44060. parameters.push(null);
  44061. }
  44062. // If interpolate value action
  44063. if (parsedAction.name === "InterpolateValueAction") {
  44064. var param = parameters[parameters.length - 2];
  44065. parameters[parameters.length - 1] = param;
  44066. parameters[parameters.length - 2] = condition;
  44067. }
  44068. // Action or condition(s) and not CombineAction
  44069. var newAction = instanciate(parsedAction.name, parameters);
  44070. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44071. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44072. if (action)
  44073. action.then(nothing);
  44074. else
  44075. actionManager.registerAction(nothing);
  44076. action = nothing;
  44077. }
  44078. if (combineArray === null) {
  44079. if (newAction instanceof BABYLON.Condition) {
  44080. condition = newAction;
  44081. newAction = action;
  44082. }
  44083. else {
  44084. condition = null;
  44085. if (action)
  44086. action.then(newAction);
  44087. else
  44088. actionManager.registerAction(newAction);
  44089. }
  44090. }
  44091. else {
  44092. combineArray.push(newAction);
  44093. }
  44094. for (var i = 0; i < parsedAction.children.length; i++)
  44095. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44096. };
  44097. // triggers
  44098. for (var i = 0; i < parsedActions.children.length; i++) {
  44099. var triggerParams;
  44100. var trigger = parsedActions.children[i];
  44101. if (trigger.properties.length > 0) {
  44102. var param = trigger.properties[0].value;
  44103. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44104. if (value._meshId) {
  44105. value.mesh = scene.getMeshByID(value._meshId);
  44106. }
  44107. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  44108. }
  44109. else
  44110. triggerParams = BABYLON.ActionManager[trigger.name];
  44111. for (var j = 0; j < trigger.children.length; j++) {
  44112. if (!trigger.detached)
  44113. traverse(trigger.children[j], triggerParams, null, null);
  44114. }
  44115. }
  44116. };
  44117. ActionManager.GetTriggerName = function (trigger) {
  44118. switch (trigger) {
  44119. case 0: return "NothingTrigger";
  44120. case 1: return "OnPickTrigger";
  44121. case 2: return "OnLeftPickTrigger";
  44122. case 3: return "OnRightPickTrigger";
  44123. case 4: return "OnCenterPickTrigger";
  44124. case 5: return "OnPickDownTrigger";
  44125. case 6: return "OnPickUpTrigger";
  44126. case 7: return "OnLongPressTrigger";
  44127. case 8: return "OnPointerOverTrigger";
  44128. case 9: return "OnPointerOutTrigger";
  44129. case 10: return "OnEveryFrameTrigger";
  44130. case 11: return "OnIntersectionEnterTrigger";
  44131. case 12: return "OnIntersectionExitTrigger";
  44132. case 13: return "OnKeyDownTrigger";
  44133. case 14: return "OnKeyUpTrigger";
  44134. case 15: return "OnPickOutTrigger";
  44135. default: return "";
  44136. }
  44137. };
  44138. return ActionManager;
  44139. }());
  44140. // Statics
  44141. ActionManager._NothingTrigger = 0;
  44142. ActionManager._OnPickTrigger = 1;
  44143. ActionManager._OnLeftPickTrigger = 2;
  44144. ActionManager._OnRightPickTrigger = 3;
  44145. ActionManager._OnCenterPickTrigger = 4;
  44146. ActionManager._OnPickDownTrigger = 5;
  44147. ActionManager._OnDoublePickTrigger = 6;
  44148. ActionManager._OnPickUpTrigger = 7;
  44149. ActionManager._OnLongPressTrigger = 8;
  44150. ActionManager._OnPointerOverTrigger = 9;
  44151. ActionManager._OnPointerOutTrigger = 10;
  44152. ActionManager._OnEveryFrameTrigger = 11;
  44153. ActionManager._OnIntersectionEnterTrigger = 12;
  44154. ActionManager._OnIntersectionExitTrigger = 13;
  44155. ActionManager._OnKeyDownTrigger = 14;
  44156. ActionManager._OnKeyUpTrigger = 15;
  44157. ActionManager._OnPickOutTrigger = 16;
  44158. ActionManager.Triggers = {};
  44159. BABYLON.ActionManager = ActionManager;
  44160. })(BABYLON || (BABYLON = {}));
  44161. //# sourceMappingURL=babylon.actionManager.js.map
  44162. var BABYLON;
  44163. (function (BABYLON) {
  44164. var InterpolateValueAction = (function (_super) {
  44165. __extends(InterpolateValueAction, _super);
  44166. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44167. if (duration === void 0) { duration = 1000; }
  44168. var _this = _super.call(this, triggerOptions, condition) || this;
  44169. _this.propertyPath = propertyPath;
  44170. _this.value = value;
  44171. _this.duration = duration;
  44172. _this.stopOtherAnimations = stopOtherAnimations;
  44173. _this.onInterpolationDone = onInterpolationDone;
  44174. _this._target = _this._effectiveTarget = target;
  44175. return _this;
  44176. }
  44177. InterpolateValueAction.prototype._prepare = function () {
  44178. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44179. this._property = this._getProperty(this.propertyPath);
  44180. };
  44181. InterpolateValueAction.prototype.execute = function () {
  44182. var scene = this._actionManager.getScene();
  44183. var keys = [
  44184. {
  44185. frame: 0,
  44186. value: this._effectiveTarget[this._property]
  44187. }, {
  44188. frame: 100,
  44189. value: this.value
  44190. }
  44191. ];
  44192. var dataType;
  44193. if (typeof this.value === "number") {
  44194. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44195. }
  44196. else if (this.value instanceof BABYLON.Color3) {
  44197. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44198. }
  44199. else if (this.value instanceof BABYLON.Vector3) {
  44200. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44201. }
  44202. else if (this.value instanceof BABYLON.Matrix) {
  44203. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44204. }
  44205. else if (this.value instanceof BABYLON.Quaternion) {
  44206. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44207. }
  44208. else {
  44209. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44210. return;
  44211. }
  44212. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44213. animation.setKeys(keys);
  44214. if (this.stopOtherAnimations) {
  44215. scene.stopAnimation(this._effectiveTarget);
  44216. }
  44217. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  44218. };
  44219. InterpolateValueAction.prototype.serialize = function (parent) {
  44220. return _super.prototype._serialize.call(this, {
  44221. name: "InterpolateValueAction",
  44222. properties: [
  44223. BABYLON.Action._GetTargetProperty(this._target),
  44224. { name: "propertyPath", value: this.propertyPath },
  44225. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44226. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44227. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44228. ]
  44229. }, parent);
  44230. };
  44231. return InterpolateValueAction;
  44232. }(BABYLON.Action));
  44233. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44234. })(BABYLON || (BABYLON = {}));
  44235. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44236. var BABYLON;
  44237. (function (BABYLON) {
  44238. var SwitchBooleanAction = (function (_super) {
  44239. __extends(SwitchBooleanAction, _super);
  44240. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44241. var _this = _super.call(this, triggerOptions, condition) || this;
  44242. _this.propertyPath = propertyPath;
  44243. _this._target = _this._effectiveTarget = target;
  44244. return _this;
  44245. }
  44246. SwitchBooleanAction.prototype._prepare = function () {
  44247. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44248. this._property = this._getProperty(this.propertyPath);
  44249. };
  44250. SwitchBooleanAction.prototype.execute = function () {
  44251. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44252. };
  44253. SwitchBooleanAction.prototype.serialize = function (parent) {
  44254. return _super.prototype._serialize.call(this, {
  44255. name: "SwitchBooleanAction",
  44256. properties: [
  44257. BABYLON.Action._GetTargetProperty(this._target),
  44258. { name: "propertyPath", value: this.propertyPath }
  44259. ]
  44260. }, parent);
  44261. };
  44262. return SwitchBooleanAction;
  44263. }(BABYLON.Action));
  44264. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44265. var SetStateAction = (function (_super) {
  44266. __extends(SetStateAction, _super);
  44267. function SetStateAction(triggerOptions, target, value, condition) {
  44268. var _this = _super.call(this, triggerOptions, condition) || this;
  44269. _this.value = value;
  44270. _this._target = target;
  44271. return _this;
  44272. }
  44273. SetStateAction.prototype.execute = function () {
  44274. this._target.state = this.value;
  44275. };
  44276. SetStateAction.prototype.serialize = function (parent) {
  44277. return _super.prototype._serialize.call(this, {
  44278. name: "SetStateAction",
  44279. properties: [
  44280. BABYLON.Action._GetTargetProperty(this._target),
  44281. { name: "value", value: this.value }
  44282. ]
  44283. }, parent);
  44284. };
  44285. return SetStateAction;
  44286. }(BABYLON.Action));
  44287. BABYLON.SetStateAction = SetStateAction;
  44288. var SetValueAction = (function (_super) {
  44289. __extends(SetValueAction, _super);
  44290. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44291. var _this = _super.call(this, triggerOptions, condition) || this;
  44292. _this.propertyPath = propertyPath;
  44293. _this.value = value;
  44294. _this._target = _this._effectiveTarget = target;
  44295. return _this;
  44296. }
  44297. SetValueAction.prototype._prepare = function () {
  44298. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44299. this._property = this._getProperty(this.propertyPath);
  44300. };
  44301. SetValueAction.prototype.execute = function () {
  44302. this._effectiveTarget[this._property] = this.value;
  44303. if (this._target.markAsDirty) {
  44304. this._target.markAsDirty(this._property);
  44305. }
  44306. };
  44307. SetValueAction.prototype.serialize = function (parent) {
  44308. return _super.prototype._serialize.call(this, {
  44309. name: "SetValueAction",
  44310. properties: [
  44311. BABYLON.Action._GetTargetProperty(this._target),
  44312. { name: "propertyPath", value: this.propertyPath },
  44313. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44314. ]
  44315. }, parent);
  44316. };
  44317. return SetValueAction;
  44318. }(BABYLON.Action));
  44319. BABYLON.SetValueAction = SetValueAction;
  44320. var IncrementValueAction = (function (_super) {
  44321. __extends(IncrementValueAction, _super);
  44322. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44323. var _this = _super.call(this, triggerOptions, condition) || this;
  44324. _this.propertyPath = propertyPath;
  44325. _this.value = value;
  44326. _this._target = _this._effectiveTarget = target;
  44327. return _this;
  44328. }
  44329. IncrementValueAction.prototype._prepare = function () {
  44330. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44331. this._property = this._getProperty(this.propertyPath);
  44332. if (typeof this._effectiveTarget[this._property] !== "number") {
  44333. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44334. }
  44335. };
  44336. IncrementValueAction.prototype.execute = function () {
  44337. this._effectiveTarget[this._property] += this.value;
  44338. if (this._target.markAsDirty) {
  44339. this._target.markAsDirty(this._property);
  44340. }
  44341. };
  44342. IncrementValueAction.prototype.serialize = function (parent) {
  44343. return _super.prototype._serialize.call(this, {
  44344. name: "IncrementValueAction",
  44345. properties: [
  44346. BABYLON.Action._GetTargetProperty(this._target),
  44347. { name: "propertyPath", value: this.propertyPath },
  44348. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44349. ]
  44350. }, parent);
  44351. };
  44352. return IncrementValueAction;
  44353. }(BABYLON.Action));
  44354. BABYLON.IncrementValueAction = IncrementValueAction;
  44355. var PlayAnimationAction = (function (_super) {
  44356. __extends(PlayAnimationAction, _super);
  44357. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44358. var _this = _super.call(this, triggerOptions, condition) || this;
  44359. _this.from = from;
  44360. _this.to = to;
  44361. _this.loop = loop;
  44362. _this._target = target;
  44363. return _this;
  44364. }
  44365. PlayAnimationAction.prototype._prepare = function () {
  44366. };
  44367. PlayAnimationAction.prototype.execute = function () {
  44368. var scene = this._actionManager.getScene();
  44369. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44370. };
  44371. PlayAnimationAction.prototype.serialize = function (parent) {
  44372. return _super.prototype._serialize.call(this, {
  44373. name: "PlayAnimationAction",
  44374. properties: [
  44375. BABYLON.Action._GetTargetProperty(this._target),
  44376. { name: "from", value: String(this.from) },
  44377. { name: "to", value: String(this.to) },
  44378. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44379. ]
  44380. }, parent);
  44381. };
  44382. return PlayAnimationAction;
  44383. }(BABYLON.Action));
  44384. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44385. var StopAnimationAction = (function (_super) {
  44386. __extends(StopAnimationAction, _super);
  44387. function StopAnimationAction(triggerOptions, target, condition) {
  44388. var _this = _super.call(this, triggerOptions, condition) || this;
  44389. _this._target = target;
  44390. return _this;
  44391. }
  44392. StopAnimationAction.prototype._prepare = function () {
  44393. };
  44394. StopAnimationAction.prototype.execute = function () {
  44395. var scene = this._actionManager.getScene();
  44396. scene.stopAnimation(this._target);
  44397. };
  44398. StopAnimationAction.prototype.serialize = function (parent) {
  44399. return _super.prototype._serialize.call(this, {
  44400. name: "StopAnimationAction",
  44401. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44402. }, parent);
  44403. };
  44404. return StopAnimationAction;
  44405. }(BABYLON.Action));
  44406. BABYLON.StopAnimationAction = StopAnimationAction;
  44407. var DoNothingAction = (function (_super) {
  44408. __extends(DoNothingAction, _super);
  44409. function DoNothingAction(triggerOptions, condition) {
  44410. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44411. return _super.call(this, triggerOptions, condition) || this;
  44412. }
  44413. DoNothingAction.prototype.execute = function () {
  44414. };
  44415. DoNothingAction.prototype.serialize = function (parent) {
  44416. return _super.prototype._serialize.call(this, {
  44417. name: "DoNothingAction",
  44418. properties: []
  44419. }, parent);
  44420. };
  44421. return DoNothingAction;
  44422. }(BABYLON.Action));
  44423. BABYLON.DoNothingAction = DoNothingAction;
  44424. var CombineAction = (function (_super) {
  44425. __extends(CombineAction, _super);
  44426. function CombineAction(triggerOptions, children, condition) {
  44427. var _this = _super.call(this, triggerOptions, condition) || this;
  44428. _this.children = children;
  44429. return _this;
  44430. }
  44431. CombineAction.prototype._prepare = function () {
  44432. for (var index = 0; index < this.children.length; index++) {
  44433. this.children[index]._actionManager = this._actionManager;
  44434. this.children[index]._prepare();
  44435. }
  44436. };
  44437. CombineAction.prototype.execute = function (evt) {
  44438. for (var index = 0; index < this.children.length; index++) {
  44439. this.children[index].execute(evt);
  44440. }
  44441. };
  44442. CombineAction.prototype.serialize = function (parent) {
  44443. var serializationObject = _super.prototype._serialize.call(this, {
  44444. name: "CombineAction",
  44445. properties: [],
  44446. combine: []
  44447. }, parent);
  44448. for (var i = 0; i < this.children.length; i++) {
  44449. serializationObject.combine.push(this.children[i].serialize(null));
  44450. }
  44451. return serializationObject;
  44452. };
  44453. return CombineAction;
  44454. }(BABYLON.Action));
  44455. BABYLON.CombineAction = CombineAction;
  44456. var ExecuteCodeAction = (function (_super) {
  44457. __extends(ExecuteCodeAction, _super);
  44458. function ExecuteCodeAction(triggerOptions, func, condition) {
  44459. var _this = _super.call(this, triggerOptions, condition) || this;
  44460. _this.func = func;
  44461. return _this;
  44462. }
  44463. ExecuteCodeAction.prototype.execute = function (evt) {
  44464. this.func(evt);
  44465. };
  44466. return ExecuteCodeAction;
  44467. }(BABYLON.Action));
  44468. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44469. var SetParentAction = (function (_super) {
  44470. __extends(SetParentAction, _super);
  44471. function SetParentAction(triggerOptions, target, parent, condition) {
  44472. var _this = _super.call(this, triggerOptions, condition) || this;
  44473. _this._target = target;
  44474. _this._parent = parent;
  44475. return _this;
  44476. }
  44477. SetParentAction.prototype._prepare = function () {
  44478. };
  44479. SetParentAction.prototype.execute = function () {
  44480. if (this._target.parent === this._parent) {
  44481. return;
  44482. }
  44483. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44484. invertParentWorldMatrix.invert();
  44485. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44486. this._target.parent = this._parent;
  44487. };
  44488. SetParentAction.prototype.serialize = function (parent) {
  44489. return _super.prototype._serialize.call(this, {
  44490. name: "SetParentAction",
  44491. properties: [
  44492. BABYLON.Action._GetTargetProperty(this._target),
  44493. BABYLON.Action._GetTargetProperty(this._parent),
  44494. ]
  44495. }, parent);
  44496. };
  44497. return SetParentAction;
  44498. }(BABYLON.Action));
  44499. BABYLON.SetParentAction = SetParentAction;
  44500. var PlaySoundAction = (function (_super) {
  44501. __extends(PlaySoundAction, _super);
  44502. function PlaySoundAction(triggerOptions, sound, condition) {
  44503. var _this = _super.call(this, triggerOptions, condition) || this;
  44504. _this._sound = sound;
  44505. return _this;
  44506. }
  44507. PlaySoundAction.prototype._prepare = function () {
  44508. };
  44509. PlaySoundAction.prototype.execute = function () {
  44510. if (this._sound !== undefined)
  44511. this._sound.play();
  44512. };
  44513. PlaySoundAction.prototype.serialize = function (parent) {
  44514. return _super.prototype._serialize.call(this, {
  44515. name: "PlaySoundAction",
  44516. properties: [{ name: "sound", value: this._sound.name }]
  44517. }, parent);
  44518. };
  44519. return PlaySoundAction;
  44520. }(BABYLON.Action));
  44521. BABYLON.PlaySoundAction = PlaySoundAction;
  44522. var StopSoundAction = (function (_super) {
  44523. __extends(StopSoundAction, _super);
  44524. function StopSoundAction(triggerOptions, sound, condition) {
  44525. var _this = _super.call(this, triggerOptions, condition) || this;
  44526. _this._sound = sound;
  44527. return _this;
  44528. }
  44529. StopSoundAction.prototype._prepare = function () {
  44530. };
  44531. StopSoundAction.prototype.execute = function () {
  44532. if (this._sound !== undefined)
  44533. this._sound.stop();
  44534. };
  44535. StopSoundAction.prototype.serialize = function (parent) {
  44536. return _super.prototype._serialize.call(this, {
  44537. name: "StopSoundAction",
  44538. properties: [{ name: "sound", value: this._sound.name }]
  44539. }, parent);
  44540. };
  44541. return StopSoundAction;
  44542. }(BABYLON.Action));
  44543. BABYLON.StopSoundAction = StopSoundAction;
  44544. })(BABYLON || (BABYLON = {}));
  44545. //# sourceMappingURL=babylon.directActions.js.map
  44546. var BABYLON;
  44547. (function (BABYLON) {
  44548. var Debug;
  44549. (function (Debug) {
  44550. /**
  44551. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44552. */
  44553. var SkeletonViewer = (function () {
  44554. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44555. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44556. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44557. this.skeleton = skeleton;
  44558. this.mesh = mesh;
  44559. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44560. this.renderingGroupId = renderingGroupId;
  44561. this.color = BABYLON.Color3.White();
  44562. this._debugLines = [];
  44563. this._isEnabled = false;
  44564. this._scene = scene;
  44565. this.update();
  44566. this._renderFunction = this.update.bind(this);
  44567. }
  44568. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44569. get: function () {
  44570. return this._isEnabled;
  44571. },
  44572. set: function (value) {
  44573. if (this._isEnabled === value) {
  44574. return;
  44575. }
  44576. this._isEnabled = value;
  44577. if (value) {
  44578. this._scene.registerBeforeRender(this._renderFunction);
  44579. }
  44580. else {
  44581. this._scene.unregisterBeforeRender(this._renderFunction);
  44582. }
  44583. },
  44584. enumerable: true,
  44585. configurable: true
  44586. });
  44587. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44588. if (x === void 0) { x = 0; }
  44589. if (y === void 0) { y = 0; }
  44590. if (z === void 0) { z = 0; }
  44591. var tmat = BABYLON.Tmp.Matrix[0];
  44592. var parentBone = bone.getParent();
  44593. tmat.copyFrom(bone.getLocalMatrix());
  44594. if (x !== 0 || y !== 0 || z !== 0) {
  44595. var tmat2 = BABYLON.Tmp.Matrix[1];
  44596. BABYLON.Matrix.IdentityToRef(tmat2);
  44597. tmat2.m[12] = x;
  44598. tmat2.m[13] = y;
  44599. tmat2.m[14] = z;
  44600. tmat2.multiplyToRef(tmat, tmat);
  44601. }
  44602. if (parentBone) {
  44603. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44604. }
  44605. tmat.multiplyToRef(meshMat, tmat);
  44606. position.x = tmat.m[12];
  44607. position.y = tmat.m[13];
  44608. position.z = tmat.m[14];
  44609. };
  44610. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44611. var len = bones.length;
  44612. var meshPos = this.mesh.position;
  44613. for (var i = 0; i < len; i++) {
  44614. var bone = bones[i];
  44615. var points = this._debugLines[i];
  44616. if (!points) {
  44617. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44618. this._debugLines[i] = points;
  44619. }
  44620. this._getBonePosition(points[0], bone, meshMat);
  44621. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44622. points[0].subtractInPlace(meshPos);
  44623. points[1].subtractInPlace(meshPos);
  44624. }
  44625. };
  44626. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44627. var len = bones.length;
  44628. var boneNum = 0;
  44629. var meshPos = this.mesh.position;
  44630. for (var i = len - 1; i >= 0; i--) {
  44631. var childBone = bones[i];
  44632. var parentBone = childBone.getParent();
  44633. if (!parentBone) {
  44634. continue;
  44635. }
  44636. var points = this._debugLines[boneNum];
  44637. if (!points) {
  44638. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44639. this._debugLines[boneNum] = points;
  44640. }
  44641. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  44642. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  44643. points[0].subtractInPlace(meshPos);
  44644. points[1].subtractInPlace(meshPos);
  44645. boneNum++;
  44646. }
  44647. };
  44648. SkeletonViewer.prototype.update = function () {
  44649. if (this.autoUpdateBonesMatrices) {
  44650. this.skeleton.computeAbsoluteTransforms();
  44651. }
  44652. if (this.skeleton.bones[0].length === undefined) {
  44653. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44654. }
  44655. else {
  44656. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44657. }
  44658. if (!this._debugMesh) {
  44659. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44660. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44661. }
  44662. else {
  44663. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44664. }
  44665. this._debugMesh.position.copyFrom(this.mesh.position);
  44666. this._debugMesh.color = this.color;
  44667. };
  44668. SkeletonViewer.prototype.dispose = function () {
  44669. if (this._debugMesh) {
  44670. this.isEnabled = false;
  44671. this._debugMesh.dispose();
  44672. this._debugMesh = null;
  44673. }
  44674. };
  44675. return SkeletonViewer;
  44676. }());
  44677. Debug.SkeletonViewer = SkeletonViewer;
  44678. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44679. })(BABYLON || (BABYLON = {}));
  44680. //# sourceMappingURL=babylon.skeletonViewer.js.map
  44681. var BABYLON;
  44682. (function (BABYLON) {
  44683. var Debug;
  44684. (function (Debug) {
  44685. var AxesViewer = (function () {
  44686. function AxesViewer(scene, scaleLines) {
  44687. if (scaleLines === void 0) { scaleLines = 1; }
  44688. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44689. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44690. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44691. this.scaleLines = 1;
  44692. this.scaleLines = scaleLines;
  44693. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  44694. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  44695. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  44696. this._xmesh.renderingGroupId = 2;
  44697. this._ymesh.renderingGroupId = 2;
  44698. this._zmesh.renderingGroupId = 2;
  44699. this._xmesh.material.checkReadyOnlyOnce = true;
  44700. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  44701. this._ymesh.material.checkReadyOnlyOnce = true;
  44702. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  44703. this._zmesh.material.checkReadyOnlyOnce = true;
  44704. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  44705. this.scene = scene;
  44706. }
  44707. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  44708. var scaleLines = this.scaleLines;
  44709. this._xmesh.position.copyFrom(position);
  44710. this._ymesh.position.copyFrom(position);
  44711. this._zmesh.position.copyFrom(position);
  44712. var point2 = this._xline[1];
  44713. point2.x = xaxis.x * scaleLines;
  44714. point2.y = xaxis.y * scaleLines;
  44715. point2.z = xaxis.z * scaleLines;
  44716. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  44717. point2 = this._yline[1];
  44718. point2.x = yaxis.x * scaleLines;
  44719. point2.y = yaxis.y * scaleLines;
  44720. point2.z = yaxis.z * scaleLines;
  44721. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  44722. point2 = this._zline[1];
  44723. point2.x = zaxis.x * scaleLines;
  44724. point2.y = zaxis.y * scaleLines;
  44725. point2.z = zaxis.z * scaleLines;
  44726. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  44727. };
  44728. AxesViewer.prototype.dispose = function () {
  44729. if (this._xmesh) {
  44730. this._xmesh.dispose();
  44731. this._ymesh.dispose();
  44732. this._zmesh.dispose();
  44733. this._xmesh = null;
  44734. this._ymesh = null;
  44735. this._zmesh = null;
  44736. this._xline = null;
  44737. this._yline = null;
  44738. this._zline = null;
  44739. this.scene = null;
  44740. }
  44741. };
  44742. return AxesViewer;
  44743. }());
  44744. Debug.AxesViewer = AxesViewer;
  44745. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44746. })(BABYLON || (BABYLON = {}));
  44747. //# sourceMappingURL=babylon.axesViewer.js.map
  44748. var BABYLON;
  44749. (function (BABYLON) {
  44750. var Debug;
  44751. (function (Debug) {
  44752. var BoneAxesViewer = (function (_super) {
  44753. __extends(BoneAxesViewer, _super);
  44754. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  44755. if (scaleLines === void 0) { scaleLines = 1; }
  44756. var _this = _super.call(this, scene, scaleLines) || this;
  44757. _this.pos = BABYLON.Vector3.Zero();
  44758. _this.xaxis = BABYLON.Vector3.Zero();
  44759. _this.yaxis = BABYLON.Vector3.Zero();
  44760. _this.zaxis = BABYLON.Vector3.Zero();
  44761. _this.mesh = mesh;
  44762. _this.bone = bone;
  44763. return _this;
  44764. }
  44765. BoneAxesViewer.prototype.update = function () {
  44766. var bone = this.bone;
  44767. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  44768. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  44769. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  44770. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  44771. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  44772. };
  44773. BoneAxesViewer.prototype.dispose = function () {
  44774. if (this.pos) {
  44775. this.pos = null;
  44776. this.xaxis = null;
  44777. this.yaxis = null;
  44778. this.zaxis = null;
  44779. this.mesh = null;
  44780. this.bone = null;
  44781. _super.prototype.dispose.call(this);
  44782. }
  44783. };
  44784. return BoneAxesViewer;
  44785. }(Debug.AxesViewer));
  44786. Debug.BoneAxesViewer = BoneAxesViewer;
  44787. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44788. })(BABYLON || (BABYLON = {}));
  44789. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  44790. var BABYLON;
  44791. (function (BABYLON) {
  44792. var RayHelper = (function () {
  44793. function RayHelper(ray) {
  44794. this.ray = ray;
  44795. }
  44796. RayHelper.CreateAndShow = function (ray, scene, color) {
  44797. var helper = new RayHelper(ray);
  44798. helper.show(scene, color);
  44799. return helper;
  44800. };
  44801. RayHelper.prototype.show = function (scene, color) {
  44802. if (!this._renderFunction) {
  44803. var ray = this.ray;
  44804. this._renderFunction = this._render.bind(this);
  44805. this._scene = scene;
  44806. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  44807. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  44808. this._scene.registerBeforeRender(this._renderFunction);
  44809. }
  44810. if (color) {
  44811. this._renderLine.color.copyFrom(color);
  44812. }
  44813. };
  44814. RayHelper.prototype.hide = function () {
  44815. if (this._renderFunction) {
  44816. this._scene.unregisterBeforeRender(this._renderFunction);
  44817. this._scene = null;
  44818. this._renderFunction = null;
  44819. this._renderLine.dispose();
  44820. this._renderLine = null;
  44821. this._renderPoints = null;
  44822. }
  44823. };
  44824. RayHelper.prototype._render = function () {
  44825. var ray = this.ray;
  44826. var point = this._renderPoints[1];
  44827. var len = Math.min(ray.length, 1000000);
  44828. point.copyFrom(ray.direction);
  44829. point.scaleInPlace(len);
  44830. point.addInPlace(ray.origin);
  44831. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  44832. };
  44833. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  44834. this._attachedToMesh = mesh;
  44835. var ray = this.ray;
  44836. if (!ray.direction) {
  44837. ray.direction = BABYLON.Vector3.Zero();
  44838. }
  44839. if (!ray.origin) {
  44840. ray.origin = BABYLON.Vector3.Zero();
  44841. }
  44842. if (length) {
  44843. ray.length = length;
  44844. }
  44845. if (!meshSpaceOrigin) {
  44846. meshSpaceOrigin = BABYLON.Vector3.Zero();
  44847. }
  44848. if (!meshSpaceDirection) {
  44849. // -1 so that this will work with Mesh.lookAt
  44850. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  44851. }
  44852. if (!this._meshSpaceDirection) {
  44853. this._meshSpaceDirection = meshSpaceDirection.clone();
  44854. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  44855. }
  44856. else {
  44857. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  44858. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  44859. }
  44860. if (!this._updateToMeshFunction) {
  44861. this._updateToMeshFunction = this._updateToMesh.bind(this);
  44862. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  44863. }
  44864. this._updateToMesh();
  44865. };
  44866. RayHelper.prototype.detachFromMesh = function () {
  44867. if (this._attachedToMesh) {
  44868. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  44869. this._attachedToMesh = null;
  44870. this._updateToMeshFunction = null;
  44871. }
  44872. };
  44873. RayHelper.prototype._updateToMesh = function () {
  44874. var ray = this.ray;
  44875. if (this._attachedToMesh._isDisposed) {
  44876. this.detachFromMesh();
  44877. return;
  44878. }
  44879. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  44880. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  44881. };
  44882. RayHelper.prototype.dispose = function () {
  44883. this.hide();
  44884. this.detachFromMesh();
  44885. this.ray = null;
  44886. };
  44887. return RayHelper;
  44888. }());
  44889. BABYLON.RayHelper = RayHelper;
  44890. })(BABYLON || (BABYLON = {}));
  44891. //# sourceMappingURL=babylon.rayHelper.js.map
  44892. var BABYLON;
  44893. (function (BABYLON) {
  44894. var DebugLayer = (function () {
  44895. function DebugLayer(scene) {
  44896. this._scene = scene;
  44897. }
  44898. /** Creates the inspector window. */
  44899. DebugLayer.prototype._createInspector = function (config) {
  44900. if (config === void 0) { config = {}; }
  44901. var popup = config.popup || false;
  44902. var initialTab = config.initialTab || 0;
  44903. var parentElement = config.parentElement || null;
  44904. if (!this._inspector) {
  44905. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  44906. } // else nothing to do,; instance is already existing
  44907. };
  44908. DebugLayer.prototype.isVisible = function () {
  44909. if (!this._inspector) {
  44910. return false;
  44911. }
  44912. return true;
  44913. };
  44914. DebugLayer.prototype.hide = function () {
  44915. if (this._inspector) {
  44916. try {
  44917. this._inspector.dispose();
  44918. }
  44919. catch (e) {
  44920. // If the inspector has been removed directly from the inspector tool
  44921. }
  44922. this._inspector = null;
  44923. }
  44924. };
  44925. DebugLayer.prototype.show = function (config) {
  44926. if (config === void 0) { config = {}; }
  44927. if (typeof INSPECTOR == 'undefined') {
  44928. // Load inspector and add it to the DOM
  44929. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  44930. }
  44931. else {
  44932. // Otherwise creates the inspector
  44933. this._createInspector(config);
  44934. }
  44935. };
  44936. return DebugLayer;
  44937. }());
  44938. // Get protocol used - http or https
  44939. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  44940. BABYLON.DebugLayer = DebugLayer;
  44941. })(BABYLON || (BABYLON = {}));
  44942. //# sourceMappingURL=babylon.debugLayer.js.map
  44943. var BABYLON;
  44944. (function (BABYLON) {
  44945. var Debug;
  44946. (function (Debug) {
  44947. var PhysicsViewer = (function () {
  44948. function PhysicsViewer(scene) {
  44949. this._impostors = [];
  44950. this._meshes = [];
  44951. this._numMeshes = 0;
  44952. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44953. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  44954. }
  44955. PhysicsViewer.prototype._updateDebugMeshes = function () {
  44956. var plugin = this._physicsEnginePlugin;
  44957. for (var i = 0; i < this._numMeshes; i++) {
  44958. if (this._impostors[i].isDisposed) {
  44959. this.hideImpostor(this._impostors[i--]);
  44960. }
  44961. else {
  44962. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  44963. }
  44964. }
  44965. };
  44966. PhysicsViewer.prototype.showImpostor = function (impostor) {
  44967. for (var i = 0; i < this._numMeshes; i++) {
  44968. if (this._impostors[i] == impostor) {
  44969. return;
  44970. }
  44971. }
  44972. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  44973. if (debugMesh) {
  44974. this._impostors[this._numMeshes] = impostor;
  44975. this._meshes[this._numMeshes] = debugMesh;
  44976. if (this._numMeshes === 0) {
  44977. this._renderFunction = this._updateDebugMeshes.bind(this);
  44978. this._scene.registerBeforeRender(this._renderFunction);
  44979. }
  44980. this._numMeshes++;
  44981. }
  44982. };
  44983. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  44984. var removed = false;
  44985. for (var i = 0; i < this._numMeshes; i++) {
  44986. if (this._impostors[i] == impostor) {
  44987. this._scene.removeMesh(this._meshes[i]);
  44988. this._meshes[i].dispose();
  44989. this._numMeshes--;
  44990. if (this._numMeshes > 0) {
  44991. this._meshes[i] = this._meshes[this._numMeshes];
  44992. this._impostors[i] = this._impostors[this._numMeshes];
  44993. this._meshes[this._numMeshes] = null;
  44994. this._impostors[this._numMeshes] = null;
  44995. }
  44996. else {
  44997. this._meshes[0] = null;
  44998. this._impostors[0] = null;
  44999. }
  45000. removed = true;
  45001. break;
  45002. }
  45003. }
  45004. if (removed && this._numMeshes === 0) {
  45005. this._scene.unregisterBeforeRender(this._renderFunction);
  45006. }
  45007. };
  45008. PhysicsViewer.prototype.dispose = function () {
  45009. for (var i = 0; i < this._numMeshes; i++) {
  45010. this.hideImpostor(this._impostors[i]);
  45011. }
  45012. this._impostors.length = 0;
  45013. this._scene = null;
  45014. this._physicsEnginePlugin = null;
  45015. };
  45016. return PhysicsViewer;
  45017. }());
  45018. Debug.PhysicsViewer = PhysicsViewer;
  45019. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45020. })(BABYLON || (BABYLON = {}));
  45021. //# sourceMappingURL=babylon.physicsViewer.js.map
  45022. var BABYLON;
  45023. (function (BABYLON) {
  45024. var BoundingBoxRenderer = (function () {
  45025. function BoundingBoxRenderer(scene) {
  45026. this.frontColor = new BABYLON.Color3(1, 1, 1);
  45027. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  45028. this.showBackLines = true;
  45029. this.renderList = new BABYLON.SmartArray(32);
  45030. this._vertexBuffers = {};
  45031. this._scene = scene;
  45032. }
  45033. BoundingBoxRenderer.prototype._prepareRessources = function () {
  45034. if (this._colorShader) {
  45035. return;
  45036. }
  45037. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  45038. attributes: [BABYLON.VertexBuffer.PositionKind],
  45039. uniforms: ["world", "viewProjection", "color"]
  45040. });
  45041. var engine = this._scene.getEngine();
  45042. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  45043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  45044. 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]);
  45045. };
  45046. BoundingBoxRenderer.prototype.reset = function () {
  45047. this.renderList.reset();
  45048. };
  45049. BoundingBoxRenderer.prototype.render = function () {
  45050. if (this.renderList.length === 0) {
  45051. return;
  45052. }
  45053. this._prepareRessources();
  45054. if (!this._colorShader.isReady()) {
  45055. return;
  45056. }
  45057. var engine = this._scene.getEngine();
  45058. engine.setDepthWrite(false);
  45059. this._colorShader._preBind();
  45060. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  45061. var boundingBox = this.renderList.data[boundingBoxIndex];
  45062. var min = boundingBox.minimum;
  45063. var max = boundingBox.maximum;
  45064. var diff = max.subtract(min);
  45065. var median = min.add(diff.scale(0.5));
  45066. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  45067. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  45068. .multiply(boundingBox.getWorldMatrix());
  45069. // VBOs
  45070. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  45071. if (this.showBackLines) {
  45072. // Back
  45073. engine.setDepthFunctionToGreaterOrEqual();
  45074. this._scene.resetCachedMaterial();
  45075. this._colorShader.setColor4("color", this.backColor.toColor4());
  45076. this._colorShader.bind(worldMatrix);
  45077. // Draw order
  45078. engine.draw(false, 0, 24);
  45079. }
  45080. // Front
  45081. engine.setDepthFunctionToLess();
  45082. this._scene.resetCachedMaterial();
  45083. this._colorShader.setColor4("color", this.frontColor.toColor4());
  45084. this._colorShader.bind(worldMatrix);
  45085. // Draw order
  45086. engine.draw(false, 0, 24);
  45087. }
  45088. this._colorShader.unbind();
  45089. engine.setDepthFunctionToLessOrEqual();
  45090. engine.setDepthWrite(true);
  45091. };
  45092. BoundingBoxRenderer.prototype.dispose = function () {
  45093. if (!this._colorShader) {
  45094. return;
  45095. }
  45096. this.renderList.dispose();
  45097. this._colorShader.dispose();
  45098. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45099. if (buffer) {
  45100. buffer.dispose();
  45101. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45102. }
  45103. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45104. };
  45105. return BoundingBoxRenderer;
  45106. }());
  45107. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  45108. })(BABYLON || (BABYLON = {}));
  45109. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  45110. var BABYLON;
  45111. (function (BABYLON) {
  45112. var TextureTools = (function () {
  45113. function TextureTools() {
  45114. }
  45115. /**
  45116. * Uses the GPU to create a copy texture rescaled at a given size
  45117. * @param texture Texture to copy from
  45118. * @param width Desired width
  45119. * @param height Desired height
  45120. * @return Generated texture
  45121. */
  45122. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  45123. if (useBilinearMode === void 0) { useBilinearMode = true; }
  45124. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  45125. var scene = texture.getScene();
  45126. var engine = scene.getEngine();
  45127. rtt.wrapU = texture.wrapU;
  45128. rtt.wrapV = texture.wrapV;
  45129. rtt.uOffset = texture.uOffset;
  45130. rtt.vOffset = texture.vOffset;
  45131. rtt.uScale = texture.uScale;
  45132. rtt.vScale = texture.vScale;
  45133. rtt.uAng = texture.uAng;
  45134. rtt.vAng = texture.vAng;
  45135. rtt.wAng = texture.wAng;
  45136. rtt.coordinatesIndex = texture.coordinatesIndex;
  45137. rtt.level = texture.level;
  45138. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  45139. rtt._texture.isReady = false;
  45140. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45141. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45142. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45143. passPostProcess.getEffect().executeWhenCompiled(function () {
  45144. passPostProcess.onApply = function (effect) {
  45145. effect.setTexture("textureSampler", texture);
  45146. };
  45147. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  45148. engine.unBindFramebuffer(rtt.getInternalTexture());
  45149. rtt.disposeFramebufferObjects();
  45150. passPostProcess.dispose();
  45151. rtt._texture.isReady = true;
  45152. });
  45153. return rtt;
  45154. };
  45155. return TextureTools;
  45156. }());
  45157. BABYLON.TextureTools = TextureTools;
  45158. })(BABYLON || (BABYLON = {}));
  45159. //# sourceMappingURL=babylon.textureTools.js.map
  45160. var BABYLON;
  45161. (function (BABYLON) {
  45162. var Internals;
  45163. (function (Internals) {
  45164. var FileFaceOrientation = (function () {
  45165. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45166. this.name = name;
  45167. this.worldAxisForNormal = worldAxisForNormal;
  45168. this.worldAxisForFileX = worldAxisForFileX;
  45169. this.worldAxisForFileY = worldAxisForFileY;
  45170. }
  45171. return FileFaceOrientation;
  45172. }());
  45173. ;
  45174. /**
  45175. * Helper class dealing with the extraction of spherical polynomial dataArray
  45176. * from a cube map.
  45177. */
  45178. var CubeMapToSphericalPolynomialTools = (function () {
  45179. function CubeMapToSphericalPolynomialTools() {
  45180. }
  45181. /**
  45182. * Converts a cubemap to the according Spherical Polynomial data.
  45183. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45184. *
  45185. * @param cubeInfo The Cube map to extract the information from.
  45186. * @return The Spherical Polynomial data.
  45187. */
  45188. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45189. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45190. var totalSolidAngle = 0.0;
  45191. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45192. var du = 2.0 / cubeInfo.size;
  45193. var dv = du;
  45194. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45195. var minUV = du * 0.5 - 1.0;
  45196. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45197. var fileFace = this.FileFaces[faceIndex];
  45198. var dataArray = cubeInfo[fileFace.name];
  45199. var v = minUV;
  45200. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45201. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45202. // Because SP is still linear, so summation is fine in that basis.
  45203. for (var y = 0; y < cubeInfo.size; y++) {
  45204. var u = minUV;
  45205. for (var x = 0; x < cubeInfo.size; x++) {
  45206. // World direction (not normalised)
  45207. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45208. worldDirection.normalize();
  45209. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45210. if (1) {
  45211. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  45212. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  45213. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  45214. var color = new BABYLON.Color3(r, g, b);
  45215. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45216. }
  45217. else {
  45218. if (faceIndex == 0) {
  45219. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45220. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45221. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45222. }
  45223. else if (faceIndex == 1) {
  45224. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45225. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45226. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45227. }
  45228. else if (faceIndex == 2) {
  45229. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45230. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45231. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45232. }
  45233. else if (faceIndex == 3) {
  45234. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45235. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45236. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45237. }
  45238. else if (faceIndex == 4) {
  45239. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45240. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45241. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45242. }
  45243. else if (faceIndex == 5) {
  45244. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45245. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45246. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45247. }
  45248. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  45249. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45250. }
  45251. totalSolidAngle += deltaSolidAngle;
  45252. u += du;
  45253. }
  45254. v += dv;
  45255. }
  45256. }
  45257. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  45258. var correction = correctSolidAngle / totalSolidAngle;
  45259. sphericalHarmonics.scale(correction);
  45260. // Additionally scale by pi -- audit needed
  45261. sphericalHarmonics.scale(1.0 / Math.PI);
  45262. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  45263. };
  45264. return CubeMapToSphericalPolynomialTools;
  45265. }());
  45266. CubeMapToSphericalPolynomialTools.FileFaces = [
  45267. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45268. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45269. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45270. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45271. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45272. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45273. ];
  45274. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45275. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45276. })(BABYLON || (BABYLON = {}));
  45277. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45278. var BABYLON;
  45279. (function (BABYLON) {
  45280. var Internals;
  45281. (function (Internals) {
  45282. /**
  45283. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  45284. */
  45285. var PanoramaToCubeMapTools = (function () {
  45286. function PanoramaToCubeMapTools() {
  45287. }
  45288. /**
  45289. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  45290. *
  45291. * @param float32Array The source data.
  45292. * @param inputWidth The width of the input panorama.
  45293. * @param inputhHeight The height of the input panorama.
  45294. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  45295. * @return The cubemap data
  45296. */
  45297. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  45298. if (!float32Array) {
  45299. throw "ConvertPanoramaToCubemap: input cannot be null";
  45300. }
  45301. if (float32Array.length != inputWidth * inputHeight * 3) {
  45302. throw "ConvertPanoramaToCubemap: input size is wrong";
  45303. }
  45304. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  45305. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  45306. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  45307. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  45308. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  45309. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  45310. return {
  45311. front: textureFront,
  45312. back: textureBack,
  45313. left: textureLeft,
  45314. right: textureRight,
  45315. up: textureUp,
  45316. down: textureDown,
  45317. size: size
  45318. };
  45319. };
  45320. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  45321. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  45322. var textureArray = new Float32Array(buffer);
  45323. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  45324. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  45325. var dy = 1 / texSize;
  45326. var fy = 0;
  45327. for (var y = 0; y < texSize; y++) {
  45328. var xv1 = faceData[0];
  45329. var xv2 = faceData[2];
  45330. for (var x = 0; x < texSize; x++) {
  45331. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  45332. v.normalize();
  45333. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  45334. // 3 channels per pixels
  45335. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  45336. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  45337. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  45338. xv1 = xv1.add(rotDX1);
  45339. xv2 = xv2.add(rotDX2);
  45340. }
  45341. fy += dy;
  45342. }
  45343. return textureArray;
  45344. };
  45345. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  45346. var theta = Math.atan2(vDir.z, vDir.x);
  45347. var phi = Math.acos(vDir.y);
  45348. while (theta < -Math.PI)
  45349. theta += 2 * Math.PI;
  45350. while (theta > Math.PI)
  45351. theta -= 2 * Math.PI;
  45352. var dx = theta / Math.PI;
  45353. var dy = phi / Math.PI;
  45354. // recenter.
  45355. dx = dx * 0.5 + 0.5;
  45356. var px = Math.round(dx * inputWidth);
  45357. if (px < 0)
  45358. px = 0;
  45359. else if (px >= inputWidth)
  45360. px = inputWidth - 1;
  45361. var py = Math.round(dy * inputHeight);
  45362. if (py < 0)
  45363. py = 0;
  45364. else if (py >= inputHeight)
  45365. py = inputHeight - 1;
  45366. var inputY = (inputHeight - py - 1);
  45367. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  45368. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  45369. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  45370. return {
  45371. r: r,
  45372. g: g,
  45373. b: b
  45374. };
  45375. };
  45376. return PanoramaToCubeMapTools;
  45377. }());
  45378. PanoramaToCubeMapTools.FACE_FRONT = [
  45379. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45380. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45381. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45382. new BABYLON.Vector3(1.0, 1.0, -1.0)
  45383. ];
  45384. PanoramaToCubeMapTools.FACE_BACK = [
  45385. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45386. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45387. new BABYLON.Vector3(1.0, 1.0, 1.0),
  45388. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  45389. ];
  45390. PanoramaToCubeMapTools.FACE_RIGHT = [
  45391. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45392. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45393. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45394. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45395. ];
  45396. PanoramaToCubeMapTools.FACE_LEFT = [
  45397. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45398. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45399. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45400. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  45401. ];
  45402. PanoramaToCubeMapTools.FACE_DOWN = [
  45403. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45404. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45405. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45406. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45407. ];
  45408. PanoramaToCubeMapTools.FACE_UP = [
  45409. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45410. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45411. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45412. new BABYLON.Vector3(1.0, -1.0, -1.0)
  45413. ];
  45414. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  45415. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45416. })(BABYLON || (BABYLON = {}));
  45417. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  45418. var BABYLON;
  45419. (function (BABYLON) {
  45420. var Internals;
  45421. (function (Internals) {
  45422. ;
  45423. /**
  45424. * This groups tools to convert HDR texture to native colors array.
  45425. */
  45426. var HDRTools = (function () {
  45427. function HDRTools() {
  45428. }
  45429. HDRTools.Ldexp = function (mantissa, exponent) {
  45430. if (exponent > 1023) {
  45431. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  45432. }
  45433. if (exponent < -1074) {
  45434. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  45435. }
  45436. return mantissa * Math.pow(2, exponent);
  45437. };
  45438. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  45439. if (exponent > 0) {
  45440. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  45441. float32array[index + 0] = red * exponent;
  45442. float32array[index + 1] = green * exponent;
  45443. float32array[index + 2] = blue * exponent;
  45444. }
  45445. else {
  45446. float32array[index + 0] = 0;
  45447. float32array[index + 1] = 0;
  45448. float32array[index + 2] = 0;
  45449. }
  45450. };
  45451. HDRTools.readStringLine = function (uint8array, startIndex) {
  45452. var line = "";
  45453. var character = "";
  45454. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  45455. character = String.fromCharCode(uint8array[i]);
  45456. if (character == "\n") {
  45457. break;
  45458. }
  45459. line += character;
  45460. }
  45461. return line;
  45462. };
  45463. /**
  45464. * Reads header information from an RGBE texture stored in a native array.
  45465. * More information on this format are available here:
  45466. * https://en.wikipedia.org/wiki/RGBE_image_format
  45467. *
  45468. * @param uint8array The binary file stored in native array.
  45469. * @return The header information.
  45470. */
  45471. HDRTools.RGBE_ReadHeader = function (uint8array) {
  45472. var height = 0;
  45473. var width = 0;
  45474. var line = this.readStringLine(uint8array, 0);
  45475. if (line[0] != '#' || line[1] != '?') {
  45476. throw "Bad HDR Format.";
  45477. }
  45478. var endOfHeader = false;
  45479. var findFormat = false;
  45480. var lineIndex = 0;
  45481. do {
  45482. lineIndex += (line.length + 1);
  45483. line = this.readStringLine(uint8array, lineIndex);
  45484. if (line == "FORMAT=32-bit_rle_rgbe") {
  45485. findFormat = true;
  45486. }
  45487. else if (line.length == 0) {
  45488. endOfHeader = true;
  45489. }
  45490. } while (!endOfHeader);
  45491. if (!findFormat) {
  45492. throw "HDR Bad header format, unsupported FORMAT";
  45493. }
  45494. lineIndex += (line.length + 1);
  45495. line = this.readStringLine(uint8array, lineIndex);
  45496. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  45497. var match = sizeRegexp.exec(line);
  45498. // TODO. Support +Y and -X if needed.
  45499. if (match.length < 3) {
  45500. throw "HDR Bad header format, no size";
  45501. }
  45502. width = parseInt(match[2]);
  45503. height = parseInt(match[1]);
  45504. if (width < 8 || width > 0x7fff) {
  45505. throw "HDR Bad header format, unsupported size";
  45506. }
  45507. lineIndex += (line.length + 1);
  45508. return {
  45509. height: height,
  45510. width: width,
  45511. dataPosition: lineIndex
  45512. };
  45513. };
  45514. /**
  45515. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  45516. * This RGBE texture needs to store the information as a panorama.
  45517. *
  45518. * More information on this format are available here:
  45519. * https://en.wikipedia.org/wiki/RGBE_image_format
  45520. *
  45521. * @param buffer The binary file stored in an array buffer.
  45522. * @param size The expected size of the extracted cubemap.
  45523. * @return The Cube Map information.
  45524. */
  45525. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  45526. var uint8array = new Uint8Array(buffer);
  45527. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  45528. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45529. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  45530. return cubeMapData;
  45531. };
  45532. /**
  45533. * Returns the pixels data extracted from an RGBE texture.
  45534. * This pixels will be stored left to right up to down in the R G B order in one array.
  45535. *
  45536. * More information on this format are available here:
  45537. * https://en.wikipedia.org/wiki/RGBE_image_format
  45538. *
  45539. * @param uint8array The binary file stored in an array buffer.
  45540. * @param hdrInfo The header information of the file.
  45541. * @return The pixels data in RGB right to left up to down order.
  45542. */
  45543. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  45544. // Keep for multi format supports.
  45545. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45546. };
  45547. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  45548. var num_scanlines = hdrInfo.height;
  45549. var scanline_width = hdrInfo.width;
  45550. var a, b, c, d, count;
  45551. var dataIndex = hdrInfo.dataPosition;
  45552. var index = 0, endIndex = 0, i = 0;
  45553. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  45554. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  45555. // 3 channels of 4 bytes per pixel in float.
  45556. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  45557. var resultArray = new Float32Array(resultBuffer);
  45558. // read in each successive scanline
  45559. while (num_scanlines > 0) {
  45560. a = uint8array[dataIndex++];
  45561. b = uint8array[dataIndex++];
  45562. c = uint8array[dataIndex++];
  45563. d = uint8array[dataIndex++];
  45564. if (a != 2 || b != 2 || (c & 0x80)) {
  45565. // this file is not run length encoded
  45566. throw "HDR Bad header format, not RLE";
  45567. }
  45568. if (((c << 8) | d) != scanline_width) {
  45569. throw "HDR Bad header format, wrong scan line width";
  45570. }
  45571. index = 0;
  45572. // read each of the four channels for the scanline into the buffer
  45573. for (i = 0; i < 4; i++) {
  45574. endIndex = (i + 1) * scanline_width;
  45575. while (index < endIndex) {
  45576. a = uint8array[dataIndex++];
  45577. b = uint8array[dataIndex++];
  45578. if (a > 128) {
  45579. // a run of the same value
  45580. count = a - 128;
  45581. if ((count == 0) || (count > endIndex - index)) {
  45582. throw "HDR Bad Format, bad scanline data (run)";
  45583. }
  45584. while (count-- > 0) {
  45585. scanLineArray[index++] = b;
  45586. }
  45587. }
  45588. else {
  45589. // a non-run
  45590. count = a;
  45591. if ((count == 0) || (count > endIndex - index)) {
  45592. throw "HDR Bad Format, bad scanline data (non-run)";
  45593. }
  45594. scanLineArray[index++] = b;
  45595. if (--count > 0) {
  45596. for (var j = 0; j < count; j++) {
  45597. scanLineArray[index++] = uint8array[dataIndex++];
  45598. }
  45599. }
  45600. }
  45601. }
  45602. }
  45603. // now convert data from buffer into floats
  45604. for (i = 0; i < scanline_width; i++) {
  45605. a = scanLineArray[i];
  45606. b = scanLineArray[i + scanline_width];
  45607. c = scanLineArray[i + 2 * scanline_width];
  45608. d = scanLineArray[i + 3 * scanline_width];
  45609. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  45610. }
  45611. num_scanlines--;
  45612. }
  45613. return resultArray;
  45614. };
  45615. return HDRTools;
  45616. }());
  45617. Internals.HDRTools = HDRTools;
  45618. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45619. })(BABYLON || (BABYLON = {}));
  45620. //# sourceMappingURL=babylon.hdr.js.map
  45621. //_______________________________________________________________
  45622. // Extracted from CubeMapGen:
  45623. // https://code.google.com/archive/p/cubemapgen/
  45624. //
  45625. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45626. //_______________________________________________________________
  45627. var BABYLON;
  45628. (function (BABYLON) {
  45629. var Internals;
  45630. (function (Internals) {
  45631. /**
  45632. * The bounding box information used during the conversion process.
  45633. */
  45634. var CMGBoundinBox = (function () {
  45635. function CMGBoundinBox() {
  45636. this.min = new BABYLON.Vector3(0, 0, 0);
  45637. this.max = new BABYLON.Vector3(0, 0, 0);
  45638. this.clear();
  45639. }
  45640. CMGBoundinBox.prototype.clear = function () {
  45641. this.min.x = CMGBoundinBox.MAX;
  45642. this.min.y = CMGBoundinBox.MAX;
  45643. this.min.z = CMGBoundinBox.MAX;
  45644. this.max.x = CMGBoundinBox.MIN;
  45645. this.max.y = CMGBoundinBox.MIN;
  45646. this.max.z = CMGBoundinBox.MIN;
  45647. };
  45648. CMGBoundinBox.prototype.augment = function (x, y, z) {
  45649. this.min.x = Math.min(this.min.x, x);
  45650. this.min.y = Math.min(this.min.y, y);
  45651. this.min.z = Math.min(this.min.z, z);
  45652. this.max.x = Math.max(this.max.x, x);
  45653. this.max.y = Math.max(this.max.y, y);
  45654. this.max.z = Math.max(this.max.z, z);
  45655. };
  45656. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  45657. this.min.x = Math.max(this.min.x, x);
  45658. this.min.y = Math.max(this.min.y, y);
  45659. this.min.z = Math.max(this.min.z, z);
  45660. };
  45661. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  45662. this.max.x = Math.min(this.max.x, x);
  45663. this.max.y = Math.min(this.max.y, y);
  45664. this.max.z = Math.min(this.max.z, z);
  45665. };
  45666. CMGBoundinBox.prototype.empty = function () {
  45667. if ((this.min.x > this.max.y) ||
  45668. (this.min.y > this.max.y) ||
  45669. (this.min.z > this.max.y)) {
  45670. return true;
  45671. }
  45672. else {
  45673. return false;
  45674. }
  45675. };
  45676. return CMGBoundinBox;
  45677. }());
  45678. CMGBoundinBox.MAX = Number.MAX_VALUE;
  45679. CMGBoundinBox.MIN = Number.MIN_VALUE;
  45680. /**
  45681. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  45682. * required by the glossinees of a material.
  45683. *
  45684. * This only supports the cosine drop power as well as Warp fixup generation method.
  45685. *
  45686. * This is using the process from CubeMapGen described here:
  45687. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45688. */
  45689. var PMREMGenerator = (function () {
  45690. /**
  45691. * Constructor of the generator.
  45692. *
  45693. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  45694. * @param inputSize The size of the cubemap faces
  45695. * @param outputSize The size of the output cubemap faces
  45696. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  45697. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  45698. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  45699. * @param specularPower The max specular level of the desired cubemap
  45700. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  45701. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  45702. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  45703. */
  45704. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  45705. this.input = input;
  45706. this.inputSize = inputSize;
  45707. this.outputSize = outputSize;
  45708. this.maxNumMipLevels = maxNumMipLevels;
  45709. this.numChannels = numChannels;
  45710. this.isFloat = isFloat;
  45711. this.specularPower = specularPower;
  45712. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  45713. this.excludeBase = excludeBase;
  45714. this.fixup = fixup;
  45715. this._outputSurface = [];
  45716. this._numMipLevels = 0;
  45717. }
  45718. /**
  45719. * Launches the filter process and return the result.
  45720. *
  45721. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  45722. */
  45723. PMREMGenerator.prototype.filterCubeMap = function () {
  45724. // Init cubemap processor
  45725. this.init();
  45726. // Filters the cubemap
  45727. this.filterCubeMapMipChain();
  45728. // Returns the filtered mips.
  45729. return this._outputSurface;
  45730. };
  45731. PMREMGenerator.prototype.init = function () {
  45732. var i;
  45733. var j;
  45734. var mipLevelSize;
  45735. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  45736. if (this.maxNumMipLevels == 0) {
  45737. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  45738. }
  45739. //first miplevel size
  45740. mipLevelSize = this.outputSize;
  45741. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  45742. for (j = 0; j < this.maxNumMipLevels; j++) {
  45743. this._outputSurface.length++;
  45744. this._outputSurface[j] = [];
  45745. //Iterate over faces for output images
  45746. for (i = 0; i < 6; i++) {
  45747. this._outputSurface[j].length++;
  45748. // Initializes a new array for the output.
  45749. if (this.isFloat) {
  45750. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45751. }
  45752. else {
  45753. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45754. }
  45755. }
  45756. //next mip level is half size
  45757. mipLevelSize >>= 1;
  45758. this._numMipLevels++;
  45759. //terminate if mip chain becomes too small
  45760. if (mipLevelSize == 0) {
  45761. this.maxNumMipLevels = j;
  45762. return;
  45763. }
  45764. }
  45765. };
  45766. //--------------------------------------------------------------------------------------
  45767. //Cube map filtering and mip chain generation.
  45768. // the cube map filtereing is specified using a number of parameters:
  45769. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  45770. // indicates the region of the hemisphere to filter over for each tap.
  45771. //
  45772. // Note that the top mip level is also a filtered version of the original input images
  45773. // as well in order to create mip chains for diffuse environment illumination.
  45774. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  45775. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  45776. //
  45777. // Then the mip angle used to genreate the next level of the mip chain from the first level
  45778. // is a_InitialMipAngle
  45779. //
  45780. // The angle for the subsequent levels of the mip chain are specified by their parents
  45781. // filtering angle and a per-level scale and bias
  45782. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  45783. //
  45784. //--------------------------------------------------------------------------------------
  45785. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  45786. // First, take count of the lighting model to modify SpecularPower
  45787. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  45788. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  45789. //Cone angle start (for generating subsequent mip levels)
  45790. var currentSpecularPower = this.specularPower;
  45791. //Build filter lookup tables based on the source miplevel size
  45792. this.precomputeFilterLookupTables(this.inputSize);
  45793. // Note that we need to filter the first level before generating mipmap
  45794. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  45795. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  45796. // TODO : Write a function to copy and scale the base mipmap in output
  45797. // I am just lazy here and just put a high specular power value, and do some if.
  45798. if (this.excludeBase && (levelIndex == 0)) {
  45799. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  45800. currentSpecularPower = 100000.0;
  45801. }
  45802. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  45803. var srcCubeImage = this.input;
  45804. var dstCubeImage = this._outputSurface[levelIndex];
  45805. var dstSize = this.outputSize >> levelIndex;
  45806. // Compute required angle.
  45807. var angle = this.getBaseFilterAngle(currentSpecularPower);
  45808. // filter cube surfaces
  45809. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  45810. // fix seams
  45811. if (this.fixup) {
  45812. this.fixupCubeEdges(dstCubeImage, dstSize);
  45813. }
  45814. // Decrease the specular power to generate the mipmap chain
  45815. // TODO : Use another method for Exclude (see first comment at start of the function
  45816. if (this.excludeBase && (levelIndex == 0)) {
  45817. currentSpecularPower = this.specularPower;
  45818. }
  45819. currentSpecularPower *= this.cosinePowerDropPerMip;
  45820. }
  45821. };
  45822. //--------------------------------------------------------------------------------------
  45823. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  45824. // It allow to optimize the texel to access base on the specular power.
  45825. //--------------------------------------------------------------------------------------
  45826. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  45827. // We want to find the alpha such that:
  45828. // cos(alpha)^cosinePower = epsilon
  45829. // That's: acos(epsilon^(1/cosinePower))
  45830. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  45831. var angle = 180.0;
  45832. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  45833. angle *= 180.0 / Math.PI; // Convert to degree
  45834. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  45835. return angle;
  45836. };
  45837. //--------------------------------------------------------------------------------------
  45838. //Builds the following lookup tables prior to filtering:
  45839. // -normalizer cube map
  45840. // -tap weight lookup table
  45841. //
  45842. //--------------------------------------------------------------------------------------
  45843. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  45844. var srcTexelAngle;
  45845. var iCubeFace;
  45846. //clear pre-existing normalizer cube map
  45847. this._normCubeMap = [];
  45848. //Normalized vectors per cubeface and per-texel solid angle
  45849. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  45850. };
  45851. //--------------------------------------------------------------------------------------
  45852. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  45853. //
  45854. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  45855. //
  45856. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  45857. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  45858. // below
  45859. //--------------------------------------------------------------------------------------
  45860. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  45861. var iCubeFace;
  45862. var u;
  45863. var v;
  45864. //iterate over cube faces
  45865. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  45866. //First three channels for norm cube, and last channel for solid angle
  45867. this._normCubeMap.push(new Float32Array(size * size * 4));
  45868. //fast texture walk, build normalizer cube map
  45869. var facesData = this.input[iCubeFace];
  45870. for (v = 0; v < size; v++) {
  45871. for (u = 0; u < size; u++) {
  45872. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  45873. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  45874. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  45875. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  45876. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  45877. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  45878. }
  45879. }
  45880. }
  45881. };
  45882. //--------------------------------------------------------------------------------------
  45883. // Convert cubemap face texel coordinates and face idx to 3D vector
  45884. // note the U and V coords are integer coords and range from 0 to size-1
  45885. // this routine can be used to generate a normalizer cube map
  45886. //--------------------------------------------------------------------------------------
  45887. // SL BEGIN
  45888. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  45889. var nvcU;
  45890. var nvcV;
  45891. var tempVec;
  45892. // Change from original AMD code
  45893. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  45894. // + 0.5f is for texel center addressing
  45895. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  45896. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  45897. // warp fixup
  45898. if (fixup && size > 1) {
  45899. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  45900. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  45901. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  45902. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  45903. }
  45904. // Get current vector
  45905. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  45906. // U contribution
  45907. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  45908. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  45909. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  45910. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  45911. // V contribution and Sum
  45912. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  45913. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  45914. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  45915. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  45916. //add face axis
  45917. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  45918. PMREMGenerator._vectorTemp.x += faceAxis[0];
  45919. PMREMGenerator._vectorTemp.y += faceAxis[1];
  45920. PMREMGenerator._vectorTemp.z += faceAxis[2];
  45921. //normalize vector
  45922. PMREMGenerator._vectorTemp.normalize();
  45923. return PMREMGenerator._vectorTemp;
  45924. };
  45925. //--------------------------------------------------------------------------------------
  45926. // Convert 3D vector to cubemap face texel coordinates and face idx
  45927. // note the U and V coords are integer coords and range from 0 to size-1
  45928. // this routine can be used to generate a normalizer cube map
  45929. //
  45930. // returns face IDX and texel coords
  45931. //--------------------------------------------------------------------------------------
  45932. // SL BEGIN
  45933. /*
  45934. Mapping Texture Coordinates to Cube Map Faces
  45935. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  45936. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  45937. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  45938. map arrangement in Pixar's RenderMan package.
  45939. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  45940. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  45941. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  45942. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  45943. the major axis direction). The target column in the table below explains how the major axis direction
  45944. maps to the 2D image of a particular cube map target.
  45945. major axis
  45946. direction target sc tc ma
  45947. ---------- --------------------------------- --- --- ---
  45948. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  45949. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  45950. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  45951. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  45952. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  45953. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  45954. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  45955. an updated (s,t) is calculated as follows
  45956. s = ( sc/|ma| + 1 ) / 2
  45957. t = ( tc/|ma| + 1 ) / 2
  45958. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  45959. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  45960. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  45961. */
  45962. // Note this method return U and V in range from 0 to size-1
  45963. // SL END
  45964. // Store the information in vector3 for convenience (faceindex, u, v)
  45965. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  45966. var maxCoord;
  45967. var faceIdx;
  45968. //absolute value 3
  45969. var absX = Math.abs(x);
  45970. var absY = Math.abs(y);
  45971. var absZ = Math.abs(z);
  45972. if (absX >= absY && absX >= absZ) {
  45973. maxCoord = absX;
  45974. if (x >= 0) {
  45975. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  45976. }
  45977. else {
  45978. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  45979. }
  45980. }
  45981. else if (absY >= absX && absY >= absZ) {
  45982. maxCoord = absY;
  45983. if (y >= 0) {
  45984. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  45985. }
  45986. else {
  45987. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  45988. }
  45989. }
  45990. else {
  45991. maxCoord = absZ;
  45992. if (z >= 0) {
  45993. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  45994. }
  45995. else {
  45996. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  45997. }
  45998. }
  45999. //divide through by max coord so face vector lies on cube face
  46000. var scale = 1 / maxCoord;
  46001. x *= scale;
  46002. y *= scale;
  46003. z *= scale;
  46004. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  46005. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  46006. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  46007. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  46008. // Modify original AMD code to return value from 0 to Size - 1
  46009. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  46010. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  46011. PMREMGenerator._vectorTemp.x = faceIdx;
  46012. PMREMGenerator._vectorTemp.y = u;
  46013. PMREMGenerator._vectorTemp.z = v;
  46014. return PMREMGenerator._vectorTemp;
  46015. };
  46016. //--------------------------------------------------------------------------------------
  46017. //Original code from Ignacio CastaÒo
  46018. // This formula is from Manne ÷hrstrˆm's thesis.
  46019. // Take two coordiantes in the range [-1, 1] that define a portion of a
  46020. // cube face and return the area of the projection of that portion on the
  46021. // surface of the sphere.
  46022. //--------------------------------------------------------------------------------------
  46023. PMREMGenerator.prototype.areaElement = function (x, y) {
  46024. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  46025. };
  46026. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  46027. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  46028. // (+ 0.5f is for texel center addressing)
  46029. u = (2.0 * (u + 0.5) / size) - 1.0;
  46030. v = (2.0 * (v + 0.5) / size) - 1.0;
  46031. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  46032. var invResolution = 1.0 / size;
  46033. // U and V are the -1..1 texture coordinate on the current face.
  46034. // Get projected area for this texel
  46035. var x0 = u - invResolution;
  46036. var y0 = v - invResolution;
  46037. var x1 = u + invResolution;
  46038. var y1 = v + invResolution;
  46039. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  46040. return solidAngle;
  46041. };
  46042. //--------------------------------------------------------------------------------------
  46043. //The key to the speed of these filtering routines is to quickly define a per-face
  46044. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  46045. // Later these pixels are selectively processed based on their dot products to see if
  46046. // they reside within the filtering cone.
  46047. //
  46048. //This is done by computing the smallest per-texel angle to get a conservative estimate
  46049. // of the number of texels needed to be covered in width and height order to filter the
  46050. // region. the bounding box for the center taps face is defined first, and if the
  46051. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  46052. // defined next
  46053. //--------------------------------------------------------------------------------------
  46054. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  46055. // note that pixels within these regions may be rejected
  46056. // based on the anlge
  46057. var iCubeFace;
  46058. var u;
  46059. var v;
  46060. // bounding box per face to specify region to process
  46061. var filterExtents = [];
  46062. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46063. filterExtents.push(new CMGBoundinBox());
  46064. }
  46065. // min angle a src texel can cover (in degrees)
  46066. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  46067. // angle about center tap to define filter cone
  46068. // filter angle is 1/2 the cone angle
  46069. var filterAngle = filterConeAngle / 2.0;
  46070. //ensure filter angle is larger than a texel
  46071. if (filterAngle < srcTexelAngle) {
  46072. filterAngle = srcTexelAngle;
  46073. }
  46074. //ensure filter cone is always smaller than the hemisphere
  46075. if (filterAngle > 90.0) {
  46076. filterAngle = 90.0;
  46077. }
  46078. // the maximum number of texels in 1D the filter cone angle will cover
  46079. // used to determine bounding box size for filter extents
  46080. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  46081. // ensure conservative region always covers at least one texel
  46082. if (filterSize < 1) {
  46083. filterSize = 1;
  46084. }
  46085. // dotProdThresh threshold based on cone angle to determine whether or not taps
  46086. // reside within the cone angle
  46087. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  46088. // process required faces
  46089. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46090. //iterate over dst cube map face texel
  46091. for (v = 0; v < dstSize; v++) {
  46092. for (u = 0; u < dstSize; u++) {
  46093. //get center tap direction
  46094. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  46095. //clear old per-face filter extents
  46096. this.clearFilterExtents(filterExtents);
  46097. //define per-face filter extents
  46098. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  46099. //perform filtering of src faces using filter extents
  46100. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  46101. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  46102. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  46103. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  46104. }
  46105. }
  46106. }
  46107. };
  46108. //--------------------------------------------------------------------------------------
  46109. //Clear filter extents for the 6 cube map faces
  46110. //--------------------------------------------------------------------------------------
  46111. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  46112. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  46113. filterExtents[iCubeFaces].clear();
  46114. }
  46115. };
  46116. //--------------------------------------------------------------------------------------
  46117. //Define per-face bounding box filter extents
  46118. //
  46119. // These define conservative texel regions in each of the faces the filter can possibly
  46120. // process. When the pixels in the regions are actually processed, the dot product
  46121. // between the tap vector and the center tap vector is used to determine the weight of
  46122. // the tap and whether or not the tap is within the cone.
  46123. //
  46124. //--------------------------------------------------------------------------------------
  46125. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  46126. //neighboring face and bleed over amount, and width of BBOX for
  46127. // left, right, top, and bottom edges of this face
  46128. var bleedOverAmount = [0, 0, 0, 0];
  46129. var bleedOverBBoxMin = [0, 0, 0, 0];
  46130. var bleedOverBBoxMax = [0, 0, 0, 0];
  46131. var neighborFace;
  46132. var neighborEdge;
  46133. var oppositeFaceIdx;
  46134. //get face idx, and u, v info from center tap dir
  46135. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  46136. var faceIdx = result.x;
  46137. var u = result.y;
  46138. var v = result.z;
  46139. //define bbox size within face
  46140. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  46141. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  46142. filterExtents[faceIdx].clampMin(0, 0, 0);
  46143. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  46144. //u and v extent in face corresponding to center tap
  46145. var minU = filterExtents[faceIdx].min.x;
  46146. var minV = filterExtents[faceIdx].min.y;
  46147. var maxU = filterExtents[faceIdx].max.x;
  46148. var maxV = filterExtents[faceIdx].max.y;
  46149. //bleed over amounts for face across u=0 edge (left)
  46150. bleedOverAmount[0] = (bboxSize - u);
  46151. bleedOverBBoxMin[0] = minV;
  46152. bleedOverBBoxMax[0] = maxV;
  46153. //bleed over amounts for face across u=1 edge (right)
  46154. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  46155. bleedOverBBoxMin[1] = minV;
  46156. bleedOverBBoxMax[1] = maxV;
  46157. //bleed over to face across v=0 edge (up)
  46158. bleedOverAmount[2] = (bboxSize - v);
  46159. bleedOverBBoxMin[2] = minU;
  46160. bleedOverBBoxMax[2] = maxU;
  46161. //bleed over to face across v=1 edge (down)
  46162. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  46163. bleedOverBBoxMin[3] = minU;
  46164. bleedOverBBoxMax[3] = maxU;
  46165. //compute bleed over regions in neighboring faces
  46166. for (var i = 0; i < 4; i++) {
  46167. if (bleedOverAmount[i] > 0) {
  46168. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  46169. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  46170. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  46171. // be flipped: the cases are
  46172. // if a left edge mates with a left or bottom edge on the neighbor
  46173. // if a top edge mates with a top or right edge on the neighbor
  46174. // if a right edge mates with a right or top edge on the neighbor
  46175. // if a bottom edge mates with a bottom or left edge on the neighbor
  46176. //Seeing as the edges are enumerated as follows
  46177. // left =0
  46178. // right =1
  46179. // top =2
  46180. // bottom =3
  46181. //
  46182. // so if the edge enums are the same, or the sum of the enums == 3,
  46183. // the bbox needs to be flipped
  46184. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  46185. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  46186. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  46187. }
  46188. //The way the bounding box is extended onto the neighboring face
  46189. // depends on which edge of neighboring face abuts with this one
  46190. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  46191. case PMREMGenerator.CP_EDGE_LEFT:
  46192. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  46193. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46194. break;
  46195. case PMREMGenerator.CP_EDGE_RIGHT:
  46196. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  46197. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46198. break;
  46199. case PMREMGenerator.CP_EDGE_TOP:
  46200. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  46201. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  46202. break;
  46203. case PMREMGenerator.CP_EDGE_BOTTOM:
  46204. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  46205. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  46206. break;
  46207. }
  46208. //clamp filter extents in non-center tap faces to remain within surface
  46209. filterExtents[neighborFace].clampMin(0, 0, 0);
  46210. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  46211. }
  46212. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  46213. // from the center tap face, then process the opposite face entirely for now.
  46214. //Note that the cases in which this happens, what usually happens is that
  46215. // more than one edge bleeds onto the opposite face, and the bounding box
  46216. // encompasses the entire cube map face.
  46217. if (bleedOverAmount[i] > srcSize) {
  46218. //determine opposite face
  46219. switch (faceIdx) {
  46220. case PMREMGenerator.CP_FACE_X_POS:
  46221. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  46222. break;
  46223. case PMREMGenerator.CP_FACE_X_NEG:
  46224. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  46225. break;
  46226. case PMREMGenerator.CP_FACE_Y_POS:
  46227. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  46228. break;
  46229. case PMREMGenerator.CP_FACE_Y_NEG:
  46230. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  46231. break;
  46232. case PMREMGenerator.CP_FACE_Z_POS:
  46233. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  46234. break;
  46235. case PMREMGenerator.CP_FACE_Z_NEG:
  46236. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  46237. break;
  46238. default:
  46239. break;
  46240. }
  46241. //just encompass entire face for now
  46242. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  46243. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  46244. }
  46245. }
  46246. };
  46247. //--------------------------------------------------------------------------------------
  46248. //ProcessFilterExtents
  46249. // Process bounding box in each cube face
  46250. //
  46251. //--------------------------------------------------------------------------------------
  46252. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  46253. //accumulators are 64-bit floats in order to have the precision needed
  46254. // over a summation of a large number of pixels
  46255. var dstAccum = [0, 0, 0, 0];
  46256. var weightAccum = 0;
  46257. var k = 0;
  46258. var nSrcChannels = this.numChannels;
  46259. // norm cube map and srcCubeMap have same face width
  46260. var faceWidth = srcSize;
  46261. //amount to add to pointer to move to next scanline in images
  46262. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  46263. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  46264. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  46265. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  46266. // iterate over cubefaces
  46267. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  46268. //if bbox is non empty
  46269. if (!filterExtents[iFaceIdx].empty()) {
  46270. var uStart = filterExtents[iFaceIdx].min.x;
  46271. var vStart = filterExtents[iFaceIdx].min.y;
  46272. var uEnd = filterExtents[iFaceIdx].max.x;
  46273. var vEnd = filterExtents[iFaceIdx].max.y;
  46274. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  46275. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  46276. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  46277. for (var v = vStart; v <= vEnd; v++) {
  46278. var normCubeRowWalk = 0;
  46279. var srcCubeRowWalk = 0;
  46280. for (var u = uStart; u <= uEnd; u++) {
  46281. //pointer to direction in cube map associated with texel
  46282. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  46283. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  46284. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  46285. //check dot product to see if texel is within cone
  46286. var tapDotProd = texelVectX * centerTapDir.x +
  46287. texelVectY * centerTapDir.y +
  46288. texelVectZ * centerTapDir.z;
  46289. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  46290. //solid angle stored in 4th channel of normalizer/solid angle cube map
  46291. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  46292. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  46293. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  46294. // so just adding one to specularpower do the trick.
  46295. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  46296. //iterate over channels
  46297. for (k = 0; k < nSrcChannels; k++) {
  46298. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  46299. srcCubeRowWalk++;
  46300. }
  46301. weightAccum += weight; //accumulate weight
  46302. }
  46303. else {
  46304. //step across source pixel
  46305. srcCubeRowWalk += nSrcChannels;
  46306. }
  46307. normCubeRowWalk += 4; // 4 channels per norm cube map.
  46308. }
  46309. startIndexNormCubeMap += normCubePitch;
  46310. startIndexSrcCubeMap += srcCubePitch;
  46311. }
  46312. }
  46313. }
  46314. //divide through by weights if weight is non zero
  46315. if (weightAccum != 0.0) {
  46316. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  46317. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  46318. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  46319. if (this.numChannels > 3) {
  46320. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  46321. }
  46322. }
  46323. else {
  46324. // otherwise sample nearest
  46325. // get face idx and u, v texel coordinate in face
  46326. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  46327. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  46328. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  46329. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  46330. if (this.numChannels > 3) {
  46331. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  46332. }
  46333. }
  46334. return PMREMGenerator._vectorTemp;
  46335. };
  46336. //--------------------------------------------------------------------------------------
  46337. // Fixup cube edges
  46338. //
  46339. // average texels on cube map faces across the edges
  46340. // WARP/BENT Method Only.
  46341. //--------------------------------------------------------------------------------------
  46342. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  46343. var k;
  46344. var j;
  46345. var i;
  46346. var iFace;
  46347. var iCorner = 0;
  46348. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  46349. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  46350. // note that if functionality to filter across the three texels for each corner, then
  46351. //indexed by corner and face idx. the array contains the face the start points belongs to.
  46352. var cornerPtr = [
  46353. [[], [], []],
  46354. [[], [], []],
  46355. [[], [], []],
  46356. [[], [], []],
  46357. [[], [], []],
  46358. [[], [], []],
  46359. [[], [], []],
  46360. [[], [], []]
  46361. ];
  46362. //if there is no fixup, or fixup width = 0, do nothing
  46363. if (cubeMapSize < 1) {
  46364. return;
  46365. }
  46366. //special case 1x1 cubemap, average face colors
  46367. if (cubeMapSize == 1) {
  46368. //iterate over channels
  46369. for (k = 0; k < this.numChannels; k++) {
  46370. var accum = 0.0;
  46371. //iterate over faces to accumulate face colors
  46372. for (iFace = 0; iFace < 6; iFace++) {
  46373. accum += cubeMap[iFace][k];
  46374. }
  46375. //compute average over 6 face colors
  46376. accum /= 6.0;
  46377. //iterate over faces to distribute face colors
  46378. for (iFace = 0; iFace < 6; iFace++) {
  46379. cubeMap[iFace][k] = accum;
  46380. }
  46381. }
  46382. return;
  46383. }
  46384. //iterate over faces to collect list of corner texel pointers
  46385. for (iFace = 0; iFace < 6; iFace++) {
  46386. //the 4 corner pointers for this face
  46387. faceCornerStartIndicies[0] = [iFace, 0];
  46388. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  46389. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  46390. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  46391. //iterate over face corners to collect cube corner pointers
  46392. for (iCorner = 0; iCorner < 4; iCorner++) {
  46393. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  46394. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  46395. cornerNumPtrs[corner]++;
  46396. }
  46397. }
  46398. //iterate over corners to average across corner tap values
  46399. for (iCorner = 0; iCorner < 8; iCorner++) {
  46400. for (k = 0; k < this.numChannels; k++) {
  46401. var cornerTapAccum = 0.0;
  46402. //iterate over corner texels and average results
  46403. for (i = 0; i < 3; i++) {
  46404. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  46405. }
  46406. //divide by 3 to compute average of corner tap values
  46407. cornerTapAccum *= (1.0 / 3.0);
  46408. //iterate over corner texels and average results
  46409. for (i = 0; i < 3; i++) {
  46410. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  46411. }
  46412. }
  46413. }
  46414. //iterate over the twelve edges of the cube to average across edges
  46415. for (i = 0; i < 12; i++) {
  46416. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  46417. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  46418. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  46419. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  46420. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  46421. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  46422. var edgeWalk = 0;
  46423. var neighborEdgeWalk = 0;
  46424. //Determine walking pointers based on edge type
  46425. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  46426. switch (edge) {
  46427. case PMREMGenerator.CP_EDGE_LEFT:
  46428. // no change to faceEdgeStartPtr
  46429. edgeWalk = this.numChannels * cubeMapSize;
  46430. break;
  46431. case PMREMGenerator.CP_EDGE_RIGHT:
  46432. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46433. edgeWalk = this.numChannels * cubeMapSize;
  46434. break;
  46435. case PMREMGenerator.CP_EDGE_TOP:
  46436. // no change to faceEdgeStartPtr
  46437. edgeWalk = this.numChannels;
  46438. break;
  46439. case PMREMGenerator.CP_EDGE_BOTTOM:
  46440. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46441. edgeWalk = this.numChannels;
  46442. break;
  46443. }
  46444. //For certain types of edge abutments, the neighbor edge walk needs to
  46445. // be flipped: the cases are
  46446. // if a left edge mates with a left or bottom edge on the neighbor
  46447. // if a top edge mates with a top or right edge on the neighbor
  46448. // if a right edge mates with a right or top edge on the neighbor
  46449. // if a bottom edge mates with a bottom or left edge on the neighbor
  46450. //Seeing as the edges are enumerated as follows
  46451. // left =0
  46452. // right =1
  46453. // top =2
  46454. // bottom =3
  46455. //
  46456. //If the edge enums are the same, or the sum of the enums == 3,
  46457. // the neighbor edge walk needs to be flipped
  46458. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  46459. switch (neighborEdge) {
  46460. case PMREMGenerator.CP_EDGE_LEFT:
  46461. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  46462. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46463. break;
  46464. case PMREMGenerator.CP_EDGE_RIGHT:
  46465. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46466. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46467. break;
  46468. case PMREMGenerator.CP_EDGE_TOP:
  46469. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46470. neighborEdgeWalk = -this.numChannels;
  46471. break;
  46472. case PMREMGenerator.CP_EDGE_BOTTOM:
  46473. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46474. neighborEdgeWalk = -this.numChannels;
  46475. break;
  46476. }
  46477. }
  46478. else {
  46479. //swapped direction neighbor edge walk
  46480. switch (neighborEdge) {
  46481. case PMREMGenerator.CP_EDGE_LEFT:
  46482. //no change to neighborEdgeStartPtr for this case since it points
  46483. // to the upper left corner already
  46484. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46485. break;
  46486. case PMREMGenerator.CP_EDGE_RIGHT:
  46487. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46488. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46489. break;
  46490. case PMREMGenerator.CP_EDGE_TOP:
  46491. //no change to neighborEdgeStartPtr for this case since it points
  46492. // to the upper left corner already
  46493. neighborEdgeWalk = this.numChannels;
  46494. break;
  46495. case PMREMGenerator.CP_EDGE_BOTTOM:
  46496. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46497. neighborEdgeWalk = this.numChannels;
  46498. break;
  46499. }
  46500. }
  46501. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  46502. //nearby neighborhood
  46503. //step ahead one texel on edge
  46504. edgeStartIndex += edgeWalk;
  46505. neighborEdgeStartIndex += neighborEdgeWalk;
  46506. // note that this loop does not process the corner texels, since they have already been
  46507. // averaged across faces across earlier
  46508. for (j = 1; j < (cubeMapSize - 1); j++) {
  46509. //for each set of taps along edge, average them
  46510. // and rewrite the results into the edges
  46511. for (k = 0; k < this.numChannels; k++) {
  46512. var edgeTap = cubeMap[face][edgeStartIndex + k];
  46513. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  46514. //compute average of tap intensity values
  46515. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  46516. //propagate average of taps to edge taps
  46517. cubeMap[face][edgeStartIndex + k] = avgTap;
  46518. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  46519. }
  46520. edgeStartIndex += edgeWalk;
  46521. neighborEdgeStartIndex += neighborEdgeWalk;
  46522. }
  46523. }
  46524. };
  46525. return PMREMGenerator;
  46526. }());
  46527. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  46528. PMREMGenerator.CP_UDIR = 0;
  46529. PMREMGenerator.CP_VDIR = 1;
  46530. PMREMGenerator.CP_FACEAXIS = 2;
  46531. //used to index cube faces
  46532. PMREMGenerator.CP_FACE_X_POS = 0;
  46533. PMREMGenerator.CP_FACE_X_NEG = 1;
  46534. PMREMGenerator.CP_FACE_Y_POS = 2;
  46535. PMREMGenerator.CP_FACE_Y_NEG = 3;
  46536. PMREMGenerator.CP_FACE_Z_POS = 4;
  46537. PMREMGenerator.CP_FACE_Z_NEG = 5;
  46538. //used to index image edges
  46539. // NOTE.. the actual number corresponding to the edge is important
  46540. // do not change these, or the code will break
  46541. //
  46542. // CP_EDGE_LEFT is u = 0
  46543. // CP_EDGE_RIGHT is u = width-1
  46544. // CP_EDGE_TOP is v = 0
  46545. // CP_EDGE_BOTTOM is v = height-1
  46546. PMREMGenerator.CP_EDGE_LEFT = 0;
  46547. PMREMGenerator.CP_EDGE_RIGHT = 1;
  46548. PMREMGenerator.CP_EDGE_TOP = 2;
  46549. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  46550. //corners of CUBE map (P or N specifys if it corresponds to the
  46551. // positive or negative direction each of X, Y, and Z
  46552. PMREMGenerator.CP_CORNER_NNN = 0;
  46553. PMREMGenerator.CP_CORNER_NNP = 1;
  46554. PMREMGenerator.CP_CORNER_NPN = 2;
  46555. PMREMGenerator.CP_CORNER_NPP = 3;
  46556. PMREMGenerator.CP_CORNER_PNN = 4;
  46557. PMREMGenerator.CP_CORNER_PNP = 5;
  46558. PMREMGenerator.CP_CORNER_PPN = 6;
  46559. PMREMGenerator.CP_CORNER_PPP = 7;
  46560. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  46561. //3x2 matrices that map cube map indexing vectors in 3d
  46562. // (after face selection and divide through by the
  46563. // _ABSOLUTE VALUE_ of the max coord)
  46564. // into NVC space
  46565. //Note this currently assumes the D3D cube face ordering and orientation
  46566. PMREMGenerator._sgFace2DMapping = [
  46567. //XPOS face
  46568. [[0, 0, -1],
  46569. [0, -1, 0],
  46570. [1, 0, 0]],
  46571. //XNEG face
  46572. [[0, 0, 1],
  46573. [0, -1, 0],
  46574. [-1, 0, 0]],
  46575. //YPOS face
  46576. [[1, 0, 0],
  46577. [0, 0, 1],
  46578. [0, 1, 0]],
  46579. //YNEG face
  46580. [[1, 0, 0],
  46581. [0, 0, -1],
  46582. [0, -1, 0]],
  46583. //ZPOS face
  46584. [[1, 0, 0],
  46585. [0, -1, 0],
  46586. [0, 0, 1]],
  46587. //ZNEG face
  46588. [[-1, 0, 0],
  46589. [0, -1, 0],
  46590. [0, 0, -1]],
  46591. ];
  46592. //------------------------------------------------------------------------------
  46593. // D3D cube map face specification
  46594. // mapping from 3D x,y,z cube map lookup coordinates
  46595. // to 2D within face u,v coordinates
  46596. //
  46597. // --------------------> U direction
  46598. // | (within-face texture space)
  46599. // | _____
  46600. // | | |
  46601. // | | +Y |
  46602. // | _____|_____|_____ _____
  46603. // | | | | | |
  46604. // | | -X | +Z | +X | -Z |
  46605. // | |_____|_____|_____|_____|
  46606. // | | |
  46607. // | | -Y |
  46608. // | |_____|
  46609. // |
  46610. // v V direction
  46611. // (within-face texture space)
  46612. //------------------------------------------------------------------------------
  46613. //Information about neighbors and how texture coorrdinates change across faces
  46614. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  46615. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  46616. //Note this currently assumes the D3D cube face ordering and orientation
  46617. PMREMGenerator._sgCubeNgh = [
  46618. //XPOS face
  46619. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46620. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46621. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46622. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  46623. //XNEG face
  46624. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46625. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  46626. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  46627. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  46628. //YPOS face
  46629. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46630. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46631. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46632. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  46633. //YNEG face
  46634. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46635. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46636. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46637. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  46638. //ZPOS face
  46639. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46640. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46641. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46642. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  46643. //ZNEG face
  46644. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46645. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46646. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  46647. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  46648. ];
  46649. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  46650. // this table is used to average over the edges.
  46651. PMREMGenerator._sgCubeEdgeList = [
  46652. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46653. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46654. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46655. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46656. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46657. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46658. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46659. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46660. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  46661. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46662. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46663. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  46664. ];
  46665. //Information about which of the 8 cube corners are correspond to the
  46666. // the 4 corners in each cube face
  46667. // the order is upper left, upper right, lower left, lower right
  46668. PMREMGenerator._sgCubeCornerList = [
  46669. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  46670. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  46671. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  46672. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  46673. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  46674. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  46675. ];
  46676. Internals.PMREMGenerator = PMREMGenerator;
  46677. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46678. })(BABYLON || (BABYLON = {}));
  46679. //# sourceMappingURL=babylon.pmremgenerator.js.map
  46680. var BABYLON;
  46681. (function (BABYLON) {
  46682. /**
  46683. * This represents a texture coming from an HDR input.
  46684. *
  46685. * The only supported format is currently panorama picture stored in RGBE format.
  46686. * Example of such files can be found on HDRLib: http://hdrlib.com/
  46687. */
  46688. var HDRCubeTexture = (function (_super) {
  46689. __extends(HDRCubeTexture, _super);
  46690. /**
  46691. * Instantiates an HDRTexture from the following parameters.
  46692. *
  46693. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  46694. * @param scene The scene the texture will be used in
  46695. * @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.
  46696. * @param noMipmap Forces to not generate the mipmap if true
  46697. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  46698. * @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)
  46699. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  46700. */
  46701. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  46702. if (noMipmap === void 0) { noMipmap = false; }
  46703. if (generateHarmonics === void 0) { generateHarmonics = true; }
  46704. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  46705. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  46706. if (onLoad === void 0) { onLoad = null; }
  46707. if (onError === void 0) { onError = null; }
  46708. var _this = _super.call(this, scene) || this;
  46709. _this._useInGammaSpace = false;
  46710. _this._generateHarmonics = true;
  46711. _this._isBABYLONPreprocessed = false;
  46712. _this._onLoad = null;
  46713. _this._onError = null;
  46714. /**
  46715. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  46716. */
  46717. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46718. /**
  46719. * The spherical polynomial data extracted from the texture.
  46720. */
  46721. _this.sphericalPolynomial = null;
  46722. /**
  46723. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  46724. * This is usefull at run time to apply the good shader.
  46725. */
  46726. _this.isPMREM = false;
  46727. _this._isBlocking = true;
  46728. if (!url) {
  46729. return _this;
  46730. }
  46731. _this.name = url;
  46732. _this.url = url;
  46733. _this.hasAlpha = false;
  46734. _this.isCube = true;
  46735. _this._textureMatrix = BABYLON.Matrix.Identity();
  46736. _this._onLoad = onLoad;
  46737. _this._onError = onError;
  46738. if (size) {
  46739. _this._isBABYLONPreprocessed = false;
  46740. _this._noMipmap = noMipmap;
  46741. _this._size = size;
  46742. _this._useInGammaSpace = useInGammaSpace;
  46743. _this._usePMREMGenerator = usePMREMGenerator &&
  46744. scene.getEngine().getCaps().textureLOD &&
  46745. _this.getScene().getEngine().getCaps().textureFloat &&
  46746. !_this._useInGammaSpace;
  46747. }
  46748. else {
  46749. _this._isBABYLONPreprocessed = true;
  46750. _this._noMipmap = false;
  46751. _this._useInGammaSpace = false;
  46752. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  46753. _this.getScene().getEngine().getCaps().textureFloat &&
  46754. !_this._useInGammaSpace;
  46755. }
  46756. _this.isPMREM = _this._usePMREMGenerator;
  46757. _this._texture = _this._getFromCache(url, _this._noMipmap);
  46758. if (!_this._texture) {
  46759. if (!scene.useDelayedTextureLoading) {
  46760. _this.loadTexture();
  46761. }
  46762. else {
  46763. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46764. }
  46765. }
  46766. return _this;
  46767. }
  46768. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  46769. /**
  46770. * Gets wether or not the texture is blocking during loading.
  46771. */
  46772. get: function () {
  46773. return this._isBlocking;
  46774. },
  46775. /**
  46776. * Sets wether or not the texture is blocking during loading.
  46777. */
  46778. set: function (value) {
  46779. this._isBlocking = value;
  46780. },
  46781. enumerable: true,
  46782. configurable: true
  46783. });
  46784. /**
  46785. * Occurs when the file is a preprocessed .babylon.hdr file.
  46786. */
  46787. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  46788. var _this = this;
  46789. var mipLevels = 0;
  46790. var floatArrayView = null;
  46791. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  46792. var mips = [];
  46793. var startIndex = 30;
  46794. for (var level = 0; level < mipLevels; level++) {
  46795. mips.push([]);
  46796. // Fill each pixel of the mip level.
  46797. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  46798. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46799. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  46800. mips[level].push(faceData);
  46801. startIndex += faceSize;
  46802. }
  46803. }
  46804. return mips;
  46805. } : null;
  46806. var callback = function (buffer) {
  46807. // Create Native Array Views
  46808. var intArrayView = new Int32Array(buffer);
  46809. floatArrayView = new Float32Array(buffer);
  46810. // Fill header.
  46811. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  46812. _this._size = intArrayView[1]; // CubeMap max mip face size.
  46813. // Update Texture Information.
  46814. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  46815. // Fill polynomial information.
  46816. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  46817. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  46818. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  46819. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  46820. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  46821. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  46822. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  46823. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  46824. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  46825. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  46826. // Fill pixel data.
  46827. mipLevels = intArrayView[29]; // Number of mip levels.
  46828. var startIndex = 30;
  46829. var data = [];
  46830. var faceSize = Math.pow(_this._size, 2) * 3;
  46831. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46832. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  46833. startIndex += faceSize;
  46834. }
  46835. var results = [];
  46836. var byteArray = null;
  46837. // Push each faces.
  46838. for (var k = 0; k < 6; k++) {
  46839. var dataFace = null;
  46840. // If special cases.
  46841. if (!mipmapGenerator) {
  46842. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  46843. dataFace = data[j];
  46844. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46845. // 3 channels of 1 bytes per pixel in bytes.
  46846. var byteBuffer = new ArrayBuffer(faceSize);
  46847. byteArray = new Uint8Array(byteBuffer);
  46848. }
  46849. for (var i = 0; i < _this._size * _this._size; i++) {
  46850. // Put in gamma space if requested.
  46851. if (_this._useInGammaSpace) {
  46852. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46853. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46854. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46855. }
  46856. // Convert to int texture for fallback.
  46857. if (byteArray) {
  46858. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46859. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46860. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46861. // May use luminance instead if the result is not accurate.
  46862. var max = Math.max(Math.max(r, g), b);
  46863. if (max > 255) {
  46864. var scale = 255 / max;
  46865. r *= scale;
  46866. g *= scale;
  46867. b *= scale;
  46868. }
  46869. byteArray[(i * 3) + 0] = r;
  46870. byteArray[(i * 3) + 1] = g;
  46871. byteArray[(i * 3) + 2] = b;
  46872. }
  46873. }
  46874. }
  46875. else {
  46876. dataFace = data[k];
  46877. }
  46878. // Fill the array accordingly.
  46879. if (byteArray) {
  46880. results.push(byteArray);
  46881. }
  46882. else {
  46883. results.push(dataFace);
  46884. }
  46885. }
  46886. return results;
  46887. };
  46888. 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);
  46889. };
  46890. /**
  46891. * Occurs when the file is raw .hdr file.
  46892. */
  46893. HDRCubeTexture.prototype.loadHDRTexture = function () {
  46894. var _this = this;
  46895. var callback = function (buffer) {
  46896. // Extract the raw linear data.
  46897. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  46898. // Generate harmonics if needed.
  46899. if (_this._generateHarmonics) {
  46900. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  46901. }
  46902. var results = [];
  46903. var byteArray = null;
  46904. // Push each faces.
  46905. for (var j = 0; j < 6; j++) {
  46906. // Create uintarray fallback.
  46907. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46908. // 3 channels of 1 bytes per pixel in bytes.
  46909. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  46910. byteArray = new Uint8Array(byteBuffer);
  46911. }
  46912. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  46913. // If special cases.
  46914. if (_this._useInGammaSpace || byteArray) {
  46915. for (var i = 0; i < _this._size * _this._size; i++) {
  46916. // Put in gamma space if requested.
  46917. if (_this._useInGammaSpace) {
  46918. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46919. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46920. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46921. }
  46922. // Convert to int texture for fallback.
  46923. if (byteArray) {
  46924. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46925. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46926. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46927. // May use luminance instead if the result is not accurate.
  46928. var max = Math.max(Math.max(r, g), b);
  46929. if (max > 255) {
  46930. var scale = 255 / max;
  46931. r *= scale;
  46932. g *= scale;
  46933. b *= scale;
  46934. }
  46935. byteArray[(i * 3) + 0] = r;
  46936. byteArray[(i * 3) + 1] = g;
  46937. byteArray[(i * 3) + 2] = b;
  46938. }
  46939. }
  46940. }
  46941. if (byteArray) {
  46942. results.push(byteArray);
  46943. }
  46944. else {
  46945. results.push(dataFace);
  46946. }
  46947. }
  46948. return results;
  46949. };
  46950. var mipmapGenerator = null;
  46951. if (!this._noMipmap &&
  46952. this._usePMREMGenerator) {
  46953. mipmapGenerator = function (data) {
  46954. // Custom setup of the generator matching with the PBR shader values.
  46955. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  46956. return generator.filterCubeMap();
  46957. };
  46958. }
  46959. 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);
  46960. };
  46961. /**
  46962. * Starts the loading process of the texture.
  46963. */
  46964. HDRCubeTexture.prototype.loadTexture = function () {
  46965. if (this._isBABYLONPreprocessed) {
  46966. this.loadBabylonTexture();
  46967. }
  46968. else {
  46969. this.loadHDRTexture();
  46970. }
  46971. };
  46972. HDRCubeTexture.prototype.clone = function () {
  46973. var size = this._isBABYLONPreprocessed ? null : this._size;
  46974. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  46975. // Base texture
  46976. newTexture.level = this.level;
  46977. newTexture.wrapU = this.wrapU;
  46978. newTexture.wrapV = this.wrapV;
  46979. newTexture.coordinatesIndex = this.coordinatesIndex;
  46980. newTexture.coordinatesMode = this.coordinatesMode;
  46981. return newTexture;
  46982. };
  46983. // Methods
  46984. HDRCubeTexture.prototype.delayLoad = function () {
  46985. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  46986. return;
  46987. }
  46988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  46989. this._texture = this._getFromCache(this.url, this._noMipmap);
  46990. if (!this._texture) {
  46991. this.loadTexture();
  46992. }
  46993. };
  46994. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  46995. return this._textureMatrix;
  46996. };
  46997. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  46998. var texture = null;
  46999. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  47000. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  47001. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  47002. texture.name = parsedTexture.name;
  47003. texture.hasAlpha = parsedTexture.hasAlpha;
  47004. texture.level = parsedTexture.level;
  47005. texture.coordinatesMode = parsedTexture.coordinatesMode;
  47006. texture.isBlocking = parsedTexture.isBlocking;
  47007. }
  47008. return texture;
  47009. };
  47010. HDRCubeTexture.prototype.serialize = function () {
  47011. if (!this.name) {
  47012. return null;
  47013. }
  47014. var serializationObject = {};
  47015. serializationObject.name = this.name;
  47016. serializationObject.hasAlpha = this.hasAlpha;
  47017. serializationObject.isCube = true;
  47018. serializationObject.level = this.level;
  47019. serializationObject.size = this._size;
  47020. serializationObject.coordinatesMode = this.coordinatesMode;
  47021. serializationObject.useInGammaSpace = this._useInGammaSpace;
  47022. serializationObject.generateHarmonics = this._generateHarmonics;
  47023. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  47024. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  47025. serializationObject.customType = "BABYLON.HDRCubeTexture";
  47026. serializationObject.noMipmap = this._noMipmap;
  47027. serializationObject.isBlocking = this._isBlocking;
  47028. return serializationObject;
  47029. };
  47030. /**
  47031. * Saves as a file the data contained in the texture in a binary format.
  47032. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47033. * as the spherical used in the lighting.
  47034. * @param url The HDR file url.
  47035. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47036. * @param onError Method called if any error happens during download.
  47037. * @return The packed binary data.
  47038. */
  47039. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  47040. if (onError === void 0) { onError = null; }
  47041. var callback = function (buffer) {
  47042. var data = new Blob([buffer], { type: 'application/octet-stream' });
  47043. // Returns a URL you can use as a href.
  47044. var objUrl = window.URL.createObjectURL(data);
  47045. // Simulates a link to it and click to dowload.
  47046. var a = document.createElement("a");
  47047. document.body.appendChild(a);
  47048. a.style.display = "none";
  47049. a.href = objUrl;
  47050. a.download = "envmap.babylon.hdr";
  47051. a.click();
  47052. };
  47053. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  47054. };
  47055. /**
  47056. * Serializes the data contained in the texture in a binary format.
  47057. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47058. * as the spherical used in the lighting.
  47059. * @param url The HDR file url.
  47060. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47061. * @param onError Method called if any error happens during download.
  47062. * @return The packed binary data.
  47063. */
  47064. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  47065. if (onError === void 0) { onError = null; }
  47066. // Needs the url tho create the texture.
  47067. if (!url) {
  47068. return null;
  47069. }
  47070. // Check Power of two size.
  47071. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  47072. return null;
  47073. }
  47074. var getDataCallback = function (dataBuffer) {
  47075. // Extract the raw linear data.
  47076. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  47077. // Generate harmonics if needed.
  47078. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  47079. // Generate seamless faces
  47080. var mipGeneratorArray = [];
  47081. // Data are known to be in +X +Y +Z -X -Y -Z
  47082. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  47083. mipGeneratorArray.push(cubeData.right); // +X
  47084. mipGeneratorArray.push(cubeData.left); // -X
  47085. mipGeneratorArray.push(cubeData.up); // +Y
  47086. mipGeneratorArray.push(cubeData.down); // -Y
  47087. mipGeneratorArray.push(cubeData.front); // +Z
  47088. mipGeneratorArray.push(cubeData.back); // -Z
  47089. // Custom setup of the generator matching with the PBR shader values.
  47090. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  47091. var mippedData = generator.filterCubeMap();
  47092. // Compute required byte length.
  47093. var byteLength = 1 * 4; // Raw Data Version int32.
  47094. byteLength += 4; // CubeMap max mip face size int32.
  47095. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  47096. // Add data size.
  47097. byteLength += 4; // Number of mip levels int32.
  47098. for (var level = 0; level < mippedData.length; level++) {
  47099. var mipSize = size >> level;
  47100. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  47101. }
  47102. // Prepare binary structure.
  47103. var buffer = new ArrayBuffer(byteLength);
  47104. var intArrayView = new Int32Array(buffer);
  47105. var floatArrayView = new Float32Array(buffer);
  47106. // Fill header.
  47107. intArrayView[0] = 1; // Version 1.
  47108. intArrayView[1] = size; // CubeMap max mip face size.
  47109. // Fill polynomial information.
  47110. sphericalPolynomial.x.toArray(floatArrayView, 2);
  47111. sphericalPolynomial.y.toArray(floatArrayView, 5);
  47112. sphericalPolynomial.z.toArray(floatArrayView, 8);
  47113. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  47114. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  47115. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  47116. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  47117. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  47118. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  47119. // Fill pixel data.
  47120. intArrayView[29] = mippedData.length; // Number of mip levels.
  47121. var startIndex = 30;
  47122. for (var level = 0; level < mippedData.length; level++) {
  47123. // Fill each pixel of the mip level.
  47124. var faceSize = Math.pow(size >> level, 2) * 3;
  47125. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47126. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  47127. startIndex += faceSize;
  47128. }
  47129. }
  47130. // Callback.
  47131. callback(buffer);
  47132. };
  47133. // Download and process.
  47134. BABYLON.Tools.LoadFile(url, function (data) {
  47135. getDataCallback(data);
  47136. }, null, null, true, onError);
  47137. };
  47138. return HDRCubeTexture;
  47139. }(BABYLON.BaseTexture));
  47140. HDRCubeTexture._facesMapping = [
  47141. "right",
  47142. "up",
  47143. "front",
  47144. "left",
  47145. "down",
  47146. "back"
  47147. ];
  47148. BABYLON.HDRCubeTexture = HDRCubeTexture;
  47149. })(BABYLON || (BABYLON = {}));
  47150. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  47151. var BABYLON;
  47152. (function (BABYLON) {
  47153. var DefaultLoadingScreen = (function () {
  47154. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47155. if (_loadingText === void 0) { _loadingText = ""; }
  47156. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47157. var _this = this;
  47158. this._renderingCanvas = _renderingCanvas;
  47159. this._loadingText = _loadingText;
  47160. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47161. // Resize
  47162. this._resizeLoadingUI = function () {
  47163. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47164. _this._loadingDiv.style.position = "absolute";
  47165. _this._loadingDiv.style.left = canvasRect.left + "px";
  47166. _this._loadingDiv.style.top = canvasRect.top + "px";
  47167. _this._loadingDiv.style.width = canvasRect.width + "px";
  47168. _this._loadingDiv.style.height = canvasRect.height + "px";
  47169. };
  47170. }
  47171. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47172. if (this._loadingDiv) {
  47173. // Do not add a loading screen if there is already one
  47174. return;
  47175. }
  47176. this._loadingDiv = document.createElement("div");
  47177. this._loadingDiv.id = "babylonjsLoadingDiv";
  47178. this._loadingDiv.style.opacity = "0";
  47179. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47180. // Loading text
  47181. this._loadingTextDiv = document.createElement("div");
  47182. this._loadingTextDiv.style.position = "absolute";
  47183. this._loadingTextDiv.style.left = "0";
  47184. this._loadingTextDiv.style.top = "50%";
  47185. this._loadingTextDiv.style.marginTop = "80px";
  47186. this._loadingTextDiv.style.width = "100%";
  47187. this._loadingTextDiv.style.height = "20px";
  47188. this._loadingTextDiv.style.fontFamily = "Arial";
  47189. this._loadingTextDiv.style.fontSize = "14px";
  47190. this._loadingTextDiv.style.color = "white";
  47191. this._loadingTextDiv.style.textAlign = "center";
  47192. this._loadingTextDiv.innerHTML = "Loading";
  47193. this._loadingDiv.appendChild(this._loadingTextDiv);
  47194. //set the predefined text
  47195. this._loadingTextDiv.innerHTML = this._loadingText;
  47196. // Generating keyframes
  47197. var style = document.createElement('style');
  47198. style.type = 'text/css';
  47199. 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 }";
  47200. style.innerHTML = keyFrames;
  47201. document.getElementsByTagName('head')[0].appendChild(style);
  47202. // Loading img
  47203. var imgBack = new Image();
  47204. 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";
  47205. imgBack.style.position = "absolute";
  47206. imgBack.style.left = "50%";
  47207. imgBack.style.top = "50%";
  47208. imgBack.style.marginLeft = "-50px";
  47209. imgBack.style.marginTop = "-50px";
  47210. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47211. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47212. imgBack.style.transformOrigin = "50% 50%";
  47213. imgBack.style.webkitTransformOrigin = "50% 50%";
  47214. this._loadingDiv.appendChild(imgBack);
  47215. this._resizeLoadingUI();
  47216. window.addEventListener("resize", this._resizeLoadingUI);
  47217. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47218. document.body.appendChild(this._loadingDiv);
  47219. this._loadingDiv.style.opacity = "1";
  47220. };
  47221. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47222. var _this = this;
  47223. if (!this._loadingDiv) {
  47224. return;
  47225. }
  47226. var onTransitionEnd = function () {
  47227. if (!_this._loadingDiv) {
  47228. return;
  47229. }
  47230. document.body.removeChild(_this._loadingDiv);
  47231. window.removeEventListener("resize", _this._resizeLoadingUI);
  47232. _this._loadingDiv = null;
  47233. };
  47234. this._loadingDiv.style.opacity = "0";
  47235. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47236. };
  47237. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47238. set: function (text) {
  47239. this._loadingText = text;
  47240. if (this._loadingTextDiv) {
  47241. this._loadingTextDiv.innerHTML = this._loadingText;
  47242. }
  47243. },
  47244. enumerable: true,
  47245. configurable: true
  47246. });
  47247. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47248. get: function () {
  47249. return this._loadingDivBackgroundColor;
  47250. },
  47251. set: function (color) {
  47252. this._loadingDivBackgroundColor = color;
  47253. if (!this._loadingDiv) {
  47254. return;
  47255. }
  47256. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47257. },
  47258. enumerable: true,
  47259. configurable: true
  47260. });
  47261. return DefaultLoadingScreen;
  47262. }());
  47263. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47264. })(BABYLON || (BABYLON = {}));
  47265. //# sourceMappingURL=babylon.loadingScreen.js.map
  47266. var BABYLON;
  47267. (function (BABYLON) {
  47268. var SceneLoader = (function () {
  47269. function SceneLoader() {
  47270. }
  47271. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47272. get: function () {
  47273. return 0;
  47274. },
  47275. enumerable: true,
  47276. configurable: true
  47277. });
  47278. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47279. get: function () {
  47280. return 1;
  47281. },
  47282. enumerable: true,
  47283. configurable: true
  47284. });
  47285. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47286. get: function () {
  47287. return 2;
  47288. },
  47289. enumerable: true,
  47290. configurable: true
  47291. });
  47292. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47293. get: function () {
  47294. return 3;
  47295. },
  47296. enumerable: true,
  47297. configurable: true
  47298. });
  47299. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47300. get: function () {
  47301. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47302. },
  47303. set: function (value) {
  47304. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47305. },
  47306. enumerable: true,
  47307. configurable: true
  47308. });
  47309. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47310. get: function () {
  47311. return SceneLoader._ShowLoadingScreen;
  47312. },
  47313. set: function (value) {
  47314. SceneLoader._ShowLoadingScreen = value;
  47315. },
  47316. enumerable: true,
  47317. configurable: true
  47318. });
  47319. Object.defineProperty(SceneLoader, "loggingLevel", {
  47320. get: function () {
  47321. return SceneLoader._loggingLevel;
  47322. },
  47323. set: function (value) {
  47324. SceneLoader._loggingLevel = value;
  47325. },
  47326. enumerable: true,
  47327. configurable: true
  47328. });
  47329. SceneLoader._getDefaultPlugin = function () {
  47330. return SceneLoader._registeredPlugins[".babylon"];
  47331. };
  47332. SceneLoader._getPluginForExtension = function (extension) {
  47333. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47334. if (registeredPlugin) {
  47335. return registeredPlugin;
  47336. }
  47337. return SceneLoader._getDefaultPlugin();
  47338. };
  47339. SceneLoader._getPluginForDirectLoad = function (data) {
  47340. for (var extension in SceneLoader._registeredPlugins) {
  47341. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47342. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47343. return SceneLoader._registeredPlugins[extension];
  47344. }
  47345. }
  47346. return SceneLoader._getDefaultPlugin();
  47347. };
  47348. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47349. if (sceneFilename.name) {
  47350. sceneFilename = sceneFilename.name;
  47351. }
  47352. var dotPosition = sceneFilename.lastIndexOf(".");
  47353. var queryStringPosition = sceneFilename.indexOf("?");
  47354. if (queryStringPosition === -1) {
  47355. queryStringPosition = sceneFilename.length;
  47356. }
  47357. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47358. return SceneLoader._getPluginForExtension(extension);
  47359. };
  47360. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47361. SceneLoader._getDirectLoad = function (sceneFilename) {
  47362. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47363. return sceneFilename.substr(5);
  47364. }
  47365. return null;
  47366. };
  47367. // Public functions
  47368. SceneLoader.GetPluginForExtension = function (extension) {
  47369. return SceneLoader._getPluginForExtension(extension).plugin;
  47370. };
  47371. SceneLoader.RegisterPlugin = function (plugin) {
  47372. if (typeof plugin.extensions === "string") {
  47373. var extension = plugin.extensions;
  47374. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47375. plugin: plugin,
  47376. isBinary: false
  47377. };
  47378. }
  47379. else {
  47380. var extensions = plugin.extensions;
  47381. Object.keys(extensions).forEach(function (extension) {
  47382. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47383. plugin: plugin,
  47384. isBinary: extensions[extension].isBinary
  47385. };
  47386. });
  47387. }
  47388. };
  47389. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47390. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47391. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47392. return;
  47393. }
  47394. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47395. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47396. return;
  47397. }
  47398. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47399. var loadingToken = {};
  47400. scene._addPendingData(loadingToken);
  47401. var manifestChecked = function (success) {
  47402. scene.database = database;
  47403. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  47404. var plugin = registeredPlugin.plugin;
  47405. var useArrayBuffer = registeredPlugin.isBinary;
  47406. var importMeshFromData = function (data) {
  47407. var meshes = [];
  47408. var particleSystems = [];
  47409. var skeletons = [];
  47410. if (scene.isDisposed) {
  47411. if (onerror) {
  47412. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  47413. }
  47414. return;
  47415. }
  47416. try {
  47417. if (plugin.importMesh) {
  47418. var syncedPlugin = plugin;
  47419. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  47420. if (onerror) {
  47421. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47422. }
  47423. scene._removePendingData(loadingToken);
  47424. return;
  47425. }
  47426. if (onsuccess) {
  47427. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47428. onsuccess(meshes, particleSystems, skeletons);
  47429. scene._removePendingData(loadingToken);
  47430. }
  47431. }
  47432. else {
  47433. var asyncedPlugin = plugin;
  47434. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47435. if (onsuccess) {
  47436. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47437. onsuccess(meshes, particleSystems, skeletons);
  47438. scene._removePendingData(loadingToken);
  47439. }
  47440. }, function () {
  47441. if (onerror) {
  47442. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47443. }
  47444. scene._removePendingData(loadingToken);
  47445. });
  47446. }
  47447. }
  47448. catch (e) {
  47449. if (onerror) {
  47450. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  47451. }
  47452. scene._removePendingData(loadingToken);
  47453. }
  47454. };
  47455. if (directLoad) {
  47456. importMeshFromData(directLoad);
  47457. return;
  47458. }
  47459. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  47460. importMeshFromData(data);
  47461. }, progressCallBack, database, useArrayBuffer, function () {
  47462. if (onerror) {
  47463. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  47464. }
  47465. });
  47466. };
  47467. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  47468. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47469. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47470. }
  47471. else {
  47472. // If the scene is a data stream or offline support is not enabled, it's a direct load
  47473. manifestChecked(true);
  47474. }
  47475. };
  47476. /**
  47477. * Load a scene
  47478. * @param rootUrl a string that defines the root url for scene and resources
  47479. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47480. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47481. */
  47482. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  47483. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  47484. };
  47485. /**
  47486. * Append a scene
  47487. * @param rootUrl a string that defines the root url for scene and resources
  47488. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47489. * @param scene is the instance of BABYLON.Scene to append to
  47490. */
  47491. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47492. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47493. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47494. return;
  47495. }
  47496. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47497. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47498. var plugin = registeredPlugin.plugin;
  47499. var useArrayBuffer = registeredPlugin.isBinary;
  47500. var database;
  47501. var loadingToken = {};
  47502. scene._addPendingData(loadingToken);
  47503. if (SceneLoader.ShowLoadingScreen) {
  47504. scene.getEngine().displayLoadingUI();
  47505. }
  47506. var loadSceneFromData = function (data) {
  47507. scene.database = database;
  47508. if (plugin.load) {
  47509. var syncedPlugin = plugin;
  47510. if (!syncedPlugin.load(scene, data, rootUrl)) {
  47511. if (onerror) {
  47512. onerror(scene);
  47513. }
  47514. scene._removePendingData(loadingToken);
  47515. scene.getEngine().hideLoadingUI();
  47516. return;
  47517. }
  47518. if (onsuccess) {
  47519. onsuccess(scene);
  47520. }
  47521. scene._removePendingData(loadingToken);
  47522. }
  47523. else {
  47524. var asyncedPlugin = plugin;
  47525. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47526. if (onsuccess) {
  47527. onsuccess(scene);
  47528. }
  47529. scene._removePendingData(loadingToken);
  47530. }, function () {
  47531. if (onerror) {
  47532. onerror(scene);
  47533. }
  47534. scene._removePendingData(loadingToken);
  47535. scene.getEngine().hideLoadingUI();
  47536. });
  47537. }
  47538. if (SceneLoader.ShowLoadingScreen) {
  47539. scene.executeWhenReady(function () {
  47540. scene.getEngine().hideLoadingUI();
  47541. });
  47542. }
  47543. };
  47544. var manifestChecked = function (success) {
  47545. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  47546. };
  47547. if (directLoad) {
  47548. loadSceneFromData(directLoad);
  47549. return;
  47550. }
  47551. if (rootUrl.indexOf("file:") === -1) {
  47552. if (scene.getEngine().enableOfflineSupport) {
  47553. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47554. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47555. }
  47556. else {
  47557. manifestChecked(true);
  47558. }
  47559. }
  47560. else {
  47561. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  47562. }
  47563. };
  47564. return SceneLoader;
  47565. }());
  47566. // Flags
  47567. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47568. SceneLoader._ShowLoadingScreen = true;
  47569. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47570. // Members
  47571. SceneLoader._registeredPlugins = {};
  47572. BABYLON.SceneLoader = SceneLoader;
  47573. ;
  47574. })(BABYLON || (BABYLON = {}));
  47575. //# sourceMappingURL=babylon.sceneLoader.js.map
  47576. var BABYLON;
  47577. (function (BABYLON) {
  47578. var Internals;
  47579. (function (Internals) {
  47580. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47581. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47582. var parsedMaterial = parsedData.materials[index];
  47583. if (parsedMaterial.id === id) {
  47584. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47585. }
  47586. }
  47587. return null;
  47588. };
  47589. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47590. names = (names instanceof Array) ? names : [names];
  47591. for (var i in names) {
  47592. if (mesh.name === names[i]) {
  47593. hierarchyIds.push(mesh.id);
  47594. return true;
  47595. }
  47596. }
  47597. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47598. hierarchyIds.push(mesh.id);
  47599. return true;
  47600. }
  47601. return false;
  47602. };
  47603. var logOperation = function (operation, producer) {
  47604. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47605. };
  47606. BABYLON.SceneLoader.RegisterPlugin({
  47607. extensions: ".babylon",
  47608. canDirectLoad: function (data) {
  47609. if (data.indexOf("babylon") !== -1) {
  47610. return true;
  47611. }
  47612. return false;
  47613. },
  47614. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47615. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47616. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47617. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47618. // and avoid problems with multiple concurrent .babylon loads.
  47619. var log = "importMesh has failed JSON parse";
  47620. try {
  47621. var parsedData = JSON.parse(data);
  47622. log = "";
  47623. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47624. var loadedSkeletonsIds = [];
  47625. var loadedMaterialsIds = [];
  47626. var hierarchyIds = [];
  47627. var index;
  47628. var cache;
  47629. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47630. var parsedMesh = parsedData.meshes[index];
  47631. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47632. if (meshesNames instanceof Array) {
  47633. // Remove found mesh name from list.
  47634. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47635. }
  47636. //Geometry?
  47637. if (parsedMesh.geometryId) {
  47638. //does the file contain geometries?
  47639. if (parsedData.geometries) {
  47640. //find the correct geometry and add it to the scene
  47641. var found = false;
  47642. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47643. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  47644. return;
  47645. }
  47646. else {
  47647. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47648. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47649. switch (geometryType) {
  47650. case "boxes":
  47651. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47652. break;
  47653. case "spheres":
  47654. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47655. break;
  47656. case "cylinders":
  47657. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47658. break;
  47659. case "toruses":
  47660. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47661. break;
  47662. case "grounds":
  47663. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47664. break;
  47665. case "planes":
  47666. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47667. break;
  47668. case "torusKnots":
  47669. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47670. break;
  47671. case "vertexData":
  47672. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47673. break;
  47674. }
  47675. found = true;
  47676. }
  47677. });
  47678. }
  47679. });
  47680. if (!found) {
  47681. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47682. }
  47683. }
  47684. }
  47685. // Material ?
  47686. if (parsedMesh.materialId) {
  47687. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47688. if (!materialFound && parsedData.multiMaterials) {
  47689. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47690. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47691. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47692. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47693. var subMatId = parsedMultiMaterial.materials[matIndex];
  47694. loadedMaterialsIds.push(subMatId);
  47695. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47696. log += "\n\tMaterial " + mat.toString(fullDetails);
  47697. }
  47698. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47699. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47700. materialFound = true;
  47701. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47702. break;
  47703. }
  47704. }
  47705. }
  47706. if (!materialFound) {
  47707. loadedMaterialsIds.push(parsedMesh.materialId);
  47708. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47709. if (!mat) {
  47710. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47711. }
  47712. else {
  47713. log += "\n\tMaterial " + mat.toString(fullDetails);
  47714. }
  47715. }
  47716. }
  47717. // Skeleton ?
  47718. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  47719. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47720. if (!skeletonAlreadyLoaded) {
  47721. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47722. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47723. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47724. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47725. skeletons.push(skeleton);
  47726. loadedSkeletonsIds.push(parsedSkeleton.id);
  47727. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47728. }
  47729. }
  47730. }
  47731. }
  47732. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47733. meshes.push(mesh);
  47734. log += "\n\tMesh " + mesh.toString(fullDetails);
  47735. }
  47736. }
  47737. // Connecting parents
  47738. var currentMesh;
  47739. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47740. currentMesh = scene.meshes[index];
  47741. if (currentMesh._waitingParentId) {
  47742. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47743. currentMesh._waitingParentId = undefined;
  47744. }
  47745. }
  47746. // freeze and compute world matrix application
  47747. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47748. currentMesh = scene.meshes[index];
  47749. if (currentMesh._waitingFreezeWorldMatrix) {
  47750. currentMesh.freezeWorldMatrix();
  47751. currentMesh._waitingFreezeWorldMatrix = undefined;
  47752. }
  47753. else {
  47754. currentMesh.computeWorldMatrix(true);
  47755. }
  47756. }
  47757. // Particles
  47758. if (parsedData.particleSystems) {
  47759. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47760. var parsedParticleSystem = parsedData.particleSystems[index];
  47761. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47762. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47763. }
  47764. }
  47765. }
  47766. return true;
  47767. }
  47768. catch (err) {
  47769. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47770. log = null;
  47771. throw err;
  47772. }
  47773. finally {
  47774. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47775. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47776. }
  47777. }
  47778. },
  47779. load: function (scene, data, rootUrl) {
  47780. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47781. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47782. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47783. // and avoid problems with multiple concurrent .babylon loads.
  47784. var log = "importScene has failed JSON parse";
  47785. try {
  47786. var parsedData = JSON.parse(data);
  47787. log = "";
  47788. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47789. // Scene
  47790. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47791. scene.autoClear = parsedData.autoClear;
  47792. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47793. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47794. if (parsedData.gravity) {
  47795. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47796. }
  47797. // Fog
  47798. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47799. scene.fogMode = parsedData.fogMode;
  47800. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47801. scene.fogStart = parsedData.fogStart;
  47802. scene.fogEnd = parsedData.fogEnd;
  47803. scene.fogDensity = parsedData.fogDensity;
  47804. log += "\tFog mode for scene: ";
  47805. switch (scene.fogMode) {
  47806. // getters not compiling, so using hardcoded
  47807. case 1:
  47808. log += "exp\n";
  47809. break;
  47810. case 2:
  47811. log += "exp2\n";
  47812. break;
  47813. case 3:
  47814. log += "linear\n";
  47815. break;
  47816. }
  47817. }
  47818. //Physics
  47819. if (parsedData.physicsEnabled) {
  47820. var physicsPlugin;
  47821. if (parsedData.physicsEngine === "cannon") {
  47822. physicsPlugin = new BABYLON.CannonJSPlugin();
  47823. }
  47824. else if (parsedData.physicsEngine === "oimo") {
  47825. physicsPlugin = new BABYLON.OimoJSPlugin();
  47826. }
  47827. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47828. //else - default engine, which is currently oimo
  47829. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47830. scene.enablePhysics(physicsGravity, physicsPlugin);
  47831. }
  47832. // Metadata
  47833. if (parsedData.metadata !== undefined) {
  47834. scene.metadata = parsedData.metadata;
  47835. }
  47836. //collisions, if defined. otherwise, default is true
  47837. if (parsedData.collisionsEnabled != undefined) {
  47838. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47839. }
  47840. scene.workerCollisions = !!parsedData.workerCollisions;
  47841. var index;
  47842. var cache;
  47843. // Lights
  47844. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47845. var parsedLight = parsedData.lights[index];
  47846. var light = BABYLON.Light.Parse(parsedLight, scene);
  47847. log += (index === 0 ? "\n\tLights:" : "");
  47848. log += "\n\t\t" + light.toString(fullDetails);
  47849. }
  47850. // Animations
  47851. if (parsedData.animations) {
  47852. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47853. var parsedAnimation = parsedData.animations[index];
  47854. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47855. scene.animations.push(animation);
  47856. log += (index === 0 ? "\n\tAnimations:" : "");
  47857. log += "\n\t\t" + animation.toString(fullDetails);
  47858. }
  47859. }
  47860. if (parsedData.autoAnimate) {
  47861. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47862. }
  47863. // Materials
  47864. if (parsedData.materials) {
  47865. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47866. var parsedMaterial = parsedData.materials[index];
  47867. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47868. log += (index === 0 ? "\n\tMaterials:" : "");
  47869. log += "\n\t\t" + mat.toString(fullDetails);
  47870. }
  47871. }
  47872. if (parsedData.multiMaterials) {
  47873. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47874. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47875. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47876. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47877. log += "\n\t\t" + mmat.toString(fullDetails);
  47878. }
  47879. }
  47880. // Morph targets
  47881. if (parsedData.morphTargetManagers) {
  47882. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47883. var managerData = _a[_i];
  47884. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47885. }
  47886. }
  47887. // Skeletons
  47888. if (parsedData.skeletons) {
  47889. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47890. var parsedSkeleton = parsedData.skeletons[index];
  47891. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47892. log += (index === 0 ? "\n\tSkeletons:" : "");
  47893. log += "\n\t\t" + skeleton.toString(fullDetails);
  47894. }
  47895. }
  47896. // Geometries
  47897. var geometries = parsedData.geometries;
  47898. if (geometries) {
  47899. // Boxes
  47900. var boxes = geometries.boxes;
  47901. if (boxes) {
  47902. for (index = 0, cache = boxes.length; index < cache; index++) {
  47903. var parsedBox = boxes[index];
  47904. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47905. }
  47906. }
  47907. // Spheres
  47908. var spheres = geometries.spheres;
  47909. if (spheres) {
  47910. for (index = 0, cache = spheres.length; index < cache; index++) {
  47911. var parsedSphere = spheres[index];
  47912. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47913. }
  47914. }
  47915. // Cylinders
  47916. var cylinders = geometries.cylinders;
  47917. if (cylinders) {
  47918. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47919. var parsedCylinder = cylinders[index];
  47920. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47921. }
  47922. }
  47923. // Toruses
  47924. var toruses = geometries.toruses;
  47925. if (toruses) {
  47926. for (index = 0, cache = toruses.length; index < cache; index++) {
  47927. var parsedTorus = toruses[index];
  47928. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47929. }
  47930. }
  47931. // Grounds
  47932. var grounds = geometries.grounds;
  47933. if (grounds) {
  47934. for (index = 0, cache = grounds.length; index < cache; index++) {
  47935. var parsedGround = grounds[index];
  47936. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47937. }
  47938. }
  47939. // Planes
  47940. var planes = geometries.planes;
  47941. if (planes) {
  47942. for (index = 0, cache = planes.length; index < cache; index++) {
  47943. var parsedPlane = planes[index];
  47944. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47945. }
  47946. }
  47947. // TorusKnots
  47948. var torusKnots = geometries.torusKnots;
  47949. if (torusKnots) {
  47950. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47951. var parsedTorusKnot = torusKnots[index];
  47952. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47953. }
  47954. }
  47955. // VertexData
  47956. var vertexData = geometries.vertexData;
  47957. if (vertexData) {
  47958. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47959. var parsedVertexData = vertexData[index];
  47960. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47961. }
  47962. }
  47963. }
  47964. // Meshes
  47965. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47966. var parsedMesh = parsedData.meshes[index];
  47967. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47968. log += (index === 0 ? "\n\tMeshes:" : "");
  47969. log += "\n\t\t" + mesh.toString(fullDetails);
  47970. }
  47971. // Cameras
  47972. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47973. var parsedCamera = parsedData.cameras[index];
  47974. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47975. log += (index === 0 ? "\n\tCameras:" : "");
  47976. log += "\n\t\t" + camera.toString(fullDetails);
  47977. }
  47978. if (parsedData.activeCameraID) {
  47979. scene.setActiveCameraByID(parsedData.activeCameraID);
  47980. }
  47981. // Browsing all the graph to connect the dots
  47982. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47983. var camera = scene.cameras[index];
  47984. if (camera._waitingParentId) {
  47985. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  47986. camera._waitingParentId = undefined;
  47987. }
  47988. }
  47989. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  47990. var light = scene.lights[index];
  47991. if (light._waitingParentId) {
  47992. light.parent = scene.getLastEntryByID(light._waitingParentId);
  47993. light._waitingParentId = undefined;
  47994. }
  47995. }
  47996. // Sounds
  47997. var loadedSounds = [];
  47998. var loadedSound;
  47999. if (BABYLON.AudioEngine && parsedData.sounds) {
  48000. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48001. var parsedSound = parsedData.sounds[index];
  48002. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48003. if (!parsedSound.url)
  48004. parsedSound.url = parsedSound.name;
  48005. if (!loadedSounds[parsedSound.url]) {
  48006. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48007. loadedSounds[parsedSound.url] = loadedSound;
  48008. }
  48009. else {
  48010. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48011. }
  48012. }
  48013. else {
  48014. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48015. }
  48016. }
  48017. }
  48018. loadedSounds = [];
  48019. // Connect parents & children and parse actions
  48020. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48021. var mesh = scene.meshes[index];
  48022. if (mesh._waitingParentId) {
  48023. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48024. mesh._waitingParentId = undefined;
  48025. }
  48026. if (mesh._waitingActions) {
  48027. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48028. mesh._waitingActions = undefined;
  48029. }
  48030. }
  48031. // freeze world matrix application
  48032. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48033. var currentMesh = scene.meshes[index];
  48034. if (currentMesh._waitingFreezeWorldMatrix) {
  48035. currentMesh.freezeWorldMatrix();
  48036. currentMesh._waitingFreezeWorldMatrix = undefined;
  48037. }
  48038. else {
  48039. currentMesh.computeWorldMatrix(true);
  48040. }
  48041. }
  48042. // Particles Systems
  48043. if (parsedData.particleSystems) {
  48044. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48045. var parsedParticleSystem = parsedData.particleSystems[index];
  48046. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48047. }
  48048. }
  48049. // Lens flares
  48050. if (parsedData.lensFlareSystems) {
  48051. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48052. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48053. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48054. }
  48055. }
  48056. // Shadows
  48057. if (parsedData.shadowGenerators) {
  48058. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48059. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48060. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48061. }
  48062. }
  48063. // Lights exclusions / inclusions
  48064. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48065. var light = scene.lights[index];
  48066. // Excluded check
  48067. if (light._excludedMeshesIds.length > 0) {
  48068. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48069. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48070. if (excludedMesh) {
  48071. light.excludedMeshes.push(excludedMesh);
  48072. }
  48073. }
  48074. light._excludedMeshesIds = [];
  48075. }
  48076. // Included check
  48077. if (light._includedOnlyMeshesIds.length > 0) {
  48078. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48079. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48080. if (includedOnlyMesh) {
  48081. light.includedOnlyMeshes.push(includedOnlyMesh);
  48082. }
  48083. }
  48084. light._includedOnlyMeshesIds = [];
  48085. }
  48086. }
  48087. // Actions (scene)
  48088. if (parsedData.actions) {
  48089. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48090. }
  48091. // Finish
  48092. return true;
  48093. }
  48094. catch (err) {
  48095. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48096. log = null;
  48097. throw err;
  48098. }
  48099. finally {
  48100. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48101. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48102. }
  48103. }
  48104. }
  48105. });
  48106. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48107. })(BABYLON || (BABYLON = {}));
  48108. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48109. var BABYLON;
  48110. (function (BABYLON) {
  48111. var FilesInput = (function () {
  48112. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  48113. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  48114. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  48115. this._engine = p_engine;
  48116. this._canvas = p_canvas;
  48117. this._currentScene = p_scene;
  48118. this._sceneLoadedCallback = p_sceneLoadedCallback;
  48119. this._progressCallback = p_progressCallback;
  48120. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  48121. this._textureLoadingCallback = p_textureLoadingCallback;
  48122. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  48123. }
  48124. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  48125. var _this = this;
  48126. if (p_elementToMonitor) {
  48127. this._elementToMonitor = p_elementToMonitor;
  48128. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  48129. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  48130. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  48131. }
  48132. };
  48133. FilesInput.prototype.renderFunction = function () {
  48134. if (this._additionnalRenderLoopLogicCallback) {
  48135. this._additionnalRenderLoopLogicCallback();
  48136. }
  48137. if (this._currentScene) {
  48138. if (this._textureLoadingCallback) {
  48139. var remaining = this._currentScene.getWaitingItemsCount();
  48140. if (remaining > 0) {
  48141. this._textureLoadingCallback(remaining);
  48142. }
  48143. }
  48144. this._currentScene.render();
  48145. }
  48146. };
  48147. FilesInput.prototype.drag = function (e) {
  48148. e.stopPropagation();
  48149. e.preventDefault();
  48150. };
  48151. FilesInput.prototype.drop = function (eventDrop) {
  48152. eventDrop.stopPropagation();
  48153. eventDrop.preventDefault();
  48154. this.loadFiles(eventDrop);
  48155. };
  48156. FilesInput.prototype.loadFiles = function (event) {
  48157. if (this._startingProcessingFilesCallback)
  48158. this._startingProcessingFilesCallback();
  48159. // Handling data transfer via drag'n'drop
  48160. if (event && event.dataTransfer && event.dataTransfer.files) {
  48161. this._filesToLoad = event.dataTransfer.files;
  48162. }
  48163. // Handling files from input files
  48164. if (event && event.target && event.target.files) {
  48165. this._filesToLoad = event.target.files;
  48166. }
  48167. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48168. for (var i = 0; i < this._filesToLoad.length; i++) {
  48169. var name_1 = this._filesToLoad[i].name.toLowerCase();
  48170. var extension = name_1.split('.').pop();
  48171. var type = this._filesToLoad[i].type;
  48172. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48173. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  48174. this._sceneFileToLoad = this._filesToLoad[i];
  48175. }
  48176. else {
  48177. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  48178. }
  48179. }
  48180. this.reload();
  48181. }
  48182. };
  48183. FilesInput.prototype.reload = function () {
  48184. var _this = this;
  48185. var that = this;
  48186. // If a ".babylon" file has been provided
  48187. if (this._sceneFileToLoad) {
  48188. if (this._currentScene) {
  48189. if (BABYLON.Tools.errorsCount > 0) {
  48190. BABYLON.Tools.ClearLogCache();
  48191. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48192. }
  48193. this._engine.stopRenderLoop();
  48194. this._currentScene.dispose();
  48195. }
  48196. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48197. that._currentScene = newScene;
  48198. // Wait for textures and shaders to be ready
  48199. that._currentScene.executeWhenReady(function () {
  48200. if (that._sceneLoadedCallback) {
  48201. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  48202. }
  48203. that._engine.runRenderLoop(function () { that.renderFunction(); });
  48204. });
  48205. }, function (progress) {
  48206. if (_this._progressCallback) {
  48207. _this._progressCallback(progress);
  48208. }
  48209. });
  48210. }
  48211. else {
  48212. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48213. }
  48214. };
  48215. return FilesInput;
  48216. }());
  48217. FilesInput.FilesToLoad = new Array();
  48218. BABYLON.FilesInput = FilesInput;
  48219. })(BABYLON || (BABYLON = {}));
  48220. //# sourceMappingURL=babylon.filesInput.js.map
  48221. 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 VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\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 ALBEDO\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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) || defined(METALLICWORKFLOW) \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#ifdef MICROSURFACEMAP\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#ifdef BUMP\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 NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\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\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#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#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 METALLICMAP\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#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n\n#ifdef REFRACTION\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\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#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n\n\n\nfloat NdotV=clamp(dot(normalW,viewDirectionW),0.,1.)+0.00001;\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 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\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#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\nsurfaceRefractionColor*=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#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=surfaceRefractionColor;\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#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,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\nfinalSpecular*vLightingIntensity.x*vLightingIntensity.w +\n#endif\n#ifdef REFLECTION\nfinalRadiance*vLightingIntensity.z +\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*=result.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}","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 DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\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 DIFFUSE\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#ifdef AMBIENT\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#ifdef OPACITY\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#ifdef EMISSIVE\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#ifdef LIGHTMAP\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)\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#ifdef BUMP\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\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\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)\nvarying vec2 vSpecularUV;\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}"};
  48222. 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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\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#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \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;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\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#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 vec2 vMicrosurfaceTextureLods;\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 getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\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}","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;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\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\nvarying vec2 vBumpUV;\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};"};
  48223. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  48224. module.exports = BABYLON;
  48225. };