babylon.max.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276
  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 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * 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".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * 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".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. 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);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. 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]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. 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);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. 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);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. 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);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. 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);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. 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);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * 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".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * 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".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * 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".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * 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".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * 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.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * 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.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. 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);
  3554. };
  3555. /**
  3556. * 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.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * 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.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. 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);
  3576. };
  3577. /**
  3578. * 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.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * 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.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * 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.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. 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);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * 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.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. 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);
  3627. };
  3628. /**
  3629. * 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.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * 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.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. 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);
  3653. };
  3654. /**
  3655. * 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.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. 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);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * 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.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. 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;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. if (BABYLON.Tags) {
  4808. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4809. }
  4810. // Properties
  4811. for (var property in entity.__serializableMembers) {
  4812. var propertyDescriptor = entity.__serializableMembers[property];
  4813. var targetPropertyName = propertyDescriptor.sourceName || property;
  4814. var propertyType = propertyDescriptor.type;
  4815. var sourceProperty = entity[property];
  4816. if (sourceProperty !== undefined && sourceProperty !== null) {
  4817. switch (propertyType) {
  4818. case 0:
  4819. serializationObject[targetPropertyName] = sourceProperty;
  4820. break;
  4821. case 1:
  4822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4823. break;
  4824. case 2:
  4825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4826. break;
  4827. case 3:
  4828. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4829. break;
  4830. case 4:
  4831. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4832. break;
  4833. case 5:
  4834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4835. break;
  4836. case 6:
  4837. serializationObject[targetPropertyName] = sourceProperty.id;
  4838. break;
  4839. case 7:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. }
  4843. }
  4844. }
  4845. return serializationObject;
  4846. };
  4847. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4848. var destination = creationFunction();
  4849. // Tags
  4850. if (BABYLON.Tags) {
  4851. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4852. }
  4853. // Properties
  4854. for (var property in destination.__serializableMembers) {
  4855. var propertyDescriptor = destination.__serializableMembers[property];
  4856. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4857. var propertyType = propertyDescriptor.type;
  4858. if (sourceProperty !== undefined && sourceProperty !== null) {
  4859. switch (propertyType) {
  4860. case 0:
  4861. destination[property] = sourceProperty;
  4862. break;
  4863. case 1:
  4864. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4865. break;
  4866. case 2:
  4867. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4868. break;
  4869. case 3:
  4870. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4871. break;
  4872. case 4:
  4873. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4874. break;
  4875. case 5:
  4876. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4877. break;
  4878. case 6:
  4879. destination[property] = scene.getLastMeshByID(sourceProperty);
  4880. break;
  4881. case 7:
  4882. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. return destination;
  4888. };
  4889. SerializationHelper.Clone = function (creationFunction, source) {
  4890. var destination = creationFunction();
  4891. // Tags
  4892. if (BABYLON.Tags) {
  4893. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4894. }
  4895. // Properties
  4896. for (var property in destination.__serializableMembers) {
  4897. var propertyDescriptor = destination.__serializableMembers[property];
  4898. var sourceProperty = source[property];
  4899. var propertyType = propertyDescriptor.type;
  4900. if (sourceProperty !== undefined && sourceProperty !== null) {
  4901. switch (propertyType) {
  4902. case 0: // Value
  4903. case 6:
  4904. destination[property] = sourceProperty;
  4905. break;
  4906. case 1: // Texture
  4907. case 2: // Color3
  4908. case 3: // FresnelParameters
  4909. case 4: // Vector2
  4910. case 5: // Vector3
  4911. case 7:
  4912. destination[property] = sourceProperty.clone();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. return destination;
  4918. };
  4919. return SerializationHelper;
  4920. }());
  4921. BABYLON.SerializationHelper = SerializationHelper;
  4922. })(BABYLON || (BABYLON = {}));
  4923. //# sourceMappingURL=babylon.decorators.js.map
  4924. var BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * A class serves as a medium between the observable and its observers
  4928. */
  4929. var EventState = (function () {
  4930. /**
  4931. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4932. */
  4933. function EventState(mask, skipNextObservers) {
  4934. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4935. this.initalize(mask, skipNextObservers);
  4936. }
  4937. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4938. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4939. this.mask = mask;
  4940. this.skipNextObservers = skipNextObservers;
  4941. return this;
  4942. };
  4943. return EventState;
  4944. }());
  4945. BABYLON.EventState = EventState;
  4946. /**
  4947. * Represent an Observer registered to a given Observable object.
  4948. */
  4949. var Observer = (function () {
  4950. function Observer(callback, mask) {
  4951. this.callback = callback;
  4952. this.mask = mask;
  4953. }
  4954. return Observer;
  4955. }());
  4956. BABYLON.Observer = Observer;
  4957. /**
  4958. * The Observable class is a simple implementation of the Observable pattern.
  4959. * 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.
  4960. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4961. * 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).
  4962. * 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.
  4963. */
  4964. var Observable = (function () {
  4965. function Observable() {
  4966. this._observers = new Array();
  4967. this._eventState = new EventState(0);
  4968. }
  4969. /**
  4970. * Create a new Observer with the specified callback
  4971. * @param callback the callback that will be executed for that Observer
  4972. * @param mask the mask used to filter observers
  4973. * @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.
  4974. */
  4975. Observable.prototype.add = function (callback, mask, insertFirst) {
  4976. if (mask === void 0) { mask = -1; }
  4977. if (insertFirst === void 0) { insertFirst = false; }
  4978. if (!callback) {
  4979. return null;
  4980. }
  4981. var observer = new Observer(callback, mask);
  4982. if (insertFirst) {
  4983. this._observers.unshift(observer);
  4984. }
  4985. else {
  4986. this._observers.push(observer);
  4987. }
  4988. return observer;
  4989. };
  4990. /**
  4991. * Remove an Observer from the Observable object
  4992. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4993. */
  4994. Observable.prototype.remove = function (observer) {
  4995. var index = this._observers.indexOf(observer);
  4996. if (index !== -1) {
  4997. this._observers.splice(index, 1);
  4998. return true;
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Remove a callback from the Observable object
  5004. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5005. */
  5006. Observable.prototype.removeCallback = function (callback) {
  5007. for (var index = 0; index < this._observers.length; index++) {
  5008. if (this._observers[index].callback === callback) {
  5009. this._observers.splice(index, 1);
  5010. return true;
  5011. }
  5012. }
  5013. return false;
  5014. };
  5015. /**
  5016. * Notify all Observers by calling their respective callback with the given data
  5017. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5018. * @param eventData
  5019. * @param mask
  5020. */
  5021. Observable.prototype.notifyObservers = function (eventData, mask) {
  5022. if (mask === void 0) { mask = -1; }
  5023. var state = this._eventState;
  5024. state.mask = mask;
  5025. state.skipNextObservers = false;
  5026. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5027. var obs = _a[_i];
  5028. if (obs.mask & mask) {
  5029. obs.callback(eventData, state);
  5030. }
  5031. if (state.skipNextObservers) {
  5032. return false;
  5033. }
  5034. }
  5035. return true;
  5036. };
  5037. /**
  5038. * return true is the Observable has at least one Observer registered
  5039. */
  5040. Observable.prototype.hasObservers = function () {
  5041. return this._observers.length > 0;
  5042. };
  5043. /**
  5044. * Clear the list of observers
  5045. */
  5046. Observable.prototype.clear = function () {
  5047. this._observers = new Array();
  5048. };
  5049. /**
  5050. * Clone the current observable
  5051. */
  5052. Observable.prototype.clone = function () {
  5053. var result = new Observable();
  5054. result._observers = this._observers.slice(0);
  5055. return result;
  5056. };
  5057. /**
  5058. * Does this observable handles observer registered with a given mask
  5059. * @param {number} trigger - the mask to be tested
  5060. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5061. **/
  5062. Observable.prototype.hasSpecificMask = function (mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5065. var obs = _a[_i];
  5066. if (obs.mask & mask && obs.mask === mask) {
  5067. return true;
  5068. }
  5069. }
  5070. return false;
  5071. };
  5072. return Observable;
  5073. }());
  5074. BABYLON.Observable = Observable;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.observable.js.map
  5077. var BABYLON;
  5078. (function (BABYLON) {
  5079. var SmartArray = (function () {
  5080. function SmartArray(capacity) {
  5081. this.length = 0;
  5082. this._duplicateId = 0;
  5083. this.data = new Array(capacity);
  5084. this._id = SmartArray._GlobalId++;
  5085. }
  5086. SmartArray.prototype.push = function (value) {
  5087. this.data[this.length++] = value;
  5088. if (this.length > this.data.length) {
  5089. this.data.length *= 2;
  5090. }
  5091. if (!value.__smartArrayFlags) {
  5092. value.__smartArrayFlags = {};
  5093. }
  5094. value.__smartArrayFlags[this._id] = this._duplicateId;
  5095. };
  5096. SmartArray.prototype.forEach = function (func) {
  5097. for (var index = 0; index < this.length; index++) {
  5098. func(this.data[index]);
  5099. }
  5100. };
  5101. SmartArray.prototype.pushNoDuplicate = function (value) {
  5102. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5103. return false;
  5104. }
  5105. this.push(value);
  5106. return true;
  5107. };
  5108. SmartArray.prototype.sort = function (compareFn) {
  5109. this.data.sort(compareFn);
  5110. };
  5111. SmartArray.prototype.reset = function () {
  5112. this.length = 0;
  5113. this._duplicateId++;
  5114. };
  5115. SmartArray.prototype.dispose = function () {
  5116. this.reset();
  5117. this.data.length = 0;
  5118. };
  5119. SmartArray.prototype.concat = function (array) {
  5120. if (array.length === 0) {
  5121. return;
  5122. }
  5123. if (this.length + array.length > this.data.length) {
  5124. this.data.length = (this.length + array.length) * 2;
  5125. }
  5126. for (var index = 0; index < array.length; index++) {
  5127. this.data[this.length++] = (array.data || array)[index];
  5128. }
  5129. };
  5130. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5131. if (array.length === 0) {
  5132. return;
  5133. }
  5134. if (this.length + array.length > this.data.length) {
  5135. this.data.length = (this.length + array.length) * 2;
  5136. }
  5137. for (var index = 0; index < array.length; index++) {
  5138. var item = (array.data || array)[index];
  5139. this.pushNoDuplicate(item);
  5140. }
  5141. };
  5142. SmartArray.prototype.indexOf = function (value) {
  5143. var position = this.data.indexOf(value);
  5144. if (position >= this.length) {
  5145. return -1;
  5146. }
  5147. return position;
  5148. };
  5149. SmartArray.prototype.contains = function (value) {
  5150. return this.data.indexOf(value) !== -1;
  5151. };
  5152. return SmartArray;
  5153. }());
  5154. // Statics
  5155. SmartArray._GlobalId = 0;
  5156. BABYLON.SmartArray = SmartArray;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.smartArray.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. // Screenshots
  5162. var screenshotCanvas;
  5163. var cloneValue = function (source, destinationObject) {
  5164. if (!source)
  5165. return null;
  5166. if (source instanceof BABYLON.Mesh) {
  5167. return null;
  5168. }
  5169. if (source instanceof BABYLON.SubMesh) {
  5170. return source.clone(destinationObject);
  5171. }
  5172. else if (source.clone) {
  5173. return source.clone();
  5174. }
  5175. return null;
  5176. };
  5177. var Tools = (function () {
  5178. function Tools() {
  5179. }
  5180. ;
  5181. /**
  5182. * Interpolates between a and b via alpha
  5183. * @param a The lower value (returned when alpha = 0)
  5184. * @param b The upper value (returned when alpha = 1)
  5185. * @param alpha The interpolation-factor
  5186. * @return The mixed value
  5187. */
  5188. Tools.Mix = function (a, b, alpha) {
  5189. return a * (1 - alpha) + b * alpha;
  5190. };
  5191. Tools.Instantiate = function (className) {
  5192. var arr = className.split(".");
  5193. var fn = (window || this);
  5194. for (var i = 0, len = arr.length; i < len; i++) {
  5195. fn = fn[arr[i]];
  5196. }
  5197. if (typeof fn !== "function") {
  5198. return null;
  5199. }
  5200. return fn;
  5201. };
  5202. Tools.SetImmediate = function (action) {
  5203. if (window.setImmediate) {
  5204. window.setImmediate(action);
  5205. }
  5206. else {
  5207. setTimeout(action, 1);
  5208. }
  5209. };
  5210. Tools.IsExponentOfTwo = function (value) {
  5211. var count = 1;
  5212. do {
  5213. count *= 2;
  5214. } while (count < value);
  5215. return count === value;
  5216. };
  5217. /**
  5218. * Find the next highest power of two.
  5219. * @param x Number to start search from.
  5220. * @return Next highest power of two.
  5221. */
  5222. Tools.CeilingPOT = function (x) {
  5223. x--;
  5224. x |= x >> 1;
  5225. x |= x >> 2;
  5226. x |= x >> 4;
  5227. x |= x >> 8;
  5228. x |= x >> 16;
  5229. x++;
  5230. return x;
  5231. };
  5232. /**
  5233. * Find the next lowest power of two.
  5234. * @param x Number to start search from.
  5235. * @return Next lowest power of two.
  5236. */
  5237. Tools.FloorPOT = function (x) {
  5238. x = x | (x >> 1);
  5239. x = x | (x >> 2);
  5240. x = x | (x >> 4);
  5241. x = x | (x >> 8);
  5242. x = x | (x >> 16);
  5243. return x - (x >> 1);
  5244. };
  5245. /**
  5246. * Find the nearest power of two.
  5247. * @param x Number to start search from.
  5248. * @return Next nearest power of two.
  5249. */
  5250. Tools.NearestPOT = function (x) {
  5251. var c = Tools.CeilingPOT(x);
  5252. var f = Tools.FloorPOT(x);
  5253. return (c - x) > (x - f) ? f : c;
  5254. };
  5255. Tools.GetExponentOfTwo = function (value, max, mode) {
  5256. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5257. var pot;
  5258. switch (mode) {
  5259. case BABYLON.Engine.SCALEMODE_FLOOR:
  5260. pot = Tools.FloorPOT(value);
  5261. break;
  5262. case BABYLON.Engine.SCALEMODE_NEAREST:
  5263. pot = Tools.NearestPOT(value);
  5264. break;
  5265. case BABYLON.Engine.SCALEMODE_CEILING:
  5266. pot = Tools.CeilingPOT(value);
  5267. break;
  5268. }
  5269. return Math.min(pot, max);
  5270. };
  5271. Tools.GetFilename = function (path) {
  5272. var index = path.lastIndexOf("/");
  5273. if (index < 0)
  5274. return path;
  5275. return path.substring(index + 1);
  5276. };
  5277. Tools.GetDOMTextContent = function (element) {
  5278. var result = "";
  5279. var child = element.firstChild;
  5280. while (child) {
  5281. if (child.nodeType === 3) {
  5282. result += child.textContent;
  5283. }
  5284. child = child.nextSibling;
  5285. }
  5286. return result;
  5287. };
  5288. Tools.ToDegrees = function (angle) {
  5289. return angle * 180 / Math.PI;
  5290. };
  5291. Tools.ToRadians = function (angle) {
  5292. return angle * Math.PI / 180;
  5293. };
  5294. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5295. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5296. var output = "";
  5297. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5298. var i = 0;
  5299. var bytes = new Uint8Array(buffer);
  5300. while (i < bytes.length) {
  5301. chr1 = bytes[i++];
  5302. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5303. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5304. enc1 = chr1 >> 2;
  5305. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5306. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5307. enc4 = chr3 & 63;
  5308. if (isNaN(chr2)) {
  5309. enc3 = enc4 = 64;
  5310. }
  5311. else if (isNaN(chr3)) {
  5312. enc4 = 64;
  5313. }
  5314. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5315. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5316. }
  5317. return "data:image/png;base64," + output;
  5318. };
  5319. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5320. if (bias === void 0) { bias = null; }
  5321. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5322. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5323. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5324. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5325. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5326. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5327. }
  5328. if (bias) {
  5329. minimum.x -= minimum.x * bias.x + bias.y;
  5330. minimum.y -= minimum.y * bias.x + bias.y;
  5331. minimum.z -= minimum.z * bias.x + bias.y;
  5332. maximum.x += maximum.x * bias.x + bias.y;
  5333. maximum.y += maximum.y * bias.x + bias.y;
  5334. maximum.z += maximum.z * bias.x + bias.y;
  5335. }
  5336. return {
  5337. minimum: minimum,
  5338. maximum: maximum
  5339. };
  5340. };
  5341. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5342. if (bias === void 0) { bias = null; }
  5343. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5344. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5345. if (!stride) {
  5346. stride = 3;
  5347. }
  5348. for (var index = start; index < start + count; index++) {
  5349. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5350. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5351. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5352. }
  5353. if (bias) {
  5354. minimum.x -= minimum.x * bias.x + bias.y;
  5355. minimum.y -= minimum.y * bias.x + bias.y;
  5356. minimum.z -= minimum.z * bias.x + bias.y;
  5357. maximum.x += maximum.x * bias.x + bias.y;
  5358. maximum.y += maximum.y * bias.x + bias.y;
  5359. maximum.z += maximum.z * bias.x + bias.y;
  5360. }
  5361. return {
  5362. minimum: minimum,
  5363. maximum: maximum
  5364. };
  5365. };
  5366. Tools.Vector2ArrayFeeder = function (array) {
  5367. return function (index) {
  5368. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5369. var length = isFloatArray ? array.length / 2 : array.length;
  5370. if (index >= length) {
  5371. return null;
  5372. }
  5373. if (isFloatArray) {
  5374. var fa = array;
  5375. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5376. }
  5377. var a = array;
  5378. return a[index];
  5379. };
  5380. };
  5381. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5382. if (bias === void 0) { bias = null; }
  5383. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5384. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5385. var i = 0;
  5386. var cur = feeder(i++);
  5387. while (cur) {
  5388. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5389. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5390. cur = feeder(i++);
  5391. }
  5392. if (bias) {
  5393. minimum.x -= minimum.x * bias.x + bias.y;
  5394. minimum.y -= minimum.y * bias.x + bias.y;
  5395. maximum.x += maximum.x * bias.x + bias.y;
  5396. maximum.y += maximum.y * bias.x + bias.y;
  5397. }
  5398. return {
  5399. minimum: minimum,
  5400. maximum: maximum
  5401. };
  5402. };
  5403. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5404. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5405. return undefined;
  5406. return Array.isArray(obj) ? obj : [obj];
  5407. };
  5408. // Misc.
  5409. Tools.GetPointerPrefix = function () {
  5410. var eventPrefix = "pointer";
  5411. // Check if pointer events are supported
  5412. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5413. eventPrefix = "mouse";
  5414. }
  5415. return eventPrefix;
  5416. };
  5417. /**
  5418. * @param func - the function to be called
  5419. * @param requester - the object that will request the next frame. Falls back to window.
  5420. */
  5421. Tools.QueueNewFrame = function (func, requester) {
  5422. if (requester === void 0) { requester = window; }
  5423. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5424. /*if(requester.isPresenting) {
  5425. return;
  5426. } else*/ if (requester.requestAnimationFrame)
  5427. requester.requestAnimationFrame(func);
  5428. else if (requester.msRequestAnimationFrame)
  5429. requester.msRequestAnimationFrame(func);
  5430. else if (requester.webkitRequestAnimationFrame)
  5431. requester.webkitRequestAnimationFrame(func);
  5432. else if (requester.mozRequestAnimationFrame)
  5433. requester.mozRequestAnimationFrame(func);
  5434. else if (requester.oRequestAnimationFrame)
  5435. requester.oRequestAnimationFrame(func);
  5436. else {
  5437. window.setTimeout(func, 16);
  5438. }
  5439. };
  5440. Tools.RequestFullscreen = function (element) {
  5441. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5442. if (!requestFunction)
  5443. return;
  5444. requestFunction.call(element);
  5445. };
  5446. Tools.ExitFullscreen = function () {
  5447. if (document.exitFullscreen) {
  5448. document.exitFullscreen();
  5449. }
  5450. else if (document.mozCancelFullScreen) {
  5451. document.mozCancelFullScreen();
  5452. }
  5453. else if (document.webkitCancelFullScreen) {
  5454. document.webkitCancelFullScreen();
  5455. }
  5456. else if (document.msCancelFullScreen) {
  5457. document.msCancelFullScreen();
  5458. }
  5459. };
  5460. Tools.SetCorsBehavior = function (url, img) {
  5461. if (Tools.CorsBehavior) {
  5462. switch (typeof (Tools.CorsBehavior)) {
  5463. case "function":
  5464. var result = Tools.CorsBehavior(url);
  5465. if (result) {
  5466. img.crossOrigin = result;
  5467. }
  5468. break;
  5469. case "string":
  5470. default:
  5471. img.crossOrigin = Tools.CorsBehavior;
  5472. break;
  5473. }
  5474. }
  5475. };
  5476. // External files
  5477. Tools.CleanUrl = function (url) {
  5478. url = url.replace(/#/mg, "%23");
  5479. return url;
  5480. };
  5481. Tools.LoadImage = function (url, onload, onerror, database) {
  5482. if (url instanceof ArrayBuffer) {
  5483. url = Tools.EncodeArrayBufferTobase64(url);
  5484. }
  5485. url = Tools.CleanUrl(url);
  5486. var img = new Image();
  5487. if (url.substr(0, 5) !== "data:") {
  5488. Tools.SetCorsBehavior(url, img);
  5489. }
  5490. img.onload = function () {
  5491. onload(img);
  5492. };
  5493. img.onerror = function (err) {
  5494. Tools.Error("Error while trying to load image: " + url);
  5495. if (Tools.UseFallbackTexture) {
  5496. img.src = Tools.fallbackTexture;
  5497. onload(img);
  5498. }
  5499. else {
  5500. onerror();
  5501. }
  5502. };
  5503. var noIndexedDB = function () {
  5504. img.src = url;
  5505. };
  5506. var loadFromIndexedDB = function () {
  5507. database.loadImageFromDB(url, img);
  5508. };
  5509. //ANY database to do!
  5510. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5511. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5512. }
  5513. else {
  5514. if (url.indexOf("file:") !== 0) {
  5515. noIndexedDB();
  5516. }
  5517. else {
  5518. var textureName = url.substring(5).toLowerCase();
  5519. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5520. try {
  5521. var blobURL;
  5522. try {
  5523. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5524. }
  5525. catch (ex) {
  5526. // Chrome doesn't support oneTimeOnly parameter
  5527. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5528. }
  5529. img.src = blobURL;
  5530. }
  5531. catch (e) {
  5532. img.src = null;
  5533. }
  5534. }
  5535. else {
  5536. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5537. img.src = Tools.fallbackTexture;
  5538. }
  5539. }
  5540. }
  5541. return img;
  5542. };
  5543. //ANY
  5544. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5545. url = Tools.CleanUrl(url);
  5546. var noIndexedDB = function () {
  5547. var request = new XMLHttpRequest();
  5548. var loadUrl = Tools.BaseUrl + url;
  5549. request.open('GET', loadUrl, true);
  5550. if (useArrayBuffer) {
  5551. request.responseType = "arraybuffer";
  5552. }
  5553. request.onprogress = progressCallBack;
  5554. request.onreadystatechange = function () {
  5555. // In case of undefined state in some browsers.
  5556. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5557. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5558. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5559. callback(!useArrayBuffer ? request.responseText : request.response);
  5560. }
  5561. else {
  5562. if (onError) {
  5563. onError(request);
  5564. }
  5565. else {
  5566. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5567. }
  5568. }
  5569. }
  5570. };
  5571. request.send(null);
  5572. };
  5573. var loadFromIndexedDB = function () {
  5574. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5575. };
  5576. if (url.indexOf("file:") !== -1) {
  5577. var fileName = url.substring(5).toLowerCase();
  5578. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5579. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5580. }
  5581. else {
  5582. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5583. }
  5584. }
  5585. else {
  5586. // Caching all files
  5587. if (database && database.enableSceneOffline) {
  5588. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5589. }
  5590. else {
  5591. noIndexedDB();
  5592. }
  5593. }
  5594. };
  5595. /**
  5596. * Load a script (identified by an url). When the url returns, the
  5597. * content of this file is added into a new script element, attached to the DOM (body element)
  5598. */
  5599. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5600. var head = document.getElementsByTagName('head')[0];
  5601. var script = document.createElement('script');
  5602. script.type = 'text/javascript';
  5603. script.src = scriptUrl;
  5604. var self = this;
  5605. script.onload = function () {
  5606. if (onSuccess) {
  5607. onSuccess();
  5608. }
  5609. };
  5610. script.onerror = function () {
  5611. if (onError) {
  5612. onError();
  5613. }
  5614. };
  5615. head.appendChild(script);
  5616. };
  5617. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5618. var reader = new FileReader();
  5619. reader.onload = function (e) {
  5620. //target doesn't have result from ts 1.3
  5621. callback(e.target['result']);
  5622. };
  5623. reader.onprogress = progressCallback;
  5624. reader.readAsDataURL(fileToLoad);
  5625. };
  5626. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5627. var reader = new FileReader();
  5628. reader.onerror = function (e) {
  5629. Tools.Log("Error while reading file: " + fileToLoad.name);
  5630. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5631. };
  5632. reader.onload = function (e) {
  5633. //target doesn't have result from ts 1.3
  5634. callback(e.target['result']);
  5635. };
  5636. reader.onprogress = progressCallBack;
  5637. if (!useArrayBuffer) {
  5638. // Asynchronous read
  5639. reader.readAsText(fileToLoad);
  5640. }
  5641. else {
  5642. reader.readAsArrayBuffer(fileToLoad);
  5643. }
  5644. };
  5645. //returns a downloadable url to a file content.
  5646. Tools.FileAsURL = function (content) {
  5647. var fileBlob = new Blob([content]);
  5648. var url = window.URL || window.webkitURL;
  5649. var link = url.createObjectURL(fileBlob);
  5650. return link;
  5651. };
  5652. // Misc.
  5653. Tools.Format = function (value, decimals) {
  5654. if (decimals === void 0) { decimals = 2; }
  5655. return value.toFixed(decimals);
  5656. };
  5657. Tools.CheckExtends = function (v, min, max) {
  5658. if (v.x < min.x)
  5659. min.x = v.x;
  5660. if (v.y < min.y)
  5661. min.y = v.y;
  5662. if (v.z < min.z)
  5663. min.z = v.z;
  5664. if (v.x > max.x)
  5665. max.x = v.x;
  5666. if (v.y > max.y)
  5667. max.y = v.y;
  5668. if (v.z > max.z)
  5669. max.z = v.z;
  5670. };
  5671. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5672. for (var prop in source) {
  5673. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5674. continue;
  5675. }
  5676. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5677. continue;
  5678. }
  5679. var sourceValue = source[prop];
  5680. var typeOfSourceValue = typeof sourceValue;
  5681. if (typeOfSourceValue === "function") {
  5682. continue;
  5683. }
  5684. if (typeOfSourceValue === "object") {
  5685. if (sourceValue instanceof Array) {
  5686. destination[prop] = [];
  5687. if (sourceValue.length > 0) {
  5688. if (typeof sourceValue[0] == "object") {
  5689. for (var index = 0; index < sourceValue.length; index++) {
  5690. var clonedValue = cloneValue(sourceValue[index], destination);
  5691. if (destination[prop].indexOf(clonedValue) === -1) {
  5692. destination[prop].push(clonedValue);
  5693. }
  5694. }
  5695. }
  5696. else {
  5697. destination[prop] = sourceValue.slice(0);
  5698. }
  5699. }
  5700. }
  5701. else {
  5702. destination[prop] = cloneValue(sourceValue, destination);
  5703. }
  5704. }
  5705. else {
  5706. destination[prop] = sourceValue;
  5707. }
  5708. }
  5709. };
  5710. Tools.IsEmpty = function (obj) {
  5711. for (var i in obj) {
  5712. return false;
  5713. }
  5714. return true;
  5715. };
  5716. Tools.RegisterTopRootEvents = function (events) {
  5717. for (var index = 0; index < events.length; index++) {
  5718. var event = events[index];
  5719. window.addEventListener(event.name, event.handler, false);
  5720. try {
  5721. if (window.parent) {
  5722. window.parent.addEventListener(event.name, event.handler, false);
  5723. }
  5724. }
  5725. catch (e) {
  5726. // Silently fails...
  5727. }
  5728. }
  5729. };
  5730. Tools.UnregisterTopRootEvents = function (events) {
  5731. for (var index = 0; index < events.length; index++) {
  5732. var event = events[index];
  5733. window.removeEventListener(event.name, event.handler);
  5734. try {
  5735. if (window.parent) {
  5736. window.parent.removeEventListener(event.name, event.handler);
  5737. }
  5738. }
  5739. catch (e) {
  5740. // Silently fails...
  5741. }
  5742. }
  5743. };
  5744. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5745. if (mimeType === void 0) { mimeType = "image/png"; }
  5746. // Read the contents of the framebuffer
  5747. var numberOfChannelsByLine = width * 4;
  5748. var halfHeight = height / 2;
  5749. //Reading datas from WebGL
  5750. var data = engine.readPixels(0, 0, width, height);
  5751. //To flip image on Y axis.
  5752. for (var i = 0; i < halfHeight; i++) {
  5753. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5754. var currentCell = j + i * numberOfChannelsByLine;
  5755. var targetLine = height - i - 1;
  5756. var targetCell = j + targetLine * numberOfChannelsByLine;
  5757. var temp = data[currentCell];
  5758. data[currentCell] = data[targetCell];
  5759. data[targetCell] = temp;
  5760. }
  5761. }
  5762. // Create a 2D canvas to store the result
  5763. if (!screenshotCanvas) {
  5764. screenshotCanvas = document.createElement('canvas');
  5765. }
  5766. screenshotCanvas.width = width;
  5767. screenshotCanvas.height = height;
  5768. var context = screenshotCanvas.getContext('2d');
  5769. // Copy the pixels to a 2D canvas
  5770. var imageData = context.createImageData(width, height);
  5771. var castData = (imageData.data);
  5772. castData.set(data);
  5773. context.putImageData(imageData, 0, 0);
  5774. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5775. };
  5776. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5777. if (mimeType === void 0) { mimeType = "image/png"; }
  5778. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5779. if (successCallback) {
  5780. successCallback(base64Image);
  5781. }
  5782. else {
  5783. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5784. if (("download" in document.createElement("a"))) {
  5785. var a = window.document.createElement("a");
  5786. a.href = base64Image;
  5787. var date = new Date();
  5788. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5789. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5790. window.document.body.appendChild(a);
  5791. a.addEventListener("click", function () {
  5792. a.parentElement.removeChild(a);
  5793. });
  5794. a.click();
  5795. //Or opening a new tab with the image if it is not possible to automatically start download.
  5796. }
  5797. else {
  5798. var newWindow = window.open("");
  5799. var img = newWindow.document.createElement("img");
  5800. img.src = base64Image;
  5801. newWindow.document.body.appendChild(img);
  5802. }
  5803. }
  5804. };
  5805. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5806. if (mimeType === void 0) { mimeType = "image/png"; }
  5807. var width;
  5808. var height;
  5809. // If a precision value is specified
  5810. if (size.precision) {
  5811. width = Math.round(engine.getRenderWidth() * size.precision);
  5812. height = Math.round(width / engine.getAspectRatio(camera));
  5813. }
  5814. else if (size.width && size.height) {
  5815. width = size.width;
  5816. height = size.height;
  5817. }
  5818. else if (size.width && !size.height) {
  5819. width = size.width;
  5820. height = Math.round(width / engine.getAspectRatio(camera));
  5821. }
  5822. else if (size.height && !size.width) {
  5823. height = size.height;
  5824. width = Math.round(height * engine.getAspectRatio(camera));
  5825. }
  5826. else if (!isNaN(size)) {
  5827. height = size;
  5828. width = size;
  5829. }
  5830. else {
  5831. Tools.Error("Invalid 'size' parameter !");
  5832. return;
  5833. }
  5834. if (!screenshotCanvas) {
  5835. screenshotCanvas = document.createElement('canvas');
  5836. }
  5837. screenshotCanvas.width = width;
  5838. screenshotCanvas.height = height;
  5839. var renderContext = screenshotCanvas.getContext("2d");
  5840. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5841. var newWidth = width;
  5842. var newHeight = newWidth / ratio;
  5843. if (newHeight > height) {
  5844. newHeight = height;
  5845. newWidth = newHeight * ratio;
  5846. }
  5847. var offsetX = Math.max(0, width - newWidth) / 2;
  5848. var offsetY = Math.max(0, height - newHeight) / 2;
  5849. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5850. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5851. };
  5852. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5853. if (mimeType === void 0) { mimeType = "image/png"; }
  5854. if (samples === void 0) { samples = 1; }
  5855. var width;
  5856. var height;
  5857. //If a precision value is specified
  5858. if (size.precision) {
  5859. width = Math.round(engine.getRenderWidth() * size.precision);
  5860. height = Math.round(width / engine.getAspectRatio(camera));
  5861. size = { width: width, height: height };
  5862. }
  5863. else if (size.width && size.height) {
  5864. width = size.width;
  5865. height = size.height;
  5866. }
  5867. else if (size.width && !size.height) {
  5868. width = size.width;
  5869. height = Math.round(width / engine.getAspectRatio(camera));
  5870. size = { width: width, height: height };
  5871. }
  5872. else if (size.height && !size.width) {
  5873. height = size.height;
  5874. width = Math.round(height * engine.getAspectRatio(camera));
  5875. size = { width: width, height: height };
  5876. }
  5877. else if (!isNaN(size)) {
  5878. height = size;
  5879. width = size;
  5880. }
  5881. else {
  5882. Tools.Error("Invalid 'size' parameter !");
  5883. return;
  5884. }
  5885. var scene = camera.getScene();
  5886. var previousCamera = null;
  5887. if (scene.activeCamera !== camera) {
  5888. previousCamera = scene.activeCamera;
  5889. scene.activeCamera = camera;
  5890. }
  5891. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5892. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5893. texture.renderList = scene.meshes;
  5894. texture.samples = samples;
  5895. texture.onAfterRenderObservable.add(function () {
  5896. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5897. });
  5898. scene.incrementRenderId();
  5899. scene.resetCachedMaterial();
  5900. texture.render(true);
  5901. texture.dispose();
  5902. if (previousCamera) {
  5903. scene.activeCamera = previousCamera;
  5904. }
  5905. camera.getProjectionMatrix(true); // Force cache refresh;
  5906. };
  5907. // XHR response validator for local file scenario
  5908. Tools.ValidateXHRData = function (xhr, dataType) {
  5909. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5910. if (dataType === void 0) { dataType = 7; }
  5911. try {
  5912. if (dataType & 1) {
  5913. if (xhr.responseText && xhr.responseText.length > 0) {
  5914. return true;
  5915. }
  5916. else if (dataType === 1) {
  5917. return false;
  5918. }
  5919. }
  5920. if (dataType & 2) {
  5921. // Check header width and height since there is no "TGA" magic number
  5922. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5923. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5924. return true;
  5925. }
  5926. else if (dataType === 2) {
  5927. return false;
  5928. }
  5929. }
  5930. if (dataType & 4) {
  5931. // Check for the "DDS" magic number
  5932. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5933. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5934. return true;
  5935. }
  5936. else {
  5937. return false;
  5938. }
  5939. }
  5940. }
  5941. catch (e) {
  5942. // Global protection
  5943. }
  5944. return false;
  5945. };
  5946. /**
  5947. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5948. * Be aware Math.random() could cause collisions, but:
  5949. * "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"
  5950. */
  5951. Tools.RandomId = function () {
  5952. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5953. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5954. return v.toString(16);
  5955. });
  5956. };
  5957. Object.defineProperty(Tools, "NoneLogLevel", {
  5958. get: function () {
  5959. return Tools._NoneLogLevel;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(Tools, "MessageLogLevel", {
  5965. get: function () {
  5966. return Tools._MessageLogLevel;
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "WarningLogLevel", {
  5972. get: function () {
  5973. return Tools._WarningLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "ErrorLogLevel", {
  5979. get: function () {
  5980. return Tools._ErrorLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "AllLogLevel", {
  5986. get: function () {
  5987. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Tools._AddLogEntry = function (entry) {
  5993. Tools._LogCache = entry + Tools._LogCache;
  5994. if (Tools.OnNewCacheEntry) {
  5995. Tools.OnNewCacheEntry(entry);
  5996. }
  5997. };
  5998. Tools._FormatMessage = function (message) {
  5999. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6000. var date = new Date();
  6001. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6002. };
  6003. Tools._LogDisabled = function (message) {
  6004. // nothing to do
  6005. };
  6006. Tools._LogEnabled = function (message) {
  6007. var formattedMessage = Tools._FormatMessage(message);
  6008. console.log("BJS - " + formattedMessage);
  6009. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6010. Tools._AddLogEntry(entry);
  6011. };
  6012. Tools._WarnDisabled = function (message) {
  6013. // nothing to do
  6014. };
  6015. Tools._WarnEnabled = function (message) {
  6016. var formattedMessage = Tools._FormatMessage(message);
  6017. console.warn("BJS - " + formattedMessage);
  6018. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6019. Tools._AddLogEntry(entry);
  6020. };
  6021. Tools._ErrorDisabled = function (message) {
  6022. // nothing to do
  6023. };
  6024. Tools._ErrorEnabled = function (message) {
  6025. Tools.errorsCount++;
  6026. var formattedMessage = Tools._FormatMessage(message);
  6027. console.error("BJS - " + formattedMessage);
  6028. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6029. Tools._AddLogEntry(entry);
  6030. };
  6031. Object.defineProperty(Tools, "LogCache", {
  6032. get: function () {
  6033. return Tools._LogCache;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Tools.ClearLogCache = function () {
  6039. Tools._LogCache = "";
  6040. Tools.errorsCount = 0;
  6041. };
  6042. Object.defineProperty(Tools, "LogLevels", {
  6043. set: function (level) {
  6044. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6045. Tools.Log = Tools._LogEnabled;
  6046. }
  6047. else {
  6048. Tools.Log = Tools._LogDisabled;
  6049. }
  6050. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6051. Tools.Warn = Tools._WarnEnabled;
  6052. }
  6053. else {
  6054. Tools.Warn = Tools._WarnDisabled;
  6055. }
  6056. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6057. Tools.Error = Tools._ErrorEnabled;
  6058. }
  6059. else {
  6060. Tools.Error = Tools._ErrorDisabled;
  6061. }
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6067. get: function () {
  6068. return Tools._PerformanceNoneLogLevel;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6074. get: function () {
  6075. return Tools._PerformanceUserMarkLogLevel;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6081. get: function () {
  6082. return Tools._PerformanceConsoleLogLevel;
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6088. set: function (level) {
  6089. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6090. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6091. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6092. return;
  6093. }
  6094. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6095. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6096. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6097. return;
  6098. }
  6099. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6100. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6106. };
  6107. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6108. };
  6109. Tools._StartUserMark = function (counterName, condition) {
  6110. if (condition === void 0) { condition = true; }
  6111. if (!condition || !Tools._performance.mark) {
  6112. return;
  6113. }
  6114. Tools._performance.mark(counterName + "-Begin");
  6115. };
  6116. Tools._EndUserMark = function (counterName, condition) {
  6117. if (condition === void 0) { condition = true; }
  6118. if (!condition || !Tools._performance.mark) {
  6119. return;
  6120. }
  6121. Tools._performance.mark(counterName + "-End");
  6122. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6123. };
  6124. Tools._StartPerformanceConsole = function (counterName, condition) {
  6125. if (condition === void 0) { condition = true; }
  6126. if (!condition) {
  6127. return;
  6128. }
  6129. Tools._StartUserMark(counterName, condition);
  6130. if (console.time) {
  6131. console.time(counterName);
  6132. }
  6133. };
  6134. Tools._EndPerformanceConsole = function (counterName, condition) {
  6135. if (condition === void 0) { condition = true; }
  6136. if (!condition) {
  6137. return;
  6138. }
  6139. Tools._EndUserMark(counterName, condition);
  6140. if (console.time) {
  6141. console.timeEnd(counterName);
  6142. }
  6143. };
  6144. Object.defineProperty(Tools, "Now", {
  6145. get: function () {
  6146. if (window.performance && window.performance.now) {
  6147. return window.performance.now();
  6148. }
  6149. return new Date().getTime();
  6150. },
  6151. enumerable: true,
  6152. configurable: true
  6153. });
  6154. /**
  6155. * This method will return the name of the class used to create the instance of the given object.
  6156. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6157. * @param object the object to get the class name from
  6158. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6159. */
  6160. Tools.getClassName = function (object, isType) {
  6161. if (isType === void 0) { isType = false; }
  6162. var name = null;
  6163. if (!isType && object.getClassName) {
  6164. name = object.getClassName();
  6165. }
  6166. else {
  6167. if (object instanceof Object) {
  6168. var classObj = isType ? object : Object.getPrototypeOf(object);
  6169. name = classObj.constructor["__bjsclassName__"];
  6170. }
  6171. if (!name) {
  6172. name = typeof object;
  6173. }
  6174. }
  6175. return name;
  6176. };
  6177. Tools.first = function (array, predicate) {
  6178. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6179. var el = array_1[_i];
  6180. if (predicate(el)) {
  6181. return el;
  6182. }
  6183. }
  6184. };
  6185. /**
  6186. * This method will return the name of the full name of the class, including its owning module (if any).
  6187. * 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).
  6188. * @param object the object to get the class name from
  6189. * @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.
  6190. */
  6191. Tools.getFullClassName = function (object, isType) {
  6192. if (isType === void 0) { isType = false; }
  6193. var className = null;
  6194. var moduleName = null;
  6195. if (!isType && object.getClassName) {
  6196. className = object.getClassName();
  6197. }
  6198. else {
  6199. if (object instanceof Object) {
  6200. var classObj = isType ? object : Object.getPrototypeOf(object);
  6201. className = classObj.constructor["__bjsclassName__"];
  6202. moduleName = classObj.constructor["__bjsmoduleName__"];
  6203. }
  6204. if (!className) {
  6205. className = typeof object;
  6206. }
  6207. }
  6208. if (!className) {
  6209. return null;
  6210. }
  6211. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6212. };
  6213. /**
  6214. * 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.
  6215. * @param array
  6216. */
  6217. Tools.arrayOrStringFeeder = function (array) {
  6218. return function (index) {
  6219. if (index >= array.length) {
  6220. return null;
  6221. }
  6222. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6223. if (val && val.getHashCode) {
  6224. val = val.getHashCode();
  6225. }
  6226. if (typeof val === "string") {
  6227. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6228. }
  6229. return val;
  6230. };
  6231. };
  6232. /**
  6233. * Compute the hashCode of a stream of number
  6234. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6235. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6236. * @return the hash code computed
  6237. */
  6238. Tools.hashCodeFromStream = function (feeder) {
  6239. // Based from here: http://stackoverflow.com/a/7616484/802124
  6240. var hash = 0;
  6241. var index = 0;
  6242. var chr = feeder(index++);
  6243. while (chr != null) {
  6244. hash = ((hash << 5) - hash) + chr;
  6245. hash |= 0; // Convert to 32bit integer
  6246. chr = feeder(index++);
  6247. }
  6248. return hash;
  6249. };
  6250. return Tools;
  6251. }());
  6252. Tools.BaseUrl = "";
  6253. Tools.CorsBehavior = "anonymous";
  6254. Tools.UseFallbackTexture = true;
  6255. // Used in case of a texture loading problem
  6256. 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";
  6257. // Logs
  6258. Tools._NoneLogLevel = 0;
  6259. Tools._MessageLogLevel = 1;
  6260. Tools._WarningLogLevel = 2;
  6261. Tools._ErrorLogLevel = 4;
  6262. Tools._LogCache = "";
  6263. Tools.errorsCount = 0;
  6264. Tools.Log = Tools._LogEnabled;
  6265. Tools.Warn = Tools._WarnEnabled;
  6266. Tools.Error = Tools._ErrorEnabled;
  6267. // Performances
  6268. Tools._PerformanceNoneLogLevel = 0;
  6269. Tools._PerformanceUserMarkLogLevel = 1;
  6270. Tools._PerformanceConsoleLogLevel = 2;
  6271. Tools._performance = window.performance;
  6272. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6273. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6274. BABYLON.Tools = Tools;
  6275. /**
  6276. * This class is used to track a performance counter which is number based.
  6277. * The user has access to many properties which give statistics of different nature
  6278. *
  6279. * The implementer can track two kinds of Performance Counter: time and count
  6280. * 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.
  6281. * 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.
  6282. */
  6283. var PerfCounter = (function () {
  6284. function PerfCounter() {
  6285. this._startMonitoringTime = 0;
  6286. this._min = 0;
  6287. this._max = 0;
  6288. this._average = 0;
  6289. this._lastSecAverage = 0;
  6290. this._current = 0;
  6291. this._totalValueCount = 0;
  6292. this._totalAccumulated = 0;
  6293. this._lastSecAccumulated = 0;
  6294. this._lastSecTime = 0;
  6295. this._lastSecValueCount = 0;
  6296. }
  6297. Object.defineProperty(PerfCounter.prototype, "min", {
  6298. /**
  6299. * Returns the smallest value ever
  6300. */
  6301. get: function () {
  6302. return this._min;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(PerfCounter.prototype, "max", {
  6308. /**
  6309. * Returns the biggest value ever
  6310. */
  6311. get: function () {
  6312. return this._max;
  6313. },
  6314. enumerable: true,
  6315. configurable: true
  6316. });
  6317. Object.defineProperty(PerfCounter.prototype, "average", {
  6318. /**
  6319. * Returns the average value since the performance counter is running
  6320. */
  6321. get: function () {
  6322. return this._average;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6328. /**
  6329. * Returns the average value of the last second the counter was monitored
  6330. */
  6331. get: function () {
  6332. return this._lastSecAverage;
  6333. },
  6334. enumerable: true,
  6335. configurable: true
  6336. });
  6337. Object.defineProperty(PerfCounter.prototype, "current", {
  6338. /**
  6339. * Returns the current value
  6340. */
  6341. get: function () {
  6342. return this._current;
  6343. },
  6344. enumerable: true,
  6345. configurable: true
  6346. });
  6347. Object.defineProperty(PerfCounter.prototype, "total", {
  6348. get: function () {
  6349. return this._totalAccumulated;
  6350. },
  6351. enumerable: true,
  6352. configurable: true
  6353. });
  6354. /**
  6355. * Call this method to start monitoring a new frame.
  6356. * 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.
  6357. */
  6358. PerfCounter.prototype.fetchNewFrame = function () {
  6359. this._totalValueCount++;
  6360. this._current = 0;
  6361. this._lastSecValueCount++;
  6362. };
  6363. /**
  6364. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6365. * @param newCount the count value to add to the monitored count
  6366. * @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.
  6367. */
  6368. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6369. if (!PerfCounter.Enabled) {
  6370. return;
  6371. }
  6372. this._current += newCount;
  6373. if (fetchResult) {
  6374. this._fetchResult();
  6375. }
  6376. };
  6377. /**
  6378. * Start monitoring this performance counter
  6379. */
  6380. PerfCounter.prototype.beginMonitoring = function () {
  6381. if (!PerfCounter.Enabled) {
  6382. return;
  6383. }
  6384. this._startMonitoringTime = Tools.Now;
  6385. };
  6386. /**
  6387. * Compute the time lapsed since the previous beginMonitoring() call.
  6388. * @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
  6389. */
  6390. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6391. if (newFrame === void 0) { newFrame = true; }
  6392. if (!PerfCounter.Enabled) {
  6393. return;
  6394. }
  6395. if (newFrame) {
  6396. this.fetchNewFrame();
  6397. }
  6398. var currentTime = Tools.Now;
  6399. this._current = currentTime - this._startMonitoringTime;
  6400. if (newFrame) {
  6401. this._fetchResult();
  6402. }
  6403. };
  6404. PerfCounter.prototype._fetchResult = function () {
  6405. this._totalAccumulated += this._current;
  6406. this._lastSecAccumulated += this._current;
  6407. // Min/Max update
  6408. this._min = Math.min(this._min, this._current);
  6409. this._max = Math.max(this._max, this._current);
  6410. this._average = this._totalAccumulated / this._totalValueCount;
  6411. // Reset last sec?
  6412. var now = Tools.Now;
  6413. if ((now - this._lastSecTime) > 1000) {
  6414. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6415. this._lastSecTime = now;
  6416. this._lastSecAccumulated = 0;
  6417. this._lastSecValueCount = 0;
  6418. }
  6419. };
  6420. return PerfCounter;
  6421. }());
  6422. PerfCounter.Enabled = true;
  6423. BABYLON.PerfCounter = PerfCounter;
  6424. /**
  6425. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6426. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6427. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6428. * @param name The name of the class, case should be preserved
  6429. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6430. */
  6431. function className(name, module) {
  6432. return function (target) {
  6433. target["__bjsclassName__"] = name;
  6434. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6435. };
  6436. }
  6437. BABYLON.className = className;
  6438. /**
  6439. * An implementation of a loop for asynchronous functions.
  6440. */
  6441. var AsyncLoop = (function () {
  6442. /**
  6443. * Constroctor.
  6444. * @param iterations the number of iterations.
  6445. * @param _fn the function to run each iteration
  6446. * @param _successCallback the callback that will be called upon succesful execution
  6447. * @param offset starting offset.
  6448. */
  6449. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6450. if (offset === void 0) { offset = 0; }
  6451. this.iterations = iterations;
  6452. this._fn = _fn;
  6453. this._successCallback = _successCallback;
  6454. this.index = offset - 1;
  6455. this._done = false;
  6456. }
  6457. /**
  6458. * Execute the next iteration. Must be called after the last iteration was finished.
  6459. */
  6460. AsyncLoop.prototype.executeNext = function () {
  6461. if (!this._done) {
  6462. if (this.index + 1 < this.iterations) {
  6463. ++this.index;
  6464. this._fn(this);
  6465. }
  6466. else {
  6467. this.breakLoop();
  6468. }
  6469. }
  6470. };
  6471. /**
  6472. * Break the loop and run the success callback.
  6473. */
  6474. AsyncLoop.prototype.breakLoop = function () {
  6475. this._done = true;
  6476. this._successCallback();
  6477. };
  6478. /**
  6479. * Helper function
  6480. */
  6481. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6482. if (offset === void 0) { offset = 0; }
  6483. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6484. loop.executeNext();
  6485. return loop;
  6486. };
  6487. /**
  6488. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6489. * @param iterations total number of iterations
  6490. * @param syncedIterations number of synchronous iterations in each async iteration.
  6491. * @param fn the function to call each iteration.
  6492. * @param callback a success call back that will be called when iterating stops.
  6493. * @param breakFunction a break condition (optional)
  6494. * @param timeout timeout settings for the setTimeout function. default - 0.
  6495. * @constructor
  6496. */
  6497. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6498. if (timeout === void 0) { timeout = 0; }
  6499. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6500. if (breakFunction && breakFunction())
  6501. loop.breakLoop();
  6502. else {
  6503. setTimeout(function () {
  6504. for (var i = 0; i < syncedIterations; ++i) {
  6505. var iteration = (loop.index * syncedIterations) + i;
  6506. if (iteration >= iterations)
  6507. break;
  6508. fn(iteration);
  6509. if (breakFunction && breakFunction()) {
  6510. loop.breakLoop();
  6511. break;
  6512. }
  6513. }
  6514. loop.executeNext();
  6515. }, timeout);
  6516. }
  6517. }, callback);
  6518. };
  6519. return AsyncLoop;
  6520. }());
  6521. BABYLON.AsyncLoop = AsyncLoop;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.tools.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. var Internals;
  6527. (function (Internals) {
  6528. var _AlphaState = (function () {
  6529. /**
  6530. * Initializes the state.
  6531. */
  6532. function _AlphaState() {
  6533. this._isAlphaBlendDirty = false;
  6534. this._isBlendFunctionParametersDirty = false;
  6535. this._isBlendEquationParametersDirty = false;
  6536. this._isBlendConstantsDirty = false;
  6537. this._alphaBlend = false;
  6538. this._blendFunctionParameters = new Array(4);
  6539. this._blendEquationParameters = new Array(2);
  6540. this._blendConstants = new Array(4);
  6541. this.reset();
  6542. }
  6543. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6544. get: function () {
  6545. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6546. },
  6547. enumerable: true,
  6548. configurable: true
  6549. });
  6550. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6551. get: function () {
  6552. return this._alphaBlend;
  6553. },
  6554. set: function (value) {
  6555. if (this._alphaBlend === value) {
  6556. return;
  6557. }
  6558. this._alphaBlend = value;
  6559. this._isAlphaBlendDirty = true;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6565. if (this._blendConstants[0] === r &&
  6566. this._blendConstants[1] === g &&
  6567. this._blendConstants[2] === b &&
  6568. this._blendConstants[3] === a) {
  6569. return;
  6570. }
  6571. this._blendConstants[0] = r;
  6572. this._blendConstants[1] = g;
  6573. this._blendConstants[2] = b;
  6574. this._blendConstants[3] = a;
  6575. this._isBlendConstantsDirty = true;
  6576. };
  6577. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6578. if (this._blendFunctionParameters[0] === value0 &&
  6579. this._blendFunctionParameters[1] === value1 &&
  6580. this._blendFunctionParameters[2] === value2 &&
  6581. this._blendFunctionParameters[3] === value3) {
  6582. return;
  6583. }
  6584. this._blendFunctionParameters[0] = value0;
  6585. this._blendFunctionParameters[1] = value1;
  6586. this._blendFunctionParameters[2] = value2;
  6587. this._blendFunctionParameters[3] = value3;
  6588. this._isBlendFunctionParametersDirty = true;
  6589. };
  6590. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6591. if (this._blendEquationParameters[0] === rgb &&
  6592. this._blendEquationParameters[1] === alpha) {
  6593. return;
  6594. }
  6595. this._blendEquationParameters[0] = rgb;
  6596. this._blendEquationParameters[1] = alpha;
  6597. this._isBlendEquationParametersDirty = true;
  6598. };
  6599. _AlphaState.prototype.reset = function () {
  6600. this._alphaBlend = false;
  6601. this._blendFunctionParameters[0] = null;
  6602. this._blendFunctionParameters[1] = null;
  6603. this._blendFunctionParameters[2] = null;
  6604. this._blendFunctionParameters[3] = null;
  6605. this._blendEquationParameters[0] = null;
  6606. this._blendEquationParameters[1] = null;
  6607. this._blendConstants[0] = null;
  6608. this._blendConstants[1] = null;
  6609. this._blendConstants[2] = null;
  6610. this._blendConstants[3] = null;
  6611. this._isAlphaBlendDirty = true;
  6612. this._isBlendFunctionParametersDirty = false;
  6613. this._isBlendEquationParametersDirty = false;
  6614. this._isBlendConstantsDirty = false;
  6615. };
  6616. _AlphaState.prototype.apply = function (gl) {
  6617. if (!this.isDirty) {
  6618. return;
  6619. }
  6620. // Alpha blend
  6621. if (this._isAlphaBlendDirty) {
  6622. if (this._alphaBlend) {
  6623. gl.enable(gl.BLEND);
  6624. }
  6625. else {
  6626. gl.disable(gl.BLEND);
  6627. }
  6628. this._isAlphaBlendDirty = false;
  6629. }
  6630. // Alpha function
  6631. if (this._isBlendFunctionParametersDirty) {
  6632. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6633. this._isBlendFunctionParametersDirty = false;
  6634. }
  6635. // Alpha equation
  6636. if (this._isBlendEquationParametersDirty) {
  6637. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6638. this._isBlendEquationParametersDirty = false;
  6639. }
  6640. // Constants
  6641. if (this._isBlendConstantsDirty) {
  6642. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6643. this._isBlendConstantsDirty = false;
  6644. }
  6645. };
  6646. return _AlphaState;
  6647. }());
  6648. Internals._AlphaState = _AlphaState;
  6649. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6650. })(BABYLON || (BABYLON = {}));
  6651. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6652. var BABYLON;
  6653. (function (BABYLON) {
  6654. var Internals;
  6655. (function (Internals) {
  6656. var _DepthCullingState = (function () {
  6657. /**
  6658. * Initializes the state.
  6659. */
  6660. function _DepthCullingState() {
  6661. this._isDepthTestDirty = false;
  6662. this._isDepthMaskDirty = false;
  6663. this._isDepthFuncDirty = false;
  6664. this._isCullFaceDirty = false;
  6665. this._isCullDirty = false;
  6666. this._isZOffsetDirty = false;
  6667. this.reset();
  6668. }
  6669. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6670. get: function () {
  6671. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6672. },
  6673. enumerable: true,
  6674. configurable: true
  6675. });
  6676. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6677. get: function () {
  6678. return this._zOffset;
  6679. },
  6680. set: function (value) {
  6681. if (this._zOffset === value) {
  6682. return;
  6683. }
  6684. this._zOffset = value;
  6685. this._isZOffsetDirty = true;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6691. get: function () {
  6692. return this._cullFace;
  6693. },
  6694. set: function (value) {
  6695. if (this._cullFace === value) {
  6696. return;
  6697. }
  6698. this._cullFace = value;
  6699. this._isCullFaceDirty = true;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6705. get: function () {
  6706. return this._cull;
  6707. },
  6708. set: function (value) {
  6709. if (this._cull === value) {
  6710. return;
  6711. }
  6712. this._cull = value;
  6713. this._isCullDirty = true;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6719. get: function () {
  6720. return this._depthFunc;
  6721. },
  6722. set: function (value) {
  6723. if (this._depthFunc === value) {
  6724. return;
  6725. }
  6726. this._depthFunc = value;
  6727. this._isDepthFuncDirty = true;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6733. get: function () {
  6734. return this._depthMask;
  6735. },
  6736. set: function (value) {
  6737. if (this._depthMask === value) {
  6738. return;
  6739. }
  6740. this._depthMask = value;
  6741. this._isDepthMaskDirty = true;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6747. get: function () {
  6748. return this._depthTest;
  6749. },
  6750. set: function (value) {
  6751. if (this._depthTest === value) {
  6752. return;
  6753. }
  6754. this._depthTest = value;
  6755. this._isDepthTestDirty = true;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. _DepthCullingState.prototype.reset = function () {
  6761. this._depthMask = true;
  6762. this._depthTest = true;
  6763. this._depthFunc = null;
  6764. this._cullFace = null;
  6765. this._cull = null;
  6766. this._zOffset = 0;
  6767. this._isDepthTestDirty = true;
  6768. this._isDepthMaskDirty = true;
  6769. this._isDepthFuncDirty = false;
  6770. this._isCullFaceDirty = false;
  6771. this._isCullDirty = false;
  6772. this._isZOffsetDirty = false;
  6773. };
  6774. _DepthCullingState.prototype.apply = function (gl) {
  6775. if (!this.isDirty) {
  6776. return;
  6777. }
  6778. // Cull
  6779. if (this._isCullDirty) {
  6780. if (this.cull) {
  6781. gl.enable(gl.CULL_FACE);
  6782. }
  6783. else {
  6784. gl.disable(gl.CULL_FACE);
  6785. }
  6786. this._isCullDirty = false;
  6787. }
  6788. // Cull face
  6789. if (this._isCullFaceDirty) {
  6790. gl.cullFace(this.cullFace);
  6791. this._isCullFaceDirty = false;
  6792. }
  6793. // Depth mask
  6794. if (this._isDepthMaskDirty) {
  6795. gl.depthMask(this.depthMask);
  6796. this._isDepthMaskDirty = false;
  6797. }
  6798. // Depth test
  6799. if (this._isDepthTestDirty) {
  6800. if (this.depthTest) {
  6801. gl.enable(gl.DEPTH_TEST);
  6802. }
  6803. else {
  6804. gl.disable(gl.DEPTH_TEST);
  6805. }
  6806. this._isDepthTestDirty = false;
  6807. }
  6808. // Depth func
  6809. if (this._isDepthFuncDirty) {
  6810. gl.depthFunc(this.depthFunc);
  6811. this._isDepthFuncDirty = false;
  6812. }
  6813. // zOffset
  6814. if (this._isZOffsetDirty) {
  6815. if (this.zOffset) {
  6816. gl.enable(gl.POLYGON_OFFSET_FILL);
  6817. gl.polygonOffset(this.zOffset, 0);
  6818. }
  6819. else {
  6820. gl.disable(gl.POLYGON_OFFSET_FILL);
  6821. }
  6822. this._isZOffsetDirty = false;
  6823. }
  6824. };
  6825. return _DepthCullingState;
  6826. }());
  6827. Internals._DepthCullingState = _DepthCullingState;
  6828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6829. })(BABYLON || (BABYLON = {}));
  6830. //# sourceMappingURL=babylon.depthCullingState.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var Internals;
  6834. (function (Internals) {
  6835. var _StencilState = (function () {
  6836. function _StencilState() {
  6837. this._isStencilTestDirty = false;
  6838. this._isStencilMaskDirty = false;
  6839. this._isStencilFuncDirty = false;
  6840. this._isStencilOpDirty = false;
  6841. this.reset();
  6842. }
  6843. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6844. get: function () {
  6845. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6851. get: function () {
  6852. return this._stencilFunc;
  6853. },
  6854. set: function (value) {
  6855. if (this._stencilFunc === value) {
  6856. return;
  6857. }
  6858. this._stencilFunc = value;
  6859. this._isStencilFuncDirty = true;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6865. get: function () {
  6866. return this._stencilFuncRef;
  6867. },
  6868. set: function (value) {
  6869. if (this._stencilFuncRef === value) {
  6870. return;
  6871. }
  6872. this._stencilFuncRef = value;
  6873. this._isStencilFuncDirty = true;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6879. get: function () {
  6880. return this._stencilFuncMask;
  6881. },
  6882. set: function (value) {
  6883. if (this._stencilFuncMask === value) {
  6884. return;
  6885. }
  6886. this._stencilFuncMask = value;
  6887. this._isStencilFuncDirty = true;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6893. get: function () {
  6894. return this._stencilOpStencilFail;
  6895. },
  6896. set: function (value) {
  6897. if (this._stencilOpStencilFail === value) {
  6898. return;
  6899. }
  6900. this._stencilOpStencilFail = value;
  6901. this._isStencilOpDirty = true;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6907. get: function () {
  6908. return this._stencilOpDepthFail;
  6909. },
  6910. set: function (value) {
  6911. if (this._stencilOpDepthFail === value) {
  6912. return;
  6913. }
  6914. this._stencilOpDepthFail = value;
  6915. this._isStencilOpDirty = true;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6921. get: function () {
  6922. return this._stencilOpStencilDepthPass;
  6923. },
  6924. set: function (value) {
  6925. if (this._stencilOpStencilDepthPass === value) {
  6926. return;
  6927. }
  6928. this._stencilOpStencilDepthPass = value;
  6929. this._isStencilOpDirty = true;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6935. get: function () {
  6936. return this._stencilMask;
  6937. },
  6938. set: function (value) {
  6939. if (this._stencilMask === value) {
  6940. return;
  6941. }
  6942. this._stencilMask = value;
  6943. this._isStencilMaskDirty = true;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6949. get: function () {
  6950. return this._stencilTest;
  6951. },
  6952. set: function (value) {
  6953. if (this._stencilTest === value) {
  6954. return;
  6955. }
  6956. this._stencilTest = value;
  6957. this._isStencilTestDirty = true;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. _StencilState.prototype.reset = function () {
  6963. this._stencilTest = false;
  6964. this._stencilMask = 0xFF;
  6965. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6966. this._stencilFuncRef = 1;
  6967. this._stencilFuncMask = 0xFF;
  6968. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6969. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6970. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6971. this._isStencilTestDirty = true;
  6972. this._isStencilMaskDirty = true;
  6973. this._isStencilFuncDirty = true;
  6974. this._isStencilOpDirty = true;
  6975. };
  6976. _StencilState.prototype.apply = function (gl) {
  6977. if (!this.isDirty) {
  6978. return;
  6979. }
  6980. // Stencil test
  6981. if (this._isStencilTestDirty) {
  6982. if (this.stencilTest) {
  6983. gl.enable(gl.STENCIL_TEST);
  6984. }
  6985. else {
  6986. gl.disable(gl.STENCIL_TEST);
  6987. }
  6988. this._isStencilTestDirty = false;
  6989. }
  6990. // Stencil mask
  6991. if (this._isStencilMaskDirty) {
  6992. gl.stencilMask(this.stencilMask);
  6993. this._isStencilMaskDirty = false;
  6994. }
  6995. // Stencil func
  6996. if (this._isStencilFuncDirty) {
  6997. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6998. this._isStencilFuncDirty = false;
  6999. }
  7000. // Stencil op
  7001. if (this._isStencilOpDirty) {
  7002. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7003. this._isStencilOpDirty = false;
  7004. }
  7005. };
  7006. return _StencilState;
  7007. }());
  7008. Internals._StencilState = _StencilState;
  7009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7010. })(BABYLON || (BABYLON = {}));
  7011. //# sourceMappingURL=babylon.stencilState.js.map
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7015. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7016. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7017. gl.compileShader(shader);
  7018. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7019. throw new Error(gl.getShaderInfoLog(shader));
  7020. }
  7021. return shader;
  7022. };
  7023. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7024. var magFilter = gl.NEAREST;
  7025. var minFilter = gl.NEAREST;
  7026. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7027. magFilter = gl.LINEAR;
  7028. if (generateMipMaps) {
  7029. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7030. }
  7031. else {
  7032. minFilter = gl.LINEAR;
  7033. }
  7034. }
  7035. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7036. magFilter = gl.LINEAR;
  7037. if (generateMipMaps) {
  7038. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7039. }
  7040. else {
  7041. minFilter = gl.LINEAR;
  7042. }
  7043. }
  7044. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7045. magFilter = gl.NEAREST;
  7046. if (generateMipMaps) {
  7047. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7048. }
  7049. else {
  7050. minFilter = gl.NEAREST;
  7051. }
  7052. }
  7053. return {
  7054. min: minFilter,
  7055. mag: magFilter
  7056. };
  7057. };
  7058. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7060. var engine = scene.getEngine();
  7061. if (!engine) {
  7062. return;
  7063. }
  7064. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7065. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7066. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7068. texture._baseWidth = width;
  7069. texture._baseHeight = height;
  7070. texture._width = potWidth;
  7071. texture._height = potHeight;
  7072. texture.isReady = true;
  7073. processFunction(potWidth, potHeight);
  7074. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7077. if (!noMipmap && !isCompressed) {
  7078. gl.generateMipmap(gl.TEXTURE_2D);
  7079. }
  7080. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7081. engine.resetTextureCache();
  7082. scene._removePendingData(texture);
  7083. texture.onLoadedCallbacks.forEach(function (callback) {
  7084. callback();
  7085. });
  7086. texture.onLoadedCallbacks = [];
  7087. };
  7088. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7089. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7090. var img;
  7091. var onload = function () {
  7092. loadedImages[index] = img;
  7093. loadedImages._internalCount++;
  7094. scene._removePendingData(img);
  7095. if (loadedImages._internalCount === 6) {
  7096. onfinish(loadedImages);
  7097. }
  7098. };
  7099. var onerror = function () {
  7100. scene._removePendingData(img);
  7101. if (onErrorCallBack) {
  7102. onErrorCallBack();
  7103. }
  7104. };
  7105. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7106. scene._addPendingData(img);
  7107. };
  7108. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7109. if (onError === void 0) { onError = null; }
  7110. var loadedImages = [];
  7111. loadedImages._internalCount = 0;
  7112. for (var index = 0; index < 6; index++) {
  7113. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7114. }
  7115. };
  7116. var InstancingAttributeInfo = (function () {
  7117. function InstancingAttributeInfo() {
  7118. }
  7119. return InstancingAttributeInfo;
  7120. }());
  7121. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7122. var EngineCapabilities = (function () {
  7123. function EngineCapabilities() {
  7124. }
  7125. return EngineCapabilities;
  7126. }());
  7127. BABYLON.EngineCapabilities = EngineCapabilities;
  7128. /**
  7129. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7130. */
  7131. var Engine = (function () {
  7132. /**
  7133. * @constructor
  7134. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7135. * @param {boolean} [antialias] - enable antialias
  7136. * @param options - further options to be sent to the getContext function
  7137. */
  7138. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7140. var _this = this;
  7141. // Public members
  7142. this.isFullscreen = false;
  7143. this.isPointerLock = false;
  7144. this.cullBackFaces = true;
  7145. this.renderEvenInBackground = true;
  7146. this.preventCacheWipeBetweenFrames = false;
  7147. // To enable/disable IDB support and avoid XHR on .manifest
  7148. this.enableOfflineSupport = BABYLON.Database;
  7149. this.scenes = new Array();
  7150. // Observables
  7151. /**
  7152. * Observable event triggered each time the rendering canvas is resized
  7153. */
  7154. this.onResizeObservable = new BABYLON.Observable();
  7155. /**
  7156. * Observable event triggered each time the canvas lost focus
  7157. */
  7158. this.onCanvasBlurObservable = new BABYLON.Observable();
  7159. this._windowIsBackground = false;
  7160. this._webGLVersion = 1.0;
  7161. this._badOS = false;
  7162. this._drawCalls = new BABYLON.PerfCounter();
  7163. this._renderingQueueLaunched = false;
  7164. this._activeRenderLoops = [];
  7165. // FPS
  7166. this.fpsRange = 60;
  7167. this.previousFramesDuration = [];
  7168. this.fps = 60;
  7169. this.deltaTime = 0;
  7170. // States
  7171. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7172. this._stencilState = new BABYLON.Internals._StencilState();
  7173. this._alphaState = new BABYLON.Internals._AlphaState();
  7174. this._alphaMode = Engine.ALPHA_DISABLE;
  7175. // Cache
  7176. this._loadedTexturesCache = new Array();
  7177. this._maxTextureChannels = 16;
  7178. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7179. this._compiledEffects = {};
  7180. this._vertexAttribArraysEnabled = [];
  7181. this._uintIndicesCurrentlySet = false;
  7182. this._currentBoundBuffer = new Array();
  7183. this._currentBufferPointers = [];
  7184. this._currentInstanceLocations = new Array();
  7185. this._currentInstanceBuffers = new Array();
  7186. this._vaoRecordInProgress = false;
  7187. this._mustWipeVertexAttributes = false;
  7188. // Hardware supported Compressed Textures
  7189. this._texturesSupported = new Array();
  7190. this._onVRFullScreenTriggered = function () {
  7191. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7192. //get the old size before we change
  7193. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7194. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7195. //get the width and height, change the render size
  7196. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7197. var width, height;
  7198. _this.setHardwareScalingLevel(1);
  7199. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7200. }
  7201. else {
  7202. //When the specs are implemented, need to uncomment this.
  7203. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7204. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7205. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7206. _this._vrDisplayEnabled = undefined;
  7207. }
  7208. };
  7209. this._renderingCanvas = canvas;
  7210. Engine.Instances.push(this);
  7211. options = options || {};
  7212. if (antialias != null) {
  7213. options.antialias = antialias;
  7214. }
  7215. if (options.preserveDrawingBuffer === undefined) {
  7216. options.preserveDrawingBuffer = false;
  7217. }
  7218. if (options.audioEngine === undefined) {
  7219. options.audioEngine = true;
  7220. }
  7221. if (options.stencil === undefined) {
  7222. options.stencil = true;
  7223. }
  7224. // GL
  7225. if (!options.disableWebGL2Support) {
  7226. try {
  7227. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7228. if (this._gl) {
  7229. this._webGLVersion = 2.0;
  7230. }
  7231. }
  7232. catch (e) {
  7233. // Do nothing
  7234. }
  7235. }
  7236. if (!this._gl) {
  7237. if (!canvas) {
  7238. throw new Error("The provided canvas is null or undefined.");
  7239. }
  7240. try {
  7241. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7242. }
  7243. catch (e) {
  7244. throw new Error("WebGL not supported");
  7245. }
  7246. }
  7247. if (!this._gl) {
  7248. throw new Error("WebGL not supported");
  7249. }
  7250. this._onBlur = function () {
  7251. _this._windowIsBackground = true;
  7252. };
  7253. this._onFocus = function () {
  7254. _this._windowIsBackground = false;
  7255. };
  7256. this._onCanvasBlur = function () {
  7257. _this.onCanvasBlurObservable.notifyObservers(_this);
  7258. };
  7259. window.addEventListener("blur", this._onBlur);
  7260. window.addEventListener("focus", this._onFocus);
  7261. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7262. // Viewport
  7263. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7264. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7265. this.resize();
  7266. // Caps
  7267. this._isStencilEnable = options.stencil;
  7268. this._caps = new EngineCapabilities();
  7269. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7270. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7271. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7272. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7273. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7274. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7275. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7276. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7277. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7278. // Infos
  7279. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7280. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7281. if (rendererInfo != null) {
  7282. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7283. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7284. }
  7285. if (!this._glVendor) {
  7286. this._glVendor = "Unknown vendor";
  7287. }
  7288. if (!this._glRenderer) {
  7289. this._glRenderer = "Unknown renderer";
  7290. }
  7291. // Extensions
  7292. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7293. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7295. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7296. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7297. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7298. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7299. 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');
  7300. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7301. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7302. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7303. this._caps.highPrecisionShaderSupported = true;
  7304. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7305. // Checks if some of the format renders first to allow the use of webgl inspector.
  7306. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7307. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7308. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7309. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7310. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7311. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7312. if (this._webGLVersion > 1) {
  7313. Engine.HALF_FLOAT_OES = 0x140B;
  7314. }
  7315. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7316. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7317. // Vertex array object
  7318. if (this._webGLVersion > 1) {
  7319. this._caps.vertexArrayObject = true;
  7320. }
  7321. else {
  7322. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7323. if (vertexArrayObjectExtension != null) {
  7324. this._caps.vertexArrayObject = true;
  7325. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7326. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7327. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7328. }
  7329. else {
  7330. this._caps.vertexArrayObject = false;
  7331. }
  7332. }
  7333. // Instances count
  7334. if (this._webGLVersion > 1) {
  7335. this._caps.instancedArrays = true;
  7336. }
  7337. else {
  7338. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7339. if (instanceExtension != null) {
  7340. this._caps.instancedArrays = true;
  7341. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7342. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7343. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7344. }
  7345. else {
  7346. this._caps.instancedArrays = false;
  7347. }
  7348. }
  7349. // Intelligently add supported compressed formats in order to check for.
  7350. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7351. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7352. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7353. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7354. if (this._caps.astc)
  7355. this.texturesSupported.push('-astc.ktx');
  7356. if (this._caps.s3tc)
  7357. this.texturesSupported.push('-dxt.ktx');
  7358. if (this._caps.pvrtc)
  7359. this.texturesSupported.push('-pvrtc.ktx');
  7360. if (this._caps.etc2)
  7361. this.texturesSupported.push('-etc2.ktx');
  7362. if (this._caps.etc1)
  7363. this.texturesSupported.push('-etc1.ktx');
  7364. if (this._gl.getShaderPrecisionFormat) {
  7365. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7366. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7367. }
  7368. // Depth buffer
  7369. this.setDepthBuffer(true);
  7370. this.setDepthFunctionToLessOrEqual();
  7371. this.setDepthWrite(true);
  7372. // Fullscreen
  7373. this._onFullscreenChange = function () {
  7374. if (document.fullscreen !== undefined) {
  7375. _this.isFullscreen = document.fullscreen;
  7376. }
  7377. else if (document.mozFullScreen !== undefined) {
  7378. _this.isFullscreen = document.mozFullScreen;
  7379. }
  7380. else if (document.webkitIsFullScreen !== undefined) {
  7381. _this.isFullscreen = document.webkitIsFullScreen;
  7382. }
  7383. else if (document.msIsFullScreen !== undefined) {
  7384. _this.isFullscreen = document.msIsFullScreen;
  7385. }
  7386. // Pointer lock
  7387. if (_this.isFullscreen && _this._pointerLockRequested) {
  7388. canvas.requestPointerLock = canvas.requestPointerLock ||
  7389. canvas.msRequestPointerLock ||
  7390. canvas.mozRequestPointerLock ||
  7391. canvas.webkitRequestPointerLock;
  7392. if (canvas.requestPointerLock) {
  7393. canvas.requestPointerLock();
  7394. }
  7395. }
  7396. };
  7397. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7398. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7399. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7400. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7401. // Pointer lock
  7402. this._onPointerLockChange = function () {
  7403. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7404. document.webkitPointerLockElement === canvas ||
  7405. document.msPointerLockElement === canvas ||
  7406. document.pointerLockElement === canvas);
  7407. };
  7408. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7409. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7410. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7411. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7412. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7413. Engine.audioEngine = new BABYLON.AudioEngine();
  7414. }
  7415. //Load WebVR Devices
  7416. if (options.autoEnableWebVR) {
  7417. this.initWebVR();
  7418. }
  7419. //Detect if we are running on a faulty buggy OS.
  7420. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7421. //ua sniffing is the tool of the devil.
  7422. this._badOS = regexp.test(navigator.userAgent);
  7423. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7424. }
  7425. Object.defineProperty(Engine, "LastCreatedEngine", {
  7426. get: function () {
  7427. if (Engine.Instances.length === 0) {
  7428. return null;
  7429. }
  7430. return Engine.Instances[Engine.Instances.length - 1];
  7431. },
  7432. enumerable: true,
  7433. configurable: true
  7434. });
  7435. Object.defineProperty(Engine, "LastCreatedScene", {
  7436. get: function () {
  7437. var lastCreatedEngine = Engine.LastCreatedEngine;
  7438. if (!lastCreatedEngine) {
  7439. return null;
  7440. }
  7441. if (lastCreatedEngine.scenes.length === 0) {
  7442. return null;
  7443. }
  7444. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7445. },
  7446. enumerable: true,
  7447. configurable: true
  7448. });
  7449. /**
  7450. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7451. */
  7452. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7453. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7454. var engine = Engine.Instances[engineIndex];
  7455. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7456. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7457. }
  7458. }
  7459. };
  7460. Object.defineProperty(Engine, "NEVER", {
  7461. get: function () {
  7462. return Engine._NEVER;
  7463. },
  7464. enumerable: true,
  7465. configurable: true
  7466. });
  7467. Object.defineProperty(Engine, "ALWAYS", {
  7468. get: function () {
  7469. return Engine._ALWAYS;
  7470. },
  7471. enumerable: true,
  7472. configurable: true
  7473. });
  7474. Object.defineProperty(Engine, "LESS", {
  7475. get: function () {
  7476. return Engine._LESS;
  7477. },
  7478. enumerable: true,
  7479. configurable: true
  7480. });
  7481. Object.defineProperty(Engine, "EQUAL", {
  7482. get: function () {
  7483. return Engine._EQUAL;
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(Engine, "LEQUAL", {
  7489. get: function () {
  7490. return Engine._LEQUAL;
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. Object.defineProperty(Engine, "GREATER", {
  7496. get: function () {
  7497. return Engine._GREATER;
  7498. },
  7499. enumerable: true,
  7500. configurable: true
  7501. });
  7502. Object.defineProperty(Engine, "GEQUAL", {
  7503. get: function () {
  7504. return Engine._GEQUAL;
  7505. },
  7506. enumerable: true,
  7507. configurable: true
  7508. });
  7509. Object.defineProperty(Engine, "NOTEQUAL", {
  7510. get: function () {
  7511. return Engine._NOTEQUAL;
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(Engine, "KEEP", {
  7517. get: function () {
  7518. return Engine._KEEP;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. Object.defineProperty(Engine, "REPLACE", {
  7524. get: function () {
  7525. return Engine._REPLACE;
  7526. },
  7527. enumerable: true,
  7528. configurable: true
  7529. });
  7530. Object.defineProperty(Engine, "INCR", {
  7531. get: function () {
  7532. return Engine._INCR;
  7533. },
  7534. enumerable: true,
  7535. configurable: true
  7536. });
  7537. Object.defineProperty(Engine, "DECR", {
  7538. get: function () {
  7539. return Engine._DECR;
  7540. },
  7541. enumerable: true,
  7542. configurable: true
  7543. });
  7544. Object.defineProperty(Engine, "INVERT", {
  7545. get: function () {
  7546. return Engine._INVERT;
  7547. },
  7548. enumerable: true,
  7549. configurable: true
  7550. });
  7551. Object.defineProperty(Engine, "INCR_WRAP", {
  7552. get: function () {
  7553. return Engine._INCR_WRAP;
  7554. },
  7555. enumerable: true,
  7556. configurable: true
  7557. });
  7558. Object.defineProperty(Engine, "DECR_WRAP", {
  7559. get: function () {
  7560. return Engine._DECR_WRAP;
  7561. },
  7562. enumerable: true,
  7563. configurable: true
  7564. });
  7565. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7566. get: function () {
  7567. return Engine._ALPHA_DISABLE;
  7568. },
  7569. enumerable: true,
  7570. configurable: true
  7571. });
  7572. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7573. get: function () {
  7574. return Engine._ALPHA_ONEONE;
  7575. },
  7576. enumerable: true,
  7577. configurable: true
  7578. });
  7579. Object.defineProperty(Engine, "ALPHA_ADD", {
  7580. get: function () {
  7581. return Engine._ALPHA_ADD;
  7582. },
  7583. enumerable: true,
  7584. configurable: true
  7585. });
  7586. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7587. get: function () {
  7588. return Engine._ALPHA_COMBINE;
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7594. get: function () {
  7595. return Engine._ALPHA_SUBTRACT;
  7596. },
  7597. enumerable: true,
  7598. configurable: true
  7599. });
  7600. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7601. get: function () {
  7602. return Engine._ALPHA_MULTIPLY;
  7603. },
  7604. enumerable: true,
  7605. configurable: true
  7606. });
  7607. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7608. get: function () {
  7609. return Engine._ALPHA_MAXIMIZED;
  7610. },
  7611. enumerable: true,
  7612. configurable: true
  7613. });
  7614. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7615. get: function () {
  7616. return Engine._ALPHA_PREMULTIPLIED;
  7617. },
  7618. enumerable: true,
  7619. configurable: true
  7620. });
  7621. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7622. get: function () {
  7623. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7624. },
  7625. enumerable: true,
  7626. configurable: true
  7627. });
  7628. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7629. get: function () {
  7630. return Engine._ALPHA_INTERPOLATE;
  7631. },
  7632. enumerable: true,
  7633. configurable: true
  7634. });
  7635. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7636. get: function () {
  7637. return Engine._ALPHA_SCREENMODE;
  7638. },
  7639. enumerable: true,
  7640. configurable: true
  7641. });
  7642. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7643. get: function () {
  7644. return Engine._DELAYLOADSTATE_NONE;
  7645. },
  7646. enumerable: true,
  7647. configurable: true
  7648. });
  7649. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7650. get: function () {
  7651. return Engine._DELAYLOADSTATE_LOADED;
  7652. },
  7653. enumerable: true,
  7654. configurable: true
  7655. });
  7656. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7657. get: function () {
  7658. return Engine._DELAYLOADSTATE_LOADING;
  7659. },
  7660. enumerable: true,
  7661. configurable: true
  7662. });
  7663. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7664. get: function () {
  7665. return Engine._DELAYLOADSTATE_NOTLOADED;
  7666. },
  7667. enumerable: true,
  7668. configurable: true
  7669. });
  7670. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7671. get: function () {
  7672. return Engine._TEXTUREFORMAT_ALPHA;
  7673. },
  7674. enumerable: true,
  7675. configurable: true
  7676. });
  7677. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7678. get: function () {
  7679. return Engine._TEXTUREFORMAT_LUMINANCE;
  7680. },
  7681. enumerable: true,
  7682. configurable: true
  7683. });
  7684. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7685. get: function () {
  7686. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7692. get: function () {
  7693. return Engine._TEXTUREFORMAT_RGB;
  7694. },
  7695. enumerable: true,
  7696. configurable: true
  7697. });
  7698. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7699. get: function () {
  7700. return Engine._TEXTUREFORMAT_RGBA;
  7701. },
  7702. enumerable: true,
  7703. configurable: true
  7704. });
  7705. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7706. get: function () {
  7707. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7713. get: function () {
  7714. return Engine._TEXTURETYPE_FLOAT;
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7720. get: function () {
  7721. return Engine._TEXTURETYPE_HALF_FLOAT;
  7722. },
  7723. enumerable: true,
  7724. configurable: true
  7725. });
  7726. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7727. get: function () {
  7728. return Engine._SCALEMODE_FLOOR;
  7729. },
  7730. enumerable: true,
  7731. configurable: true
  7732. });
  7733. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7734. get: function () {
  7735. return Engine._SCALEMODE_NEAREST;
  7736. },
  7737. enumerable: true,
  7738. configurable: true
  7739. });
  7740. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7741. get: function () {
  7742. return Engine._SCALEMODE_CEILING;
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. Object.defineProperty(Engine, "Version", {
  7748. get: function () {
  7749. return "3.0-beta";
  7750. },
  7751. enumerable: true,
  7752. configurable: true
  7753. });
  7754. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7755. get: function () {
  7756. return this._texturesSupported;
  7757. },
  7758. enumerable: true,
  7759. configurable: true
  7760. });
  7761. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7762. get: function () {
  7763. return this._textureFormatInUse;
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7769. // Empty texture
  7770. get: function () {
  7771. if (!this._emptyTexture) {
  7772. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7773. }
  7774. return this._emptyTexture;
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7780. get: function () {
  7781. if (!this._emptyCubeTexture) {
  7782. var faceData = new Uint8Array(4);
  7783. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7784. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7785. }
  7786. return this._emptyCubeTexture;
  7787. },
  7788. enumerable: true,
  7789. configurable: true
  7790. });
  7791. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7792. get: function () {
  7793. return this._webGLVersion;
  7794. },
  7795. enumerable: true,
  7796. configurable: true
  7797. });
  7798. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7799. /**
  7800. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7801. */
  7802. get: function () {
  7803. return this._isStencilEnable;
  7804. },
  7805. enumerable: true,
  7806. configurable: true
  7807. });
  7808. Engine.prototype._prepareWorkingCanvas = function () {
  7809. if (this._workingCanvas) {
  7810. return;
  7811. }
  7812. this._workingCanvas = document.createElement("canvas");
  7813. this._workingContext = this._workingCanvas.getContext("2d");
  7814. };
  7815. Engine.prototype.resetTextureCache = function () {
  7816. for (var index = 0; index < this._maxTextureChannels; index++) {
  7817. this._activeTexturesCache[index] = null;
  7818. }
  7819. };
  7820. Engine.prototype.getGlInfo = function () {
  7821. return {
  7822. vendor: this._glVendor,
  7823. renderer: this._glRenderer,
  7824. version: this._glVersion
  7825. };
  7826. };
  7827. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7828. if (useScreen === void 0) { useScreen = false; }
  7829. var viewport = camera.viewport;
  7830. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7831. };
  7832. Engine.prototype.getRenderWidth = function (useScreen) {
  7833. if (useScreen === void 0) { useScreen = false; }
  7834. if (!useScreen && this._currentRenderTarget) {
  7835. return this._currentRenderTarget._width;
  7836. }
  7837. return this._renderingCanvas.width;
  7838. };
  7839. Engine.prototype.getRenderHeight = function (useScreen) {
  7840. if (useScreen === void 0) { useScreen = false; }
  7841. if (!useScreen && this._currentRenderTarget) {
  7842. return this._currentRenderTarget._height;
  7843. }
  7844. return this._renderingCanvas.height;
  7845. };
  7846. Engine.prototype.getRenderingCanvas = function () {
  7847. return this._renderingCanvas;
  7848. };
  7849. Engine.prototype.getRenderingCanvasClientRect = function () {
  7850. return this._renderingCanvas.getBoundingClientRect();
  7851. };
  7852. Engine.prototype.setHardwareScalingLevel = function (level) {
  7853. this._hardwareScalingLevel = level;
  7854. this.resize();
  7855. };
  7856. Engine.prototype.getHardwareScalingLevel = function () {
  7857. return this._hardwareScalingLevel;
  7858. };
  7859. Engine.prototype.getLoadedTexturesCache = function () {
  7860. return this._loadedTexturesCache;
  7861. };
  7862. Engine.prototype.getCaps = function () {
  7863. return this._caps;
  7864. };
  7865. Object.defineProperty(Engine.prototype, "drawCalls", {
  7866. get: function () {
  7867. return this._drawCalls.current;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7873. get: function () {
  7874. return this._drawCalls;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Engine.prototype.getDepthFunction = function () {
  7880. return this._depthCullingState.depthFunc;
  7881. };
  7882. Engine.prototype.setDepthFunction = function (depthFunc) {
  7883. this._depthCullingState.depthFunc = depthFunc;
  7884. };
  7885. Engine.prototype.setDepthFunctionToGreater = function () {
  7886. this._depthCullingState.depthFunc = this._gl.GREATER;
  7887. };
  7888. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7889. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7890. };
  7891. Engine.prototype.setDepthFunctionToLess = function () {
  7892. this._depthCullingState.depthFunc = this._gl.LESS;
  7893. };
  7894. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7895. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7896. };
  7897. Engine.prototype.getStencilBuffer = function () {
  7898. return this._stencilState.stencilTest;
  7899. };
  7900. Engine.prototype.setStencilBuffer = function (enable) {
  7901. this._stencilState.stencilTest = enable;
  7902. };
  7903. Engine.prototype.getStencilMask = function () {
  7904. return this._stencilState.stencilMask;
  7905. };
  7906. Engine.prototype.setStencilMask = function (mask) {
  7907. this._stencilState.stencilMask = mask;
  7908. };
  7909. Engine.prototype.getStencilFunction = function () {
  7910. return this._stencilState.stencilFunc;
  7911. };
  7912. Engine.prototype.getStencilFunctionReference = function () {
  7913. return this._stencilState.stencilFuncRef;
  7914. };
  7915. Engine.prototype.getStencilFunctionMask = function () {
  7916. return this._stencilState.stencilFuncMask;
  7917. };
  7918. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7919. this._stencilState.stencilFunc = stencilFunc;
  7920. };
  7921. Engine.prototype.setStencilFunctionReference = function (reference) {
  7922. this._stencilState.stencilFuncRef = reference;
  7923. };
  7924. Engine.prototype.setStencilFunctionMask = function (mask) {
  7925. this._stencilState.stencilFuncMask = mask;
  7926. };
  7927. Engine.prototype.getStencilOperationFail = function () {
  7928. return this._stencilState.stencilOpStencilFail;
  7929. };
  7930. Engine.prototype.getStencilOperationDepthFail = function () {
  7931. return this._stencilState.stencilOpDepthFail;
  7932. };
  7933. Engine.prototype.getStencilOperationPass = function () {
  7934. return this._stencilState.stencilOpStencilDepthPass;
  7935. };
  7936. Engine.prototype.setStencilOperationFail = function (operation) {
  7937. this._stencilState.stencilOpStencilFail = operation;
  7938. };
  7939. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7940. this._stencilState.stencilOpDepthFail = operation;
  7941. };
  7942. Engine.prototype.setStencilOperationPass = function (operation) {
  7943. this._stencilState.stencilOpStencilDepthPass = operation;
  7944. };
  7945. Engine.prototype.setDitheringState = function (value) {
  7946. if (value) {
  7947. this._gl.enable(this._gl.DITHER);
  7948. }
  7949. else {
  7950. this._gl.disable(this._gl.DITHER);
  7951. }
  7952. };
  7953. /**
  7954. * stop executing a render loop function and remove it from the execution array
  7955. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7956. */
  7957. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7958. if (!renderFunction) {
  7959. this._activeRenderLoops = [];
  7960. return;
  7961. }
  7962. var index = this._activeRenderLoops.indexOf(renderFunction);
  7963. if (index >= 0) {
  7964. this._activeRenderLoops.splice(index, 1);
  7965. }
  7966. };
  7967. Engine.prototype._renderLoop = function () {
  7968. var shouldRender = true;
  7969. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7970. shouldRender = false;
  7971. }
  7972. if (shouldRender) {
  7973. // Start new frame
  7974. this.beginFrame();
  7975. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7976. var renderFunction = this._activeRenderLoops[index];
  7977. renderFunction();
  7978. }
  7979. // Present
  7980. this.endFrame();
  7981. }
  7982. if (this._activeRenderLoops.length > 0) {
  7983. // Register new frame
  7984. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7985. }
  7986. else {
  7987. this._renderingQueueLaunched = false;
  7988. }
  7989. };
  7990. /**
  7991. * Register and execute a render loop. The engine can have more than one render function.
  7992. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7993. * @example
  7994. * engine.runRenderLoop(function () {
  7995. * scene.render()
  7996. * })
  7997. */
  7998. Engine.prototype.runRenderLoop = function (renderFunction) {
  7999. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8000. return;
  8001. }
  8002. this._activeRenderLoops.push(renderFunction);
  8003. if (!this._renderingQueueLaunched) {
  8004. this._renderingQueueLaunched = true;
  8005. this._bindedRenderFunction = this._renderLoop.bind(this);
  8006. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8007. }
  8008. };
  8009. /**
  8010. * Toggle full screen mode.
  8011. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8012. * @param {any} options - an options object to be sent to the requestFullscreen function
  8013. */
  8014. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8015. if (this.isFullscreen) {
  8016. BABYLON.Tools.ExitFullscreen();
  8017. }
  8018. else {
  8019. this._pointerLockRequested = requestPointerLock;
  8020. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8021. }
  8022. };
  8023. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8024. if (stencil === void 0) { stencil = false; }
  8025. this.applyStates();
  8026. var mode = 0;
  8027. if (backBuffer && color) {
  8028. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8029. mode |= this._gl.COLOR_BUFFER_BIT;
  8030. }
  8031. if (depth) {
  8032. this._gl.clearDepth(1.0);
  8033. mode |= this._gl.DEPTH_BUFFER_BIT;
  8034. }
  8035. if (stencil) {
  8036. this._gl.clearStencil(0);
  8037. mode |= this._gl.STENCIL_BUFFER_BIT;
  8038. }
  8039. this._gl.clear(mode);
  8040. };
  8041. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8042. var gl = this._gl;
  8043. // Save state
  8044. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8045. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8046. // Change state
  8047. gl.enable(gl.SCISSOR_TEST);
  8048. gl.scissor(x, y, width, height);
  8049. // Clear
  8050. this.clear(clearColor, true, true, true);
  8051. // Restore state
  8052. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8053. if (curScissor === true) {
  8054. gl.enable(gl.SCISSOR_TEST);
  8055. }
  8056. else {
  8057. gl.disable(gl.SCISSOR_TEST);
  8058. }
  8059. };
  8060. /**
  8061. * Set the WebGL's viewport
  8062. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8063. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8064. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8065. */
  8066. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8067. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8068. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8069. var x = viewport.x || 0;
  8070. var y = viewport.y || 0;
  8071. this._cachedViewport = viewport;
  8072. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8073. };
  8074. /**
  8075. * Directly set the WebGL Viewport
  8076. * The x, y, width & height are directly passed to the WebGL call
  8077. * @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.
  8078. */
  8079. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8080. var currentViewport = this._cachedViewport;
  8081. this._cachedViewport = null;
  8082. this._gl.viewport(x, y, width, height);
  8083. return currentViewport;
  8084. };
  8085. Engine.prototype.beginFrame = function () {
  8086. this._measureFps();
  8087. };
  8088. Engine.prototype.endFrame = function () {
  8089. //force a flush in case we are using a bad OS.
  8090. if (this._badOS) {
  8091. this.flushFramebuffer();
  8092. }
  8093. //submit frame to the vr device, if enabled
  8094. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8095. this._vrDisplayEnabled.submitFrame();
  8096. }
  8097. };
  8098. /**
  8099. * resize the view according to the canvas' size.
  8100. * @example
  8101. * window.addEventListener("resize", function () {
  8102. * engine.resize();
  8103. * });
  8104. */
  8105. Engine.prototype.resize = function () {
  8106. // We're not resizing the size of the canvas while in VR mode & presenting
  8107. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8108. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8109. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8110. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8111. }
  8112. };
  8113. /**
  8114. * force a specific size of the canvas
  8115. * @param {number} width - the new canvas' width
  8116. * @param {number} height - the new canvas' height
  8117. */
  8118. Engine.prototype.setSize = function (width, height) {
  8119. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8120. return;
  8121. }
  8122. this._renderingCanvas.width = width;
  8123. this._renderingCanvas.height = height;
  8124. for (var index = 0; index < this.scenes.length; index++) {
  8125. var scene = this.scenes[index];
  8126. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8127. var cam = scene.cameras[camIndex];
  8128. cam._currentRenderId = 0;
  8129. }
  8130. }
  8131. if (this.onResizeObservable.hasObservers) {
  8132. this.onResizeObservable.notifyObservers(this);
  8133. }
  8134. };
  8135. //WebVR functions
  8136. Engine.prototype.isVRDevicePresent = function (callback) {
  8137. this.getVRDevice(null, function (device) {
  8138. callback(device !== null);
  8139. });
  8140. };
  8141. Engine.prototype.getVRDevice = function (name, callback) {
  8142. if (!this.vrDisplaysPromise) {
  8143. callback(null);
  8144. return;
  8145. }
  8146. this.vrDisplaysPromise.then(function (devices) {
  8147. if (devices.length > 0) {
  8148. if (name) {
  8149. var found = devices.some(function (device) {
  8150. if (device.displayName === name) {
  8151. callback(device);
  8152. return true;
  8153. }
  8154. else {
  8155. return false;
  8156. }
  8157. });
  8158. if (!found) {
  8159. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8160. callback(devices[0]);
  8161. }
  8162. }
  8163. else {
  8164. //choose the first one
  8165. callback(devices[0]);
  8166. }
  8167. }
  8168. else {
  8169. BABYLON.Tools.Error("No WebVR devices found!");
  8170. callback(null);
  8171. }
  8172. });
  8173. };
  8174. Engine.prototype.initWebVR = function () {
  8175. if (!this.vrDisplaysPromise) {
  8176. this._getVRDisplays();
  8177. }
  8178. };
  8179. Engine.prototype.enableVR = function (vrDevice) {
  8180. this._vrDisplayEnabled = vrDevice;
  8181. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8182. };
  8183. Engine.prototype.disableVR = function () {
  8184. if (this._vrDisplayEnabled) {
  8185. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8186. }
  8187. };
  8188. Engine.prototype._getVRDisplays = function () {
  8189. var _this = this;
  8190. var getWebVRDevices = function (devices) {
  8191. var size = devices.length;
  8192. var i = 0;
  8193. _this._vrDisplays = devices.filter(function (device) {
  8194. return devices[i] instanceof VRDisplay;
  8195. });
  8196. return _this._vrDisplays;
  8197. };
  8198. //using a key due to typescript
  8199. if (navigator.getVRDisplays) {
  8200. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8201. }
  8202. };
  8203. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8204. this._currentRenderTarget = texture;
  8205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8206. var gl = this._gl;
  8207. if (texture.isCube) {
  8208. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8209. }
  8210. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8211. this.wipeCaches();
  8212. };
  8213. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8214. if (this._currentFramebuffer !== framebuffer) {
  8215. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8216. this._currentFramebuffer = framebuffer;
  8217. }
  8218. };
  8219. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8220. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8221. this._currentRenderTarget = null;
  8222. // If MSAA, we need to bitblt back to main texture
  8223. var gl = this._gl;
  8224. if (texture._MSAAFramebuffer) {
  8225. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8226. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8227. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8228. }
  8229. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8230. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8231. gl.generateMipmap(gl.TEXTURE_2D);
  8232. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8233. }
  8234. if (onBeforeUnbind) {
  8235. if (texture._MSAAFramebuffer) {
  8236. // Bind the correct framebuffer
  8237. this.bindUnboundFramebuffer(texture._framebuffer);
  8238. }
  8239. onBeforeUnbind();
  8240. }
  8241. this.bindUnboundFramebuffer(null);
  8242. };
  8243. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8244. if (texture.generateMipMaps) {
  8245. var gl = this._gl;
  8246. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8247. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8248. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8249. }
  8250. };
  8251. Engine.prototype.flushFramebuffer = function () {
  8252. this._gl.flush();
  8253. };
  8254. Engine.prototype.restoreDefaultFramebuffer = function () {
  8255. this._currentRenderTarget = null;
  8256. this.bindUnboundFramebuffer(null);
  8257. this.setViewport(this._cachedViewport);
  8258. this.wipeCaches();
  8259. };
  8260. // UBOs
  8261. Engine.prototype.createUniformBuffer = function (elements) {
  8262. var ubo = this._gl.createBuffer();
  8263. this.bindUniformBuffer(ubo);
  8264. if (elements instanceof Float32Array) {
  8265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8266. }
  8267. else {
  8268. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8269. }
  8270. this.bindUniformBuffer(null);
  8271. ubo.references = 1;
  8272. return ubo;
  8273. };
  8274. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8275. var ubo = this._gl.createBuffer();
  8276. this.bindUniformBuffer(ubo);
  8277. if (elements instanceof Float32Array) {
  8278. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8279. }
  8280. else {
  8281. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8282. }
  8283. this.bindUniformBuffer(null);
  8284. ubo.references = 1;
  8285. return ubo;
  8286. };
  8287. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8288. this.bindUniformBuffer(uniformBuffer);
  8289. if (offset === undefined) {
  8290. offset = 0;
  8291. }
  8292. if (count === undefined) {
  8293. if (elements instanceof Float32Array) {
  8294. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8295. }
  8296. else {
  8297. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8298. }
  8299. }
  8300. else {
  8301. if (elements instanceof Float32Array) {
  8302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8303. }
  8304. else {
  8305. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8306. }
  8307. }
  8308. this.bindUniformBuffer(null);
  8309. };
  8310. // VBOs
  8311. Engine.prototype._resetVertexBufferBinding = function () {
  8312. this.bindArrayBuffer(null);
  8313. this._cachedVertexBuffers = null;
  8314. };
  8315. Engine.prototype.createVertexBuffer = function (vertices) {
  8316. var vbo = this._gl.createBuffer();
  8317. this.bindArrayBuffer(vbo);
  8318. if (vertices instanceof Float32Array) {
  8319. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8320. }
  8321. else {
  8322. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8323. }
  8324. this._resetVertexBufferBinding();
  8325. vbo.references = 1;
  8326. return vbo;
  8327. };
  8328. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8329. var vbo = this._gl.createBuffer();
  8330. this.bindArrayBuffer(vbo);
  8331. if (vertices instanceof Float32Array) {
  8332. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8333. }
  8334. else {
  8335. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8336. }
  8337. this._resetVertexBufferBinding();
  8338. vbo.references = 1;
  8339. return vbo;
  8340. };
  8341. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8342. this.bindArrayBuffer(vertexBuffer);
  8343. if (offset === undefined) {
  8344. offset = 0;
  8345. }
  8346. if (count === undefined) {
  8347. if (vertices instanceof Float32Array) {
  8348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8349. }
  8350. else {
  8351. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8352. }
  8353. }
  8354. else {
  8355. if (vertices instanceof Float32Array) {
  8356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8357. }
  8358. else {
  8359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8360. }
  8361. }
  8362. this._resetVertexBufferBinding();
  8363. };
  8364. Engine.prototype._resetIndexBufferBinding = function () {
  8365. this.bindIndexBuffer(null);
  8366. this._cachedIndexBuffer = null;
  8367. };
  8368. Engine.prototype.createIndexBuffer = function (indices) {
  8369. var vbo = this._gl.createBuffer();
  8370. this.bindIndexBuffer(vbo);
  8371. // Check for 32 bits indices
  8372. var arrayBuffer;
  8373. var need32Bits = false;
  8374. if (indices instanceof Uint16Array) {
  8375. arrayBuffer = indices;
  8376. }
  8377. else {
  8378. //check 32 bit support
  8379. if (this._caps.uintIndices) {
  8380. if (indices instanceof Uint32Array) {
  8381. arrayBuffer = indices;
  8382. need32Bits = true;
  8383. }
  8384. else {
  8385. //number[] or Int32Array, check if 32 bit is necessary
  8386. for (var index = 0; index < indices.length; index++) {
  8387. if (indices[index] > 65535) {
  8388. need32Bits = true;
  8389. break;
  8390. }
  8391. }
  8392. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8393. }
  8394. }
  8395. else {
  8396. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8397. arrayBuffer = new Uint16Array(indices);
  8398. }
  8399. }
  8400. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8401. this._resetIndexBufferBinding();
  8402. vbo.references = 1;
  8403. vbo.is32Bits = need32Bits;
  8404. return vbo;
  8405. };
  8406. Engine.prototype.bindArrayBuffer = function (buffer) {
  8407. if (!this._vaoRecordInProgress) {
  8408. this._unBindVertexArrayObject();
  8409. }
  8410. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8411. };
  8412. Engine.prototype.bindUniformBuffer = function (buffer) {
  8413. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8414. };
  8415. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8416. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8417. };
  8418. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8419. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8420. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8421. };
  8422. ;
  8423. Engine.prototype.bindIndexBuffer = function (buffer) {
  8424. if (!this._vaoRecordInProgress) {
  8425. this._unBindVertexArrayObject();
  8426. }
  8427. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8428. };
  8429. Engine.prototype.bindBuffer = function (buffer, target) {
  8430. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8431. this._gl.bindBuffer(target, buffer);
  8432. this._currentBoundBuffer[target] = buffer;
  8433. }
  8434. };
  8435. Engine.prototype.updateArrayBuffer = function (data) {
  8436. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8437. };
  8438. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8439. var pointer = this._currentBufferPointers[indx];
  8440. var changed = false;
  8441. if (!pointer) {
  8442. changed = true;
  8443. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8444. }
  8445. else {
  8446. if (pointer.buffer !== buffer) {
  8447. pointer.buffer = buffer;
  8448. changed = true;
  8449. }
  8450. if (pointer.size !== size) {
  8451. pointer.size = size;
  8452. changed = true;
  8453. }
  8454. if (pointer.type !== type) {
  8455. pointer.type = type;
  8456. changed = true;
  8457. }
  8458. if (pointer.normalized !== normalized) {
  8459. pointer.normalized = normalized;
  8460. changed = true;
  8461. }
  8462. if (pointer.stride !== stride) {
  8463. pointer.stride = stride;
  8464. changed = true;
  8465. }
  8466. if (pointer.offset !== offset) {
  8467. pointer.offset = offset;
  8468. changed = true;
  8469. }
  8470. }
  8471. if (changed || this._vaoRecordInProgress) {
  8472. this.bindArrayBuffer(buffer);
  8473. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8474. }
  8475. };
  8476. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8477. if (indexBuffer == null) {
  8478. return;
  8479. }
  8480. if (this._cachedIndexBuffer !== indexBuffer) {
  8481. this._cachedIndexBuffer = indexBuffer;
  8482. this.bindIndexBuffer(indexBuffer);
  8483. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8484. }
  8485. };
  8486. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8487. var attributes = effect.getAttributesNames();
  8488. if (!this._vaoRecordInProgress) {
  8489. this._unBindVertexArrayObject();
  8490. }
  8491. this.unbindAllAttributes();
  8492. for (var index = 0; index < attributes.length; index++) {
  8493. var order = effect.getAttributeLocation(index);
  8494. if (order >= 0) {
  8495. var vertexBuffer = vertexBuffers[attributes[index]];
  8496. if (!vertexBuffer) {
  8497. continue;
  8498. }
  8499. this._gl.enableVertexAttribArray(order);
  8500. if (!this._vaoRecordInProgress) {
  8501. this._vertexAttribArraysEnabled[order] = true;
  8502. }
  8503. var buffer = vertexBuffer.getBuffer();
  8504. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8505. if (vertexBuffer.getIsInstanced()) {
  8506. this._gl.vertexAttribDivisor(order, 1);
  8507. if (!this._vaoRecordInProgress) {
  8508. this._currentInstanceLocations.push(order);
  8509. this._currentInstanceBuffers.push(buffer);
  8510. }
  8511. }
  8512. }
  8513. }
  8514. };
  8515. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8516. var vao = this._gl.createVertexArray();
  8517. this._vaoRecordInProgress = true;
  8518. this._gl.bindVertexArray(vao);
  8519. this._mustWipeVertexAttributes = true;
  8520. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8521. this.bindIndexBuffer(indexBuffer);
  8522. this._vaoRecordInProgress = false;
  8523. this._gl.bindVertexArray(null);
  8524. return vao;
  8525. };
  8526. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8527. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8528. this._cachedVertexArrayObject = vertexArrayObject;
  8529. this._gl.bindVertexArray(vertexArrayObject);
  8530. this._cachedVertexBuffers = null;
  8531. this._cachedIndexBuffer = null;
  8532. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8533. this._mustWipeVertexAttributes = true;
  8534. }
  8535. };
  8536. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8537. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8538. this._cachedVertexBuffers = vertexBuffer;
  8539. this._cachedEffectForVertexBuffers = effect;
  8540. var attributesCount = effect.getAttributesCount();
  8541. this._unBindVertexArrayObject();
  8542. this.unbindAllAttributes();
  8543. var offset = 0;
  8544. for (var index = 0; index < attributesCount; index++) {
  8545. if (index < vertexDeclaration.length) {
  8546. var order = effect.getAttributeLocation(index);
  8547. if (order >= 0) {
  8548. this._gl.enableVertexAttribArray(order);
  8549. this._vertexAttribArraysEnabled[order] = true;
  8550. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8551. }
  8552. offset += vertexDeclaration[index] * 4;
  8553. }
  8554. }
  8555. }
  8556. this._bindIndexBufferWithCache(indexBuffer);
  8557. };
  8558. Engine.prototype._unBindVertexArrayObject = function () {
  8559. if (!this._cachedVertexArrayObject) {
  8560. return;
  8561. }
  8562. this._cachedVertexArrayObject = null;
  8563. this._gl.bindVertexArray(null);
  8564. };
  8565. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8566. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8567. this._cachedVertexBuffers = vertexBuffers;
  8568. this._cachedEffectForVertexBuffers = effect;
  8569. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8570. }
  8571. this._bindIndexBufferWithCache(indexBuffer);
  8572. };
  8573. Engine.prototype.unbindInstanceAttributes = function () {
  8574. var boundBuffer;
  8575. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8576. var instancesBuffer = this._currentInstanceBuffers[i];
  8577. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8578. boundBuffer = instancesBuffer;
  8579. this.bindArrayBuffer(instancesBuffer);
  8580. }
  8581. var offsetLocation = this._currentInstanceLocations[i];
  8582. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8583. }
  8584. this._currentInstanceBuffers.length = 0;
  8585. this._currentInstanceLocations.length = 0;
  8586. };
  8587. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8588. this._gl.deleteVertexArray(vao);
  8589. };
  8590. Engine.prototype._releaseBuffer = function (buffer) {
  8591. buffer.references--;
  8592. if (buffer.references === 0) {
  8593. this._gl.deleteBuffer(buffer);
  8594. return true;
  8595. }
  8596. return false;
  8597. };
  8598. Engine.prototype.createInstancesBuffer = function (capacity) {
  8599. var buffer = this._gl.createBuffer();
  8600. buffer.capacity = capacity;
  8601. this.bindArrayBuffer(buffer);
  8602. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8603. return buffer;
  8604. };
  8605. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8606. this._gl.deleteBuffer(buffer);
  8607. };
  8608. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8609. this.bindArrayBuffer(instancesBuffer);
  8610. if (data) {
  8611. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8612. }
  8613. if (offsetLocations[0].index !== undefined) {
  8614. var stride = 0;
  8615. for (var i = 0; i < offsetLocations.length; i++) {
  8616. var ai = offsetLocations[i];
  8617. stride += ai.attributeSize * 4;
  8618. }
  8619. for (var i = 0; i < offsetLocations.length; i++) {
  8620. var ai = offsetLocations[i];
  8621. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8622. this._gl.enableVertexAttribArray(ai.index);
  8623. this._vertexAttribArraysEnabled[ai.index] = true;
  8624. }
  8625. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8626. this._gl.vertexAttribDivisor(ai.index, 1);
  8627. this._currentInstanceLocations.push(ai.index);
  8628. this._currentInstanceBuffers.push(instancesBuffer);
  8629. }
  8630. }
  8631. else {
  8632. for (var index = 0; index < 4; index++) {
  8633. var offsetLocation = offsetLocations[index];
  8634. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8635. this._gl.enableVertexAttribArray(offsetLocation);
  8636. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8637. }
  8638. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8639. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8640. this._currentInstanceLocations.push(offsetLocation);
  8641. this._currentInstanceBuffers.push(instancesBuffer);
  8642. }
  8643. }
  8644. };
  8645. Engine.prototype.applyStates = function () {
  8646. this._depthCullingState.apply(this._gl);
  8647. this._stencilState.apply(this._gl);
  8648. this._alphaState.apply(this._gl);
  8649. };
  8650. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8651. // Apply states
  8652. this.applyStates();
  8653. this._drawCalls.addCount(1, false);
  8654. // Render
  8655. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8656. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8657. if (instancesCount) {
  8658. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8659. return;
  8660. }
  8661. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8662. };
  8663. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8664. // Apply states
  8665. this.applyStates();
  8666. this._drawCalls.addCount(1, false);
  8667. if (instancesCount) {
  8668. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8669. return;
  8670. }
  8671. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8672. };
  8673. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8674. // Apply states
  8675. this.applyStates();
  8676. this._drawCalls.addCount(1, false);
  8677. if (instancesCount) {
  8678. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8679. return;
  8680. }
  8681. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8682. };
  8683. // Shaders
  8684. Engine.prototype._releaseEffect = function (effect) {
  8685. if (this._compiledEffects[effect._key]) {
  8686. delete this._compiledEffects[effect._key];
  8687. if (effect.getProgram()) {
  8688. this._gl.deleteProgram(effect.getProgram());
  8689. }
  8690. }
  8691. };
  8692. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8693. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8694. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8695. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8696. if (this._compiledEffects[name]) {
  8697. return this._compiledEffects[name];
  8698. }
  8699. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8700. effect._key = name;
  8701. this._compiledEffects[name] = effect;
  8702. return effect;
  8703. };
  8704. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8705. if (uniformsNames === void 0) { uniformsNames = []; }
  8706. if (samplers === void 0) { samplers = []; }
  8707. if (defines === void 0) { defines = ""; }
  8708. return this.createEffect({
  8709. vertex: "particles",
  8710. fragmentElement: fragmentName
  8711. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8712. };
  8713. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8714. context = context || this._gl;
  8715. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8716. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8717. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8718. var shaderProgram = context.createProgram();
  8719. context.attachShader(shaderProgram, vertexShader);
  8720. context.attachShader(shaderProgram, fragmentShader);
  8721. context.linkProgram(shaderProgram);
  8722. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8723. if (!linked) {
  8724. var error = context.getProgramInfoLog(shaderProgram);
  8725. if (error) {
  8726. throw new Error(error);
  8727. }
  8728. }
  8729. context.deleteShader(vertexShader);
  8730. context.deleteShader(fragmentShader);
  8731. return shaderProgram;
  8732. };
  8733. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8734. var results = [];
  8735. for (var index = 0; index < uniformsNames.length; index++) {
  8736. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8737. }
  8738. return results;
  8739. };
  8740. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8741. var results = [];
  8742. for (var index = 0; index < attributesNames.length; index++) {
  8743. try {
  8744. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8745. }
  8746. catch (e) {
  8747. results.push(-1);
  8748. }
  8749. }
  8750. return results;
  8751. };
  8752. Engine.prototype.enableEffect = function (effect) {
  8753. // Use program
  8754. this.setProgram(effect.getProgram());
  8755. this._currentEffect = effect;
  8756. if (effect.onBind) {
  8757. effect.onBind(effect);
  8758. }
  8759. };
  8760. Engine.prototype.setIntArray = function (uniform, array) {
  8761. if (!uniform)
  8762. return;
  8763. this._gl.uniform1iv(uniform, array);
  8764. };
  8765. Engine.prototype.setIntArray2 = function (uniform, array) {
  8766. if (!uniform || array.length % 2 !== 0)
  8767. return;
  8768. this._gl.uniform2iv(uniform, array);
  8769. };
  8770. Engine.prototype.setIntArray3 = function (uniform, array) {
  8771. if (!uniform || array.length % 3 !== 0)
  8772. return;
  8773. this._gl.uniform3iv(uniform, array);
  8774. };
  8775. Engine.prototype.setIntArray4 = function (uniform, array) {
  8776. if (!uniform || array.length % 4 !== 0)
  8777. return;
  8778. this._gl.uniform4iv(uniform, array);
  8779. };
  8780. Engine.prototype.setFloatArray = function (uniform, array) {
  8781. if (!uniform)
  8782. return;
  8783. this._gl.uniform1fv(uniform, array);
  8784. };
  8785. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8786. if (!uniform || array.length % 2 !== 0)
  8787. return;
  8788. this._gl.uniform2fv(uniform, array);
  8789. };
  8790. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8791. if (!uniform || array.length % 3 !== 0)
  8792. return;
  8793. this._gl.uniform3fv(uniform, array);
  8794. };
  8795. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8796. if (!uniform || array.length % 4 !== 0)
  8797. return;
  8798. this._gl.uniform4fv(uniform, array);
  8799. };
  8800. Engine.prototype.setArray = function (uniform, array) {
  8801. if (!uniform)
  8802. return;
  8803. this._gl.uniform1fv(uniform, array);
  8804. };
  8805. Engine.prototype.setArray2 = function (uniform, array) {
  8806. if (!uniform || array.length % 2 !== 0)
  8807. return;
  8808. this._gl.uniform2fv(uniform, array);
  8809. };
  8810. Engine.prototype.setArray3 = function (uniform, array) {
  8811. if (!uniform || array.length % 3 !== 0)
  8812. return;
  8813. this._gl.uniform3fv(uniform, array);
  8814. };
  8815. Engine.prototype.setArray4 = function (uniform, array) {
  8816. if (!uniform || array.length % 4 !== 0)
  8817. return;
  8818. this._gl.uniform4fv(uniform, array);
  8819. };
  8820. Engine.prototype.setMatrices = function (uniform, matrices) {
  8821. if (!uniform)
  8822. return;
  8823. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8824. };
  8825. Engine.prototype.setMatrix = function (uniform, matrix) {
  8826. if (!uniform)
  8827. return;
  8828. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8829. };
  8830. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8831. if (!uniform)
  8832. return;
  8833. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8834. };
  8835. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8836. if (!uniform)
  8837. return;
  8838. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8839. };
  8840. Engine.prototype.setFloat = function (uniform, value) {
  8841. if (!uniform)
  8842. return;
  8843. this._gl.uniform1f(uniform, value);
  8844. };
  8845. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8846. if (!uniform)
  8847. return;
  8848. this._gl.uniform2f(uniform, x, y);
  8849. };
  8850. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8851. if (!uniform)
  8852. return;
  8853. this._gl.uniform3f(uniform, x, y, z);
  8854. };
  8855. Engine.prototype.setBool = function (uniform, bool) {
  8856. if (!uniform)
  8857. return;
  8858. this._gl.uniform1i(uniform, bool);
  8859. };
  8860. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8861. if (!uniform)
  8862. return;
  8863. this._gl.uniform4f(uniform, x, y, z, w);
  8864. };
  8865. Engine.prototype.setColor3 = function (uniform, color3) {
  8866. if (!uniform)
  8867. return;
  8868. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8869. };
  8870. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8871. if (!uniform)
  8872. return;
  8873. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8874. };
  8875. // States
  8876. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8877. if (zOffset === void 0) { zOffset = 0; }
  8878. if (reverseSide === void 0) { reverseSide = false; }
  8879. // Culling
  8880. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8881. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8882. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8883. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8884. if (culling) {
  8885. this._depthCullingState.cullFace = cullFace;
  8886. this._depthCullingState.cull = true;
  8887. }
  8888. else {
  8889. this._depthCullingState.cull = false;
  8890. }
  8891. }
  8892. // Z offset
  8893. this._depthCullingState.zOffset = zOffset;
  8894. };
  8895. Engine.prototype.setDepthBuffer = function (enable) {
  8896. this._depthCullingState.depthTest = enable;
  8897. };
  8898. Engine.prototype.getDepthWrite = function () {
  8899. return this._depthCullingState.depthMask;
  8900. };
  8901. Engine.prototype.setDepthWrite = function (enable) {
  8902. this._depthCullingState.depthMask = enable;
  8903. };
  8904. Engine.prototype.setColorWrite = function (enable) {
  8905. this._gl.colorMask(enable, enable, enable, enable);
  8906. };
  8907. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8908. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8909. };
  8910. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8911. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8912. if (this._alphaMode === mode) {
  8913. return;
  8914. }
  8915. switch (mode) {
  8916. case Engine.ALPHA_DISABLE:
  8917. this._alphaState.alphaBlend = false;
  8918. break;
  8919. case Engine.ALPHA_PREMULTIPLIED:
  8920. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8921. this._alphaState.alphaBlend = true;
  8922. break;
  8923. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8924. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8925. this._alphaState.alphaBlend = true;
  8926. break;
  8927. case Engine.ALPHA_COMBINE:
  8928. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8929. this._alphaState.alphaBlend = true;
  8930. break;
  8931. case Engine.ALPHA_ONEONE:
  8932. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8933. this._alphaState.alphaBlend = true;
  8934. break;
  8935. case Engine.ALPHA_ADD:
  8936. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8937. this._alphaState.alphaBlend = true;
  8938. break;
  8939. case Engine.ALPHA_SUBTRACT:
  8940. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8941. this._alphaState.alphaBlend = true;
  8942. break;
  8943. case Engine.ALPHA_MULTIPLY:
  8944. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8945. this._alphaState.alphaBlend = true;
  8946. break;
  8947. case Engine.ALPHA_MAXIMIZED:
  8948. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8949. this._alphaState.alphaBlend = true;
  8950. break;
  8951. case Engine.ALPHA_INTERPOLATE:
  8952. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8953. this._alphaState.alphaBlend = true;
  8954. break;
  8955. case Engine.ALPHA_SCREENMODE:
  8956. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8957. this._alphaState.alphaBlend = true;
  8958. break;
  8959. }
  8960. if (!noDepthWriteChange) {
  8961. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8962. }
  8963. this._alphaMode = mode;
  8964. };
  8965. Engine.prototype.getAlphaMode = function () {
  8966. return this._alphaMode;
  8967. };
  8968. Engine.prototype.setAlphaTesting = function (enable) {
  8969. this._alphaTest = enable;
  8970. };
  8971. Engine.prototype.getAlphaTesting = function () {
  8972. return !!this._alphaTest;
  8973. };
  8974. // Textures
  8975. Engine.prototype.wipeCaches = function (bruteForce) {
  8976. if (this.preventCacheWipeBetweenFrames) {
  8977. return;
  8978. }
  8979. this.resetTextureCache();
  8980. this._currentEffect = null;
  8981. // 6/8/2017: deltakosh: Should not be required anymore.
  8982. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8983. if (bruteForce) {
  8984. this._stencilState.reset();
  8985. this._depthCullingState.reset();
  8986. this.setDepthFunctionToLessOrEqual();
  8987. this._alphaState.reset();
  8988. }
  8989. this._cachedVertexBuffers = null;
  8990. this._cachedIndexBuffer = null;
  8991. this._cachedEffectForVertexBuffers = null;
  8992. this._unBindVertexArrayObject();
  8993. this.bindIndexBuffer(null);
  8994. this.bindArrayBuffer(null);
  8995. };
  8996. /**
  8997. * Set the compressed texture format to use, based on the formats you have, and the formats
  8998. * supported by the hardware / browser.
  8999. *
  9000. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9001. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9002. * to API arguments needed to compressed textures. This puts the burden on the container
  9003. * generator to house the arcane code for determining these for current & future formats.
  9004. *
  9005. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9006. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9007. *
  9008. * Note: The result of this call is not taken into account when a texture is base64.
  9009. *
  9010. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9011. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9012. *
  9013. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9014. * @returns The extension selected.
  9015. */
  9016. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9017. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9018. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9019. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9020. return this._textureFormatInUse = this._texturesSupported[i];
  9021. }
  9022. }
  9023. }
  9024. // actively set format to nothing, to allow this to be called more than once
  9025. // and possibly fail the 2nd time
  9026. return this._textureFormatInUse = null;
  9027. };
  9028. /**
  9029. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9030. * @param {string} urlArg- This contains one of the following:
  9031. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9032. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9033. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9034. *
  9035. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9036. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9037. * @param {Scene} scene- Needed for loading to the correct scene.
  9038. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9039. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9040. * @param {callback} onError- Optional callback to be called upon failure.
  9041. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9042. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9043. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9044. *
  9045. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9046. */
  9047. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9048. var _this = this;
  9049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9050. if (onLoad === void 0) { onLoad = null; }
  9051. if (onError === void 0) { onError = null; }
  9052. if (buffer === void 0) { buffer = null; }
  9053. var texture = fallBack ? fallBack : this._gl.createTexture();
  9054. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9055. var fromData = url.substr(0, 5) === "data:";
  9056. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9057. // establish the file extension, if possible
  9058. var lastDot = url.lastIndexOf('.');
  9059. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9060. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9061. if (isDDS) {
  9062. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9063. }
  9064. var isTGA = (extension === ".tga");
  9065. // determine if a ktx file should be substituted
  9066. var isKTX = false;
  9067. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9068. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9069. isKTX = true;
  9070. }
  9071. scene._addPendingData(texture);
  9072. texture.url = url;
  9073. texture.noMipmap = noMipmap;
  9074. texture.references = 1;
  9075. texture.samplingMode = samplingMode;
  9076. texture.onLoadedCallbacks = [];
  9077. if (onLoad) {
  9078. texture.onLoadedCallbacks.push(onLoad);
  9079. }
  9080. if (!fallBack)
  9081. this._loadedTexturesCache.push(texture);
  9082. var onerror = function () {
  9083. scene._removePendingData(texture);
  9084. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9085. if (isKTX) {
  9086. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9087. }
  9088. else if (onError) {
  9089. onError();
  9090. }
  9091. };
  9092. var callback;
  9093. // processing for non-image formats
  9094. if (isKTX || isTGA || isDDS) {
  9095. if (isKTX) {
  9096. callback = function (data) {
  9097. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9098. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9099. ktx.uploadLevels(_this._gl, !noMipmap);
  9100. }, samplingMode);
  9101. };
  9102. }
  9103. else if (isTGA) {
  9104. callback = function (arrayBuffer) {
  9105. var data = new Uint8Array(arrayBuffer);
  9106. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9107. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9108. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9109. }, samplingMode);
  9110. };
  9111. }
  9112. else if (isDDS) {
  9113. callback = function (data) {
  9114. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9115. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9116. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9117. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9118. }, samplingMode);
  9119. };
  9120. }
  9121. if (!buffer) {
  9122. BABYLON.Tools.LoadFile(url, function (data) {
  9123. callback(data);
  9124. }, null, scene.database, true, onerror);
  9125. }
  9126. else {
  9127. callback(buffer);
  9128. }
  9129. // image format processing
  9130. }
  9131. else {
  9132. var onload = function (img) {
  9133. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9134. var isPot = (img.width === potWidth && img.height === potHeight);
  9135. if (!isPot) {
  9136. _this._prepareWorkingCanvas();
  9137. _this._workingCanvas.width = potWidth;
  9138. _this._workingCanvas.height = potHeight;
  9139. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9140. _this._workingContext.imageSmoothingEnabled = false;
  9141. _this._workingContext.mozImageSmoothingEnabled = false;
  9142. _this._workingContext.oImageSmoothingEnabled = false;
  9143. _this._workingContext.webkitImageSmoothingEnabled = false;
  9144. _this._workingContext.msImageSmoothingEnabled = false;
  9145. }
  9146. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9147. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9148. _this._workingContext.imageSmoothingEnabled = true;
  9149. _this._workingContext.mozImageSmoothingEnabled = true;
  9150. _this._workingContext.oImageSmoothingEnabled = true;
  9151. _this._workingContext.webkitImageSmoothingEnabled = true;
  9152. _this._workingContext.msImageSmoothingEnabled = true;
  9153. }
  9154. }
  9155. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9156. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9157. }, samplingMode);
  9158. };
  9159. if (!fromData || isBase64)
  9160. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9161. else if (buffer instanceof Array || typeof buffer === "string")
  9162. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9163. else
  9164. onload(buffer);
  9165. }
  9166. return texture;
  9167. };
  9168. Engine.prototype._getInternalFormat = function (format) {
  9169. var internalFormat = this._gl.RGBA;
  9170. switch (format) {
  9171. case Engine.TEXTUREFORMAT_ALPHA:
  9172. internalFormat = this._gl.ALPHA;
  9173. break;
  9174. case Engine.TEXTUREFORMAT_LUMINANCE:
  9175. internalFormat = this._gl.LUMINANCE;
  9176. break;
  9177. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9178. internalFormat = this._gl.LUMINANCE_ALPHA;
  9179. break;
  9180. case Engine.TEXTUREFORMAT_RGB:
  9181. internalFormat = this._gl.RGB;
  9182. break;
  9183. case Engine.TEXTUREFORMAT_RGBA:
  9184. internalFormat = this._gl.RGBA;
  9185. break;
  9186. }
  9187. return internalFormat;
  9188. };
  9189. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9190. if (compression === void 0) { compression = null; }
  9191. var internalFormat = this._getInternalFormat(format);
  9192. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9193. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9194. if (texture._width % 4 !== 0) {
  9195. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9196. }
  9197. if (compression) {
  9198. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9199. }
  9200. else {
  9201. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9202. }
  9203. if (texture.generateMipMaps) {
  9204. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9205. }
  9206. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9207. this.resetTextureCache();
  9208. texture.isReady = true;
  9209. };
  9210. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9211. if (compression === void 0) { compression = null; }
  9212. var texture = this._gl.createTexture();
  9213. texture._baseWidth = width;
  9214. texture._baseHeight = height;
  9215. texture._width = width;
  9216. texture._height = height;
  9217. texture.references = 1;
  9218. this.updateRawTexture(texture, data, format, invertY, compression);
  9219. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9220. // Filters
  9221. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9222. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9224. if (generateMipMaps) {
  9225. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9226. }
  9227. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9228. texture.samplingMode = samplingMode;
  9229. this._loadedTexturesCache.push(texture);
  9230. return texture;
  9231. };
  9232. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9233. var texture = this._gl.createTexture();
  9234. texture._baseWidth = width;
  9235. texture._baseHeight = height;
  9236. if (generateMipMaps) {
  9237. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9238. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9239. }
  9240. this.resetTextureCache();
  9241. texture._width = width;
  9242. texture._height = height;
  9243. texture.isReady = false;
  9244. texture.generateMipMaps = generateMipMaps;
  9245. texture.references = 1;
  9246. texture.samplingMode = samplingMode;
  9247. this.updateTextureSamplingMode(samplingMode, texture);
  9248. this._loadedTexturesCache.push(texture);
  9249. return texture;
  9250. };
  9251. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9252. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9253. if (texture.isCube) {
  9254. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9255. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9256. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9257. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9258. }
  9259. else {
  9260. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9261. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9262. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9263. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9264. }
  9265. texture.samplingMode = samplingMode;
  9266. };
  9267. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9268. if (premulAlpha === void 0) { premulAlpha = false; }
  9269. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9270. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9271. if (premulAlpha) {
  9272. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9273. }
  9274. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9275. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9276. if (texture.generateMipMaps) {
  9277. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9278. }
  9279. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9280. if (premulAlpha) {
  9281. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9282. }
  9283. this.resetTextureCache();
  9284. texture.isReady = true;
  9285. };
  9286. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9287. if (texture._isDisabled) {
  9288. return;
  9289. }
  9290. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9291. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9292. try {
  9293. // Testing video texture support
  9294. if (this._videoTextureSupported === undefined) {
  9295. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9296. if (this._gl.getError() !== 0) {
  9297. this._videoTextureSupported = false;
  9298. }
  9299. else {
  9300. this._videoTextureSupported = true;
  9301. }
  9302. }
  9303. // Copy video through the current working canvas if video texture is not supported
  9304. if (!this._videoTextureSupported) {
  9305. if (!texture._workingCanvas) {
  9306. texture._workingCanvas = document.createElement("canvas");
  9307. texture._workingContext = texture._workingCanvas.getContext("2d");
  9308. texture._workingCanvas.width = texture._width;
  9309. texture._workingCanvas.height = texture._height;
  9310. }
  9311. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9312. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9313. }
  9314. else {
  9315. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9316. }
  9317. if (texture.generateMipMaps) {
  9318. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9319. }
  9320. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9321. this.resetTextureCache();
  9322. texture.isReady = true;
  9323. }
  9324. catch (ex) {
  9325. // Something unexpected
  9326. // Let's disable the texture
  9327. texture._isDisabled = true;
  9328. }
  9329. };
  9330. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9331. // old version had a "generateMipMaps" arg instead of options.
  9332. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9333. // in the same way, generateDepthBuffer is defaulted to true
  9334. var generateMipMaps = false;
  9335. var generateDepthBuffer = true;
  9336. var generateStencilBuffer = false;
  9337. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9338. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9339. if (options !== undefined) {
  9340. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9341. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9342. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9343. type = options.type === undefined ? type : options.type;
  9344. if (options.samplingMode !== undefined) {
  9345. samplingMode = options.samplingMode;
  9346. }
  9347. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9348. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9349. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9350. }
  9351. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9352. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9353. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9354. }
  9355. }
  9356. var gl = this._gl;
  9357. var texture = gl.createTexture();
  9358. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9359. var width = size.width || size;
  9360. var height = size.height || size;
  9361. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9362. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9363. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9364. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9365. }
  9366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9370. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9371. // Create the framebuffer
  9372. var framebuffer = gl.createFramebuffer();
  9373. this.bindUnboundFramebuffer(framebuffer);
  9374. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9375. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9376. if (generateMipMaps) {
  9377. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9378. }
  9379. // Unbind
  9380. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9381. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9382. this.bindUnboundFramebuffer(null);
  9383. texture._framebuffer = framebuffer;
  9384. texture._baseWidth = width;
  9385. texture._baseHeight = height;
  9386. texture._width = width;
  9387. texture._height = height;
  9388. texture.isReady = true;
  9389. texture.samples = 1;
  9390. texture.generateMipMaps = generateMipMaps;
  9391. texture.references = 1;
  9392. texture.samplingMode = samplingMode;
  9393. texture.type = type;
  9394. texture._generateDepthBuffer = generateDepthBuffer;
  9395. texture._generateStencilBuffer = generateStencilBuffer;
  9396. this.resetTextureCache();
  9397. this._loadedTexturesCache.push(texture);
  9398. return texture;
  9399. };
  9400. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9401. var generateMipMaps = false;
  9402. var generateDepthBuffer = true;
  9403. var generateStencilBuffer = false;
  9404. var generateDepthTexture = false;
  9405. var textureCount = 1;
  9406. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9407. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9408. var types = [], samplingModes = [];
  9409. if (options !== undefined) {
  9410. generateMipMaps = options.generateMipMaps;
  9411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9412. generateStencilBuffer = options.generateStencilBuffer;
  9413. generateDepthTexture = options.generateDepthTexture;
  9414. textureCount = options.textureCount || 1;
  9415. if (options.types) {
  9416. types = options.types;
  9417. }
  9418. if (options.samplingModes) {
  9419. samplingModes = options.samplingModes;
  9420. }
  9421. }
  9422. var gl = this._gl;
  9423. // Create the framebuffer
  9424. var framebuffer = gl.createFramebuffer();
  9425. this.bindUnboundFramebuffer(framebuffer);
  9426. var colorRenderbuffer = gl.createRenderbuffer();
  9427. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9428. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9429. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9430. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9431. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9432. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9433. var width = size.width || size;
  9434. var height = size.height || size;
  9435. var textures = [];
  9436. var attachments = [];
  9437. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9438. for (var i = 0; i < textureCount; i++) {
  9439. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9440. var type = types[i] || defaultType;
  9441. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9442. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9443. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9444. }
  9445. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9446. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9447. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9448. }
  9449. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9450. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9451. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9452. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9453. }
  9454. var texture = gl.createTexture();
  9455. var attachment = gl["COLOR_ATTACHMENT" + i];
  9456. textures.push(texture);
  9457. attachments.push(attachment);
  9458. gl.activeTexture(gl["TEXTURE" + i]);
  9459. gl.bindTexture(gl.TEXTURE_2D, texture);
  9460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9461. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9462. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9463. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9464. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9465. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9466. if (generateMipMaps) {
  9467. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9468. }
  9469. // Unbind
  9470. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9471. texture._framebuffer = framebuffer;
  9472. texture._depthStencilBuffer = depthStencilBuffer;
  9473. texture._baseWidth = width;
  9474. texture._baseHeight = height;
  9475. texture._width = width;
  9476. texture._height = height;
  9477. texture.isReady = true;
  9478. texture.samples = 1;
  9479. texture.generateMipMaps = generateMipMaps;
  9480. texture.references = 1;
  9481. texture.samplingMode = samplingMode;
  9482. texture.type = type;
  9483. texture._generateDepthBuffer = generateDepthBuffer;
  9484. texture._generateStencilBuffer = generateStencilBuffer;
  9485. this._loadedTexturesCache.push(texture);
  9486. }
  9487. if (generateDepthTexture) {
  9488. // Depth texture
  9489. var depthTexture = gl.createTexture();
  9490. gl.activeTexture(gl.TEXTURE0);
  9491. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9493. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9494. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9495. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9496. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9497. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9498. depthTexture._framebuffer = framebuffer;
  9499. depthTexture._baseWidth = width;
  9500. depthTexture._baseHeight = height;
  9501. depthTexture._width = width;
  9502. depthTexture._height = height;
  9503. depthTexture.isReady = true;
  9504. depthTexture.samples = 1;
  9505. depthTexture.generateMipMaps = generateMipMaps;
  9506. depthTexture.references = 1;
  9507. depthTexture.samplingMode = gl.NEAREST;
  9508. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9509. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9510. textures.push(depthTexture);
  9511. this._loadedTexturesCache.push(depthTexture);
  9512. }
  9513. gl.drawBuffers(attachments);
  9514. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9515. this.bindUnboundFramebuffer(null);
  9516. this.resetTextureCache();
  9517. return textures;
  9518. };
  9519. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9520. if (samples === void 0) { samples = 1; }
  9521. var depthStencilBuffer = null;
  9522. var gl = this._gl;
  9523. // Create the depth/stencil buffer
  9524. if (generateStencilBuffer) {
  9525. depthStencilBuffer = gl.createRenderbuffer();
  9526. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9527. if (samples > 1) {
  9528. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9529. }
  9530. else {
  9531. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9532. }
  9533. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9534. }
  9535. else if (generateDepthBuffer) {
  9536. depthStencilBuffer = gl.createRenderbuffer();
  9537. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9538. if (samples > 1) {
  9539. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9540. }
  9541. else {
  9542. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9543. }
  9544. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9545. }
  9546. return depthStencilBuffer;
  9547. };
  9548. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9549. if (this.webGLVersion < 2) {
  9550. return 1;
  9551. }
  9552. if (texture.samples === samples) {
  9553. return samples;
  9554. }
  9555. var gl = this._gl;
  9556. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9557. // Dispose previous render buffers
  9558. if (texture._depthStencilBuffer) {
  9559. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9560. }
  9561. if (texture._MSAAFramebuffer) {
  9562. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9563. }
  9564. if (texture._MSAARenderBuffer) {
  9565. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9566. }
  9567. if (samples > 1) {
  9568. texture._MSAAFramebuffer = gl.createFramebuffer();
  9569. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9570. var colorRenderbuffer = gl.createRenderbuffer();
  9571. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9572. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9573. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9574. texture._MSAARenderBuffer = colorRenderbuffer;
  9575. }
  9576. else {
  9577. this.bindUnboundFramebuffer(texture._framebuffer);
  9578. }
  9579. texture.samples = samples;
  9580. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9581. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9582. this.bindUnboundFramebuffer(null);
  9583. return samples;
  9584. };
  9585. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9586. var gl = this._gl;
  9587. var texture = gl.createTexture();
  9588. var generateMipMaps = true;
  9589. var generateDepthBuffer = true;
  9590. var generateStencilBuffer = false;
  9591. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9592. if (options !== undefined) {
  9593. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9594. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9595. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9596. if (options.samplingMode !== undefined) {
  9597. samplingMode = options.samplingMode;
  9598. }
  9599. }
  9600. texture.isCube = true;
  9601. texture.references = 1;
  9602. texture.generateMipMaps = generateMipMaps;
  9603. texture.references = 1;
  9604. texture.samples = 1;
  9605. texture.samplingMode = samplingMode;
  9606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9607. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9608. for (var face = 0; face < 6; face++) {
  9609. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9610. }
  9611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9612. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9613. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9614. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9615. // Create the framebuffer
  9616. var framebuffer = gl.createFramebuffer();
  9617. this.bindUnboundFramebuffer(framebuffer);
  9618. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9619. // Mipmaps
  9620. if (texture.generateMipMaps) {
  9621. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9622. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9623. }
  9624. // Unbind
  9625. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9626. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9627. this.bindUnboundFramebuffer(null);
  9628. texture._framebuffer = framebuffer;
  9629. texture._width = size;
  9630. texture._height = size;
  9631. texture.isReady = true;
  9632. this.resetTextureCache();
  9633. this._loadedTexturesCache.push(texture);
  9634. return texture;
  9635. };
  9636. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9637. var _this = this;
  9638. if (onLoad === void 0) { onLoad = null; }
  9639. if (onError === void 0) { onError = null; }
  9640. var gl = this._gl;
  9641. var texture = gl.createTexture();
  9642. texture.isCube = true;
  9643. texture.url = rootUrl;
  9644. texture.references = 1;
  9645. texture.onLoadedCallbacks = [];
  9646. var isKTX = false;
  9647. var lastDot = rootUrl.lastIndexOf('.');
  9648. var extension = rootUrl.substring(lastDot).toLowerCase();
  9649. if (this._textureFormatInUse) {
  9650. extension = this._textureFormatInUse;
  9651. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9652. isKTX = true;
  9653. }
  9654. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9655. if (isDDS) {
  9656. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9657. }
  9658. if (isKTX) {
  9659. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9660. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9661. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9662. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9663. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9664. ktx.uploadLevels(_this._gl, !noMipmap);
  9665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9666. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9669. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9670. _this.resetTextureCache();
  9671. texture._width = ktx.pixelWidth;
  9672. texture._height = ktx.pixelHeight;
  9673. texture.isReady = true;
  9674. }, null, null, true, onError);
  9675. }
  9676. else if (isDDS) {
  9677. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9678. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9679. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9680. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9681. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9682. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9683. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9684. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9685. }
  9686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9690. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9691. _this.resetTextureCache();
  9692. texture._width = info.width;
  9693. texture._height = info.height;
  9694. texture.isReady = true;
  9695. }, null, null, true, onError);
  9696. }
  9697. else {
  9698. cascadeLoad(rootUrl, scene, function (imgs) {
  9699. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9700. var height = width;
  9701. _this._prepareWorkingCanvas();
  9702. _this._workingCanvas.width = width;
  9703. _this._workingCanvas.height = height;
  9704. var faces = [
  9705. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9706. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9707. ];
  9708. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9709. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9710. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9711. for (var index = 0; index < faces.length; index++) {
  9712. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9713. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9714. }
  9715. if (!noMipmap) {
  9716. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9717. }
  9718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9721. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9723. _this.resetTextureCache();
  9724. texture._width = width;
  9725. texture._height = height;
  9726. texture.isReady = true;
  9727. texture.onLoadedCallbacks.forEach(function (callback) {
  9728. callback();
  9729. });
  9730. if (onLoad) {
  9731. onLoad();
  9732. }
  9733. }, files, onError);
  9734. }
  9735. this._loadedTexturesCache.push(texture);
  9736. return texture;
  9737. };
  9738. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9739. texture._width = width;
  9740. texture._height = height;
  9741. texture._size = width * height;
  9742. texture._baseWidth = width;
  9743. texture._baseHeight = height;
  9744. };
  9745. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9746. if (compression === void 0) { compression = null; }
  9747. if (level === void 0) { level = 0; }
  9748. var gl = this._gl;
  9749. var textureType = this._getWebGLTextureType(type);
  9750. var internalFormat = this._getInternalFormat(format);
  9751. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9752. var needConversion = false;
  9753. if (internalFormat === gl.RGB) {
  9754. internalFormat = gl.RGBA;
  9755. needConversion = true;
  9756. }
  9757. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9758. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9759. if (texture._width % 4 !== 0) {
  9760. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9761. }
  9762. var facesIndex = [
  9763. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9764. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9765. ];
  9766. // Data are known to be in +X +Y +Z -X -Y -Z
  9767. for (var index = 0; index < facesIndex.length; index++) {
  9768. var faceData = data[index];
  9769. if (compression) {
  9770. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9771. }
  9772. else {
  9773. if (needConversion) {
  9774. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9775. }
  9776. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9777. }
  9778. }
  9779. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9780. if (isPot && texture.generateMipMaps && level === 0) {
  9781. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9782. }
  9783. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9784. this.resetTextureCache();
  9785. texture.isReady = true;
  9786. };
  9787. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9788. if (compression === void 0) { compression = null; }
  9789. var gl = this._gl;
  9790. var texture = gl.createTexture();
  9791. texture.isCube = true;
  9792. texture.references = 1;
  9793. var textureType = this._getWebGLTextureType(type);
  9794. var internalFormat = this._getInternalFormat(format);
  9795. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9796. var needConversion = false;
  9797. if (internalFormat === gl.RGB) {
  9798. internalFormat = gl.RGBA;
  9799. needConversion = true;
  9800. }
  9801. var width = size;
  9802. var height = width;
  9803. texture._width = width;
  9804. texture._height = height;
  9805. // Double check on POT to generate Mips.
  9806. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9807. if (!isPot) {
  9808. generateMipMaps = false;
  9809. }
  9810. texture.generateMipMaps = generateMipMaps;
  9811. // Upload data if needed. The texture won t be ready until then.
  9812. if (data) {
  9813. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9814. }
  9815. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9816. // Filters
  9817. if (data && generateMipMaps) {
  9818. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9819. }
  9820. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9823. }
  9824. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9825. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9826. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9827. }
  9828. else {
  9829. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9832. }
  9833. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9834. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9835. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9836. this._loadedTexturesCache.push(texture);
  9837. return texture;
  9838. };
  9839. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9840. var _this = this;
  9841. if (onLoad === void 0) { onLoad = null; }
  9842. if (onError === void 0) { onError = null; }
  9843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9844. if (invertY === void 0) { invertY = false; }
  9845. var gl = this._gl;
  9846. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9847. scene._addPendingData(texture);
  9848. texture.url = url;
  9849. var onerror = function () {
  9850. scene._removePendingData(texture);
  9851. if (onError) {
  9852. onError();
  9853. }
  9854. };
  9855. var internalCallback = function (data) {
  9856. var rgbeDataArrays = callback(data);
  9857. var facesIndex = [
  9858. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9859. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9860. ];
  9861. var width = texture._width;
  9862. var height = texture._height;
  9863. if (mipmmapGenerator) {
  9864. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9865. // I ll remove ASAP.
  9866. var textureType = _this._getWebGLTextureType(type);
  9867. var internalFormat = _this._getInternalFormat(format);
  9868. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9869. var needConversion = false;
  9870. if (internalFormat === gl.RGB) {
  9871. internalFormat = gl.RGBA;
  9872. needConversion = true;
  9873. }
  9874. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9875. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9876. var arrayTemp = [];
  9877. // Data are known to be in +X +Y +Z -X -Y -Z
  9878. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9879. arrayTemp.push(rgbeDataArrays[0]); // +X
  9880. arrayTemp.push(rgbeDataArrays[3]); // -X
  9881. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9882. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9883. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9884. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9885. var mipData = mipmmapGenerator(arrayTemp);
  9886. // mipData is order in +X -X +Y -Y +Z -Z
  9887. var mipFaces = [0, 2, 4, 1, 3, 5];
  9888. for (var level = 0; level < mipData.length; level++) {
  9889. var mipSize = width >> level;
  9890. for (var mipIndex in mipFaces) {
  9891. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9892. if (needConversion) {
  9893. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9894. }
  9895. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9896. }
  9897. }
  9898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9899. }
  9900. else {
  9901. texture.generateMipMaps = !noMipmap;
  9902. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9903. }
  9904. texture.isReady = true;
  9905. _this.resetTextureCache();
  9906. scene._removePendingData(texture);
  9907. if (onLoad) {
  9908. onLoad();
  9909. }
  9910. };
  9911. BABYLON.Tools.LoadFile(url, function (data) {
  9912. internalCallback(data);
  9913. }, onerror, scene.database, true);
  9914. return texture;
  9915. };
  9916. ;
  9917. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9918. // Create new RGBA data container.
  9919. var rgbaData;
  9920. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9921. rgbaData = new Float32Array(width * height * 4);
  9922. }
  9923. else {
  9924. rgbaData = new Uint32Array(width * height * 4);
  9925. }
  9926. // Convert each pixel.
  9927. for (var x = 0; x < width; x++) {
  9928. for (var y = 0; y < height; y++) {
  9929. var index = (y * width + x) * 3;
  9930. var newIndex = (y * width + x) * 4;
  9931. // Map Old Value to new value.
  9932. rgbaData[newIndex + 0] = rgbData[index + 0];
  9933. rgbaData[newIndex + 1] = rgbData[index + 1];
  9934. rgbaData[newIndex + 2] = rgbData[index + 2];
  9935. // Add fully opaque alpha channel.
  9936. rgbaData[newIndex + 3] = 1;
  9937. }
  9938. }
  9939. return rgbaData;
  9940. };
  9941. Engine.prototype._releaseTexture = function (texture) {
  9942. var gl = this._gl;
  9943. if (texture._framebuffer) {
  9944. gl.deleteFramebuffer(texture._framebuffer);
  9945. }
  9946. if (texture._depthStencilBuffer) {
  9947. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9948. }
  9949. if (texture._MSAAFramebuffer) {
  9950. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9951. }
  9952. if (texture._MSAARenderBuffer) {
  9953. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9954. }
  9955. gl.deleteTexture(texture);
  9956. // Unbind channels
  9957. this.unbindAllTextures();
  9958. var index = this._loadedTexturesCache.indexOf(texture);
  9959. if (index !== -1) {
  9960. this._loadedTexturesCache.splice(index, 1);
  9961. }
  9962. };
  9963. Engine.prototype.setProgram = function (program) {
  9964. if (this._currentProgram !== program) {
  9965. this._gl.useProgram(program);
  9966. this._currentProgram = program;
  9967. }
  9968. };
  9969. Engine.prototype.bindSamplers = function (effect) {
  9970. this.setProgram(effect.getProgram());
  9971. var samplers = effect.getSamplers();
  9972. for (var index = 0; index < samplers.length; index++) {
  9973. var uniform = effect.getUniform(samplers[index]);
  9974. this._gl.uniform1i(uniform, index);
  9975. }
  9976. this._currentEffect = null;
  9977. };
  9978. Engine.prototype.activateTexture = function (texture) {
  9979. if (this._activeTexture !== texture) {
  9980. this._gl.activeTexture(texture);
  9981. this._activeTexture = texture;
  9982. }
  9983. };
  9984. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9985. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9986. this._gl.bindTexture(target, texture);
  9987. this._activeTexturesCache[this._activeTexture] = texture;
  9988. }
  9989. };
  9990. Engine.prototype._bindTexture = function (channel, texture) {
  9991. if (channel < 0) {
  9992. return;
  9993. }
  9994. this.activateTexture(this._gl.TEXTURE0 + channel);
  9995. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9996. };
  9997. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9998. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9999. };
  10000. Engine.prototype.unbindAllTextures = function () {
  10001. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10002. this.activateTexture(this._gl["TEXTURE" + channel]);
  10003. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10004. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10005. }
  10006. };
  10007. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10008. if (channel < 0) {
  10009. return;
  10010. }
  10011. this._gl.uniform1i(uniform, channel);
  10012. this._setTexture(channel, texture);
  10013. };
  10014. Engine.prototype._setTexture = function (channel, texture) {
  10015. // Not ready?
  10016. if (!texture) {
  10017. if (this._activeTexturesCache[channel] != null) {
  10018. this.activateTexture(this._gl["TEXTURE" + channel]);
  10019. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10020. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10021. }
  10022. return;
  10023. }
  10024. // Video
  10025. var alreadyActivated = false;
  10026. if (texture.video) {
  10027. this.activateTexture(this._gl["TEXTURE" + channel]);
  10028. alreadyActivated = true;
  10029. texture.update();
  10030. }
  10031. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10032. texture.delayLoad();
  10033. return;
  10034. }
  10035. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10036. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10037. if (this._activeTexturesCache[channel] === internalTexture) {
  10038. return;
  10039. }
  10040. if (!alreadyActivated) {
  10041. this.activateTexture(this._gl["TEXTURE" + channel]);
  10042. }
  10043. if (internalTexture.isCube) {
  10044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10045. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10046. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10047. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10048. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10049. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10050. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10051. }
  10052. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10053. }
  10054. else {
  10055. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10056. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10057. internalTexture._cachedWrapU = texture.wrapU;
  10058. switch (texture.wrapU) {
  10059. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10060. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10061. break;
  10062. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10063. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10064. break;
  10065. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10066. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10067. break;
  10068. }
  10069. }
  10070. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10071. internalTexture._cachedWrapV = texture.wrapV;
  10072. switch (texture.wrapV) {
  10073. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10074. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10075. break;
  10076. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10077. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10078. break;
  10079. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10080. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10081. break;
  10082. }
  10083. }
  10084. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10085. }
  10086. };
  10087. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10088. if (channel < 0) {
  10089. return;
  10090. }
  10091. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10092. this._textureUnits = new Int32Array(textures.length);
  10093. }
  10094. for (var i = 0; i < textures.length; i++) {
  10095. this._textureUnits[i] = channel + i;
  10096. }
  10097. this._gl.uniform1iv(uniform, this._textureUnits);
  10098. for (var index = 0; index < textures.length; index++) {
  10099. this._setTexture(channel + index, textures[index]);
  10100. }
  10101. };
  10102. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10103. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10104. var value = texture.anisotropicFilteringLevel;
  10105. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10106. value = 1;
  10107. }
  10108. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10109. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10110. texture._cachedAnisotropicFilteringLevel = value;
  10111. }
  10112. };
  10113. Engine.prototype.readPixels = function (x, y, width, height) {
  10114. var data = new Uint8Array(height * width * 4);
  10115. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10116. return data;
  10117. };
  10118. /**
  10119. * Add an externaly attached data from its key.
  10120. * This method call will fail and return false, if such key already exists.
  10121. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10122. * @param key the unique key that identifies the data
  10123. * @param data the data object to associate to the key for this Engine instance
  10124. * @return true if no such key were already present and the data was added successfully, false otherwise
  10125. */
  10126. Engine.prototype.addExternalData = function (key, data) {
  10127. if (!this._externalData) {
  10128. this._externalData = new BABYLON.StringDictionary();
  10129. }
  10130. return this._externalData.add(key, data);
  10131. };
  10132. /**
  10133. * Get an externaly attached data from its key
  10134. * @param key the unique key that identifies the data
  10135. * @return the associated data, if present (can be null), or undefined if not present
  10136. */
  10137. Engine.prototype.getExternalData = function (key) {
  10138. if (!this._externalData) {
  10139. this._externalData = new BABYLON.StringDictionary();
  10140. }
  10141. return this._externalData.get(key);
  10142. };
  10143. /**
  10144. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10145. * @param key the unique key that identifies the data
  10146. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10147. * @return the associated data, can be null if the factory returned null.
  10148. */
  10149. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10150. if (!this._externalData) {
  10151. this._externalData = new BABYLON.StringDictionary();
  10152. }
  10153. return this._externalData.getOrAddWithFactory(key, factory);
  10154. };
  10155. /**
  10156. * Remove an externaly attached data from the Engine instance
  10157. * @param key the unique key that identifies the data
  10158. * @return true if the data was successfully removed, false if it doesn't exist
  10159. */
  10160. Engine.prototype.removeExternalData = function (key) {
  10161. if (!this._externalData) {
  10162. this._externalData = new BABYLON.StringDictionary();
  10163. }
  10164. return this._externalData.remove(key);
  10165. };
  10166. Engine.prototype.releaseInternalTexture = function (texture) {
  10167. if (!texture) {
  10168. return;
  10169. }
  10170. texture.references--;
  10171. // Final reference ?
  10172. if (texture.references === 0) {
  10173. var texturesCache = this.getLoadedTexturesCache();
  10174. var index = texturesCache.indexOf(texture);
  10175. if (index > -1) {
  10176. texturesCache.splice(index, 1);
  10177. }
  10178. this._releaseTexture(texture);
  10179. }
  10180. };
  10181. Engine.prototype.unbindAllAttributes = function () {
  10182. if (this._mustWipeVertexAttributes) {
  10183. this._mustWipeVertexAttributes = false;
  10184. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10185. this._gl.disableVertexAttribArray(i);
  10186. this._vertexAttribArraysEnabled[i] = false;
  10187. this._currentBufferPointers[i] = null;
  10188. }
  10189. return;
  10190. }
  10191. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10192. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10193. continue;
  10194. }
  10195. this._gl.disableVertexAttribArray(i);
  10196. this._vertexAttribArraysEnabled[i] = false;
  10197. this._currentBufferPointers[i] = null;
  10198. }
  10199. };
  10200. Engine.prototype.releaseEffects = function () {
  10201. for (var name in this._compiledEffects) {
  10202. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10203. }
  10204. this._compiledEffects = {};
  10205. };
  10206. // Dispose
  10207. Engine.prototype.dispose = function () {
  10208. this.hideLoadingUI();
  10209. this.stopRenderLoop();
  10210. // Empty texture
  10211. if (this._emptyTexture) {
  10212. this._releaseTexture(this._emptyTexture);
  10213. this._emptyTexture = null;
  10214. }
  10215. if (this._emptyCubeTexture) {
  10216. this._releaseTexture(this._emptyCubeTexture);
  10217. this._emptyCubeTexture = null;
  10218. }
  10219. // Release scenes
  10220. while (this.scenes.length) {
  10221. this.scenes[0].dispose();
  10222. }
  10223. // Release audio engine
  10224. if (Engine.audioEngine) {
  10225. Engine.audioEngine.dispose();
  10226. }
  10227. // Release effects
  10228. this.releaseEffects();
  10229. // Unbind
  10230. this.unbindAllAttributes();
  10231. this._gl = null;
  10232. //WebVR
  10233. this.disableVR();
  10234. // Events
  10235. window.removeEventListener("blur", this._onBlur);
  10236. window.removeEventListener("focus", this._onFocus);
  10237. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10238. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10239. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10240. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10241. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10242. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10243. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10244. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10245. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10246. // Remove from Instances
  10247. var index = Engine.Instances.indexOf(this);
  10248. if (index >= 0) {
  10249. Engine.Instances.splice(index, 1);
  10250. }
  10251. };
  10252. // Loading screen
  10253. Engine.prototype.displayLoadingUI = function () {
  10254. var loadingScreen = this.loadingScreen;
  10255. if (loadingScreen) {
  10256. loadingScreen.displayLoadingUI();
  10257. }
  10258. };
  10259. Engine.prototype.hideLoadingUI = function () {
  10260. var loadingScreen = this.loadingScreen;
  10261. if (loadingScreen) {
  10262. loadingScreen.hideLoadingUI();
  10263. }
  10264. };
  10265. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10266. get: function () {
  10267. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10268. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10269. return this._loadingScreen;
  10270. },
  10271. set: function (loadingScreen) {
  10272. this._loadingScreen = loadingScreen;
  10273. },
  10274. enumerable: true,
  10275. configurable: true
  10276. });
  10277. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10278. set: function (text) {
  10279. this.loadingScreen.loadingUIText = text;
  10280. },
  10281. enumerable: true,
  10282. configurable: true
  10283. });
  10284. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10285. set: function (color) {
  10286. this.loadingScreen.loadingUIBackgroundColor = color;
  10287. },
  10288. enumerable: true,
  10289. configurable: true
  10290. });
  10291. Engine.prototype.attachContextLostEvent = function (callback) {
  10292. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10293. };
  10294. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10295. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10296. };
  10297. Engine.prototype.getVertexShaderSource = function (program) {
  10298. var shaders = this._gl.getAttachedShaders(program);
  10299. return this._gl.getShaderSource(shaders[0]);
  10300. };
  10301. Engine.prototype.getFragmentShaderSource = function (program) {
  10302. var shaders = this._gl.getAttachedShaders(program);
  10303. return this._gl.getShaderSource(shaders[1]);
  10304. };
  10305. // FPS
  10306. Engine.prototype.getFps = function () {
  10307. return this.fps;
  10308. };
  10309. Engine.prototype.getDeltaTime = function () {
  10310. return this.deltaTime;
  10311. };
  10312. Engine.prototype._measureFps = function () {
  10313. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10314. var length = this.previousFramesDuration.length;
  10315. if (length >= 2) {
  10316. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10317. }
  10318. if (length >= this.fpsRange) {
  10319. if (length > this.fpsRange) {
  10320. this.previousFramesDuration.splice(0, 1);
  10321. length = this.previousFramesDuration.length;
  10322. }
  10323. var sum = 0;
  10324. for (var id = 0; id < length - 1; id++) {
  10325. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10326. }
  10327. this.fps = 1000.0 / (sum / (length - 1));
  10328. }
  10329. };
  10330. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10331. if (this._webGLVersion > 1) {
  10332. return this._caps.colorBufferFloat;
  10333. }
  10334. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10335. };
  10336. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10337. if (this._webGLVersion > 1) {
  10338. return this._caps.colorBufferFloat;
  10339. }
  10340. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10341. };
  10342. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10343. Engine.prototype._canRenderToFramebuffer = function (type) {
  10344. var gl = this._gl;
  10345. //clear existing errors
  10346. while (gl.getError() !== gl.NO_ERROR) { }
  10347. var successful = true;
  10348. var texture = gl.createTexture();
  10349. gl.bindTexture(gl.TEXTURE_2D, texture);
  10350. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10353. var fb = gl.createFramebuffer();
  10354. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10355. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10356. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10357. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10358. successful = successful && (gl.getError() === gl.NO_ERROR);
  10359. //try render by clearing frame buffer's color buffer
  10360. if (successful) {
  10361. gl.clear(gl.COLOR_BUFFER_BIT);
  10362. successful = successful && (gl.getError() === gl.NO_ERROR);
  10363. }
  10364. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10365. if (successful) {
  10366. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10367. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10368. var readFormat = gl.RGBA;
  10369. var readType = gl.UNSIGNED_BYTE;
  10370. var buffer = new Uint8Array(4);
  10371. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10372. successful = successful && (gl.getError() === gl.NO_ERROR);
  10373. }
  10374. //clean up
  10375. gl.deleteTexture(texture);
  10376. gl.deleteFramebuffer(fb);
  10377. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10378. //clear accumulated errors
  10379. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10380. return successful;
  10381. };
  10382. Engine.prototype._getWebGLTextureType = function (type) {
  10383. if (type === Engine.TEXTURETYPE_FLOAT) {
  10384. return this._gl.FLOAT;
  10385. }
  10386. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10387. // Add Half Float Constant.
  10388. return Engine.HALF_FLOAT_OES;
  10389. }
  10390. return this._gl.UNSIGNED_BYTE;
  10391. };
  10392. ;
  10393. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10394. if (this._webGLVersion === 1) {
  10395. return this._gl.RGBA;
  10396. }
  10397. if (type === Engine.TEXTURETYPE_FLOAT) {
  10398. return Engine.RGBA32F;
  10399. }
  10400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10401. return Engine.RGBA16F;
  10402. }
  10403. return this._gl.RGBA;
  10404. };
  10405. ;
  10406. // Statics
  10407. Engine.isSupported = function () {
  10408. try {
  10409. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10410. if (navigator.isCocoonJS) {
  10411. return true;
  10412. }
  10413. var tempcanvas = document.createElement("canvas");
  10414. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10415. return gl != null && !!window.WebGLRenderingContext;
  10416. }
  10417. catch (e) {
  10418. return false;
  10419. }
  10420. };
  10421. return Engine;
  10422. }());
  10423. Engine.Instances = new Array();
  10424. // Const statics
  10425. Engine._ALPHA_DISABLE = 0;
  10426. Engine._ALPHA_ADD = 1;
  10427. Engine._ALPHA_COMBINE = 2;
  10428. Engine._ALPHA_SUBTRACT = 3;
  10429. Engine._ALPHA_MULTIPLY = 4;
  10430. Engine._ALPHA_MAXIMIZED = 5;
  10431. Engine._ALPHA_ONEONE = 6;
  10432. Engine._ALPHA_PREMULTIPLIED = 7;
  10433. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10434. Engine._ALPHA_INTERPOLATE = 9;
  10435. Engine._ALPHA_SCREENMODE = 10;
  10436. Engine._DELAYLOADSTATE_NONE = 0;
  10437. Engine._DELAYLOADSTATE_LOADED = 1;
  10438. Engine._DELAYLOADSTATE_LOADING = 2;
  10439. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10440. Engine._TEXTUREFORMAT_ALPHA = 0;
  10441. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10442. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10443. Engine._TEXTUREFORMAT_RGB = 4;
  10444. Engine._TEXTUREFORMAT_RGBA = 5;
  10445. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10446. Engine._TEXTURETYPE_FLOAT = 1;
  10447. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10448. // Depht or Stencil test Constants.
  10449. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10450. 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.
  10451. 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.
  10452. 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.
  10453. 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.
  10454. 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.
  10455. 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.
  10456. 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.
  10457. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10458. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10459. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10460. // Stencil Actions Constants.
  10461. Engine._KEEP = 0x1E00;
  10462. Engine._REPLACE = 0x1E01;
  10463. Engine._INCR = 0x1E02;
  10464. Engine._DECR = 0x1E03;
  10465. Engine._INVERT = 0x150A;
  10466. Engine._INCR_WRAP = 0x8507;
  10467. Engine._DECR_WRAP = 0x8508;
  10468. // Texture rescaling mode
  10469. Engine._SCALEMODE_FLOOR = 1;
  10470. Engine._SCALEMODE_NEAREST = 2;
  10471. Engine._SCALEMODE_CEILING = 3;
  10472. // Updatable statics so stick with vars here
  10473. Engine.CollisionsEpsilon = 0.001;
  10474. Engine.CodeRepository = "src/";
  10475. Engine.ShadersRepository = "src/Shaders/";
  10476. BABYLON.Engine = Engine;
  10477. })(BABYLON || (BABYLON = {}));
  10478. //# sourceMappingURL=babylon.engine.js.map
  10479. /// <reference path="Tools\babylon.decorators.ts" />
  10480. var BABYLON;
  10481. (function (BABYLON) {
  10482. /**
  10483. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10484. */
  10485. var Node = (function () {
  10486. /**
  10487. * @constructor
  10488. * @param {string} name - the name and id to be given to this node
  10489. * @param {BABYLON.Scene} the scene this node will be added to
  10490. */
  10491. function Node(name, scene) {
  10492. this.state = "";
  10493. this.metadata = null;
  10494. this.doNotSerialize = false;
  10495. this.animations = new Array();
  10496. this._ranges = {};
  10497. this._childrenFlag = -1;
  10498. this._isEnabled = true;
  10499. this._isReady = true;
  10500. this._currentRenderId = -1;
  10501. this._parentRenderId = -1;
  10502. /**
  10503. * An event triggered when the mesh is disposed.
  10504. * @type {BABYLON.Observable}
  10505. */
  10506. this.onDisposeObservable = new BABYLON.Observable();
  10507. this.name = name;
  10508. this.id = name;
  10509. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10510. this._initCache();
  10511. }
  10512. Object.defineProperty(Node.prototype, "parent", {
  10513. get: function () {
  10514. return this._parentNode;
  10515. },
  10516. set: function (parent) {
  10517. if (this._parentNode === parent) {
  10518. return;
  10519. }
  10520. if (this._parentNode) {
  10521. var index = this._parentNode._children.indexOf(this);
  10522. if (index !== -1) {
  10523. this._parentNode._children.splice(index, 1);
  10524. }
  10525. }
  10526. this._parentNode = parent;
  10527. if (this._parentNode) {
  10528. if (!this._parentNode._children) {
  10529. this._parentNode._children = new Array();
  10530. }
  10531. this._parentNode._children.push(this);
  10532. }
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. Node.prototype.getClassName = function () {
  10538. return "Node";
  10539. };
  10540. Object.defineProperty(Node.prototype, "onDispose", {
  10541. set: function (callback) {
  10542. if (this._onDisposeObserver) {
  10543. this.onDisposeObservable.remove(this._onDisposeObserver);
  10544. }
  10545. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10546. },
  10547. enumerable: true,
  10548. configurable: true
  10549. });
  10550. Node.prototype.getScene = function () {
  10551. return this._scene;
  10552. };
  10553. Node.prototype.getEngine = function () {
  10554. return this._scene.getEngine();
  10555. };
  10556. // override it in derived class
  10557. Node.prototype.getWorldMatrix = function () {
  10558. return BABYLON.Matrix.Identity();
  10559. };
  10560. // override it in derived class if you add new variables to the cache
  10561. // and call the parent class method
  10562. Node.prototype._initCache = function () {
  10563. this._cache = {};
  10564. this._cache.parent = undefined;
  10565. };
  10566. Node.prototype.updateCache = function (force) {
  10567. if (!force && this.isSynchronized())
  10568. return;
  10569. this._cache.parent = this.parent;
  10570. this._updateCache();
  10571. };
  10572. // override it in derived class if you add new variables to the cache
  10573. // and call the parent class method if !ignoreParentClass
  10574. Node.prototype._updateCache = function (ignoreParentClass) {
  10575. };
  10576. // override it in derived class if you add new variables to the cache
  10577. Node.prototype._isSynchronized = function () {
  10578. return true;
  10579. };
  10580. Node.prototype._markSyncedWithParent = function () {
  10581. this._parentRenderId = this.parent._currentRenderId;
  10582. };
  10583. Node.prototype.isSynchronizedWithParent = function () {
  10584. if (!this.parent) {
  10585. return true;
  10586. }
  10587. if (this._parentRenderId !== this.parent._currentRenderId) {
  10588. return false;
  10589. }
  10590. return this.parent.isSynchronized();
  10591. };
  10592. Node.prototype.isSynchronized = function (updateCache) {
  10593. var check = this.hasNewParent();
  10594. check = check || !this.isSynchronizedWithParent();
  10595. check = check || !this._isSynchronized();
  10596. if (updateCache)
  10597. this.updateCache(true);
  10598. return !check;
  10599. };
  10600. Node.prototype.hasNewParent = function (update) {
  10601. if (this._cache.parent === this.parent)
  10602. return false;
  10603. if (update)
  10604. this._cache.parent = this.parent;
  10605. return true;
  10606. };
  10607. /**
  10608. * Is this node ready to be used/rendered
  10609. * @return {boolean} is it ready
  10610. */
  10611. Node.prototype.isReady = function () {
  10612. return this._isReady;
  10613. };
  10614. /**
  10615. * Is this node enabled.
  10616. * If the node has a parent and is enabled, the parent will be inspected as well.
  10617. * @return {boolean} whether this node (and its parent) is enabled.
  10618. * @see setEnabled
  10619. */
  10620. Node.prototype.isEnabled = function () {
  10621. if (!this._isEnabled) {
  10622. return false;
  10623. }
  10624. if (this.parent) {
  10625. return this.parent.isEnabled();
  10626. }
  10627. return true;
  10628. };
  10629. /**
  10630. * Set the enabled state of this node.
  10631. * @param {boolean} value - the new enabled state
  10632. * @see isEnabled
  10633. */
  10634. Node.prototype.setEnabled = function (value) {
  10635. this._isEnabled = value;
  10636. };
  10637. /**
  10638. * Is this node a descendant of the given node.
  10639. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10640. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10641. * @see parent
  10642. */
  10643. Node.prototype.isDescendantOf = function (ancestor) {
  10644. if (this.parent) {
  10645. if (this.parent === ancestor) {
  10646. return true;
  10647. }
  10648. return this.parent.isDescendantOf(ancestor);
  10649. }
  10650. return false;
  10651. };
  10652. /**
  10653. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10654. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10655. * @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.
  10656. * @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.
  10657. */
  10658. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10659. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10660. if (!this._children) {
  10661. return;
  10662. }
  10663. for (var index = 0; index < this._children.length; index++) {
  10664. var item = this._children[index];
  10665. if (!predicate || predicate(item)) {
  10666. results.push(item);
  10667. }
  10668. if (!directDescendantsOnly) {
  10669. item._getDescendants(results, false, predicate);
  10670. }
  10671. }
  10672. };
  10673. /**
  10674. * Will return all nodes that have this node as ascendant.
  10675. * @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.
  10676. * @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.
  10677. * @return {BABYLON.Node[]} all children nodes of all types.
  10678. */
  10679. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10680. var results = [];
  10681. this._getDescendants(results, directDescendantsOnly, predicate);
  10682. return results;
  10683. };
  10684. /**
  10685. * Get all child-meshes of this node.
  10686. */
  10687. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10688. var results = [];
  10689. this._getDescendants(results, directDecendantsOnly, function (node) {
  10690. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10691. });
  10692. return results;
  10693. };
  10694. /**
  10695. * Get all direct children of this node.
  10696. */
  10697. Node.prototype.getChildren = function (predicate) {
  10698. return this.getDescendants(true, predicate);
  10699. };
  10700. Node.prototype._setReady = function (state) {
  10701. if (state === this._isReady) {
  10702. return;
  10703. }
  10704. if (!state) {
  10705. this._isReady = false;
  10706. return;
  10707. }
  10708. this._isReady = true;
  10709. if (this.onReady) {
  10710. this.onReady(this);
  10711. }
  10712. };
  10713. Node.prototype.getAnimationByName = function (name) {
  10714. for (var i = 0; i < this.animations.length; i++) {
  10715. var animation = this.animations[i];
  10716. if (animation.name === name) {
  10717. return animation;
  10718. }
  10719. }
  10720. return null;
  10721. };
  10722. Node.prototype.createAnimationRange = function (name, from, to) {
  10723. // check name not already in use
  10724. if (!this._ranges[name]) {
  10725. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10726. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10727. if (this.animations[i]) {
  10728. this.animations[i].createRange(name, from, to);
  10729. }
  10730. }
  10731. }
  10732. };
  10733. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10734. if (deleteFrames === void 0) { deleteFrames = true; }
  10735. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10736. if (this.animations[i]) {
  10737. this.animations[i].deleteRange(name, deleteFrames);
  10738. }
  10739. }
  10740. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10741. };
  10742. Node.prototype.getAnimationRange = function (name) {
  10743. return this._ranges[name];
  10744. };
  10745. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10746. var range = this.getAnimationRange(name);
  10747. if (!range) {
  10748. return null;
  10749. }
  10750. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10751. };
  10752. Node.prototype.serializeAnimationRanges = function () {
  10753. var serializationRanges = [];
  10754. for (var name in this._ranges) {
  10755. var range = {};
  10756. range.name = name;
  10757. range.from = this._ranges[name].from;
  10758. range.to = this._ranges[name].to;
  10759. serializationRanges.push(range);
  10760. }
  10761. return serializationRanges;
  10762. };
  10763. Node.prototype.dispose = function () {
  10764. this.parent = null;
  10765. // Callback
  10766. this.onDisposeObservable.notifyObservers(this);
  10767. this.onDisposeObservable.clear();
  10768. };
  10769. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10770. if (parsedNode.ranges) {
  10771. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10772. var data = parsedNode.ranges[index];
  10773. node.createAnimationRange(data.name, data.from, data.to);
  10774. }
  10775. }
  10776. };
  10777. return Node;
  10778. }());
  10779. __decorate([
  10780. BABYLON.serialize()
  10781. ], Node.prototype, "name", void 0);
  10782. __decorate([
  10783. BABYLON.serialize()
  10784. ], Node.prototype, "id", void 0);
  10785. __decorate([
  10786. BABYLON.serialize()
  10787. ], Node.prototype, "uniqueId", void 0);
  10788. __decorate([
  10789. BABYLON.serialize()
  10790. ], Node.prototype, "state", void 0);
  10791. __decorate([
  10792. BABYLON.serialize()
  10793. ], Node.prototype, "metadata", void 0);
  10794. BABYLON.Node = Node;
  10795. })(BABYLON || (BABYLON = {}));
  10796. //# sourceMappingURL=babylon.node.js.map
  10797. var BABYLON;
  10798. (function (BABYLON) {
  10799. var BoundingSphere = (function () {
  10800. function BoundingSphere(minimum, maximum) {
  10801. this.minimum = minimum;
  10802. this.maximum = maximum;
  10803. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10804. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10805. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10806. this.radius = distance * 0.5;
  10807. this.centerWorld = BABYLON.Vector3.Zero();
  10808. this._update(BABYLON.Matrix.Identity());
  10809. }
  10810. // Methods
  10811. BoundingSphere.prototype._update = function (world) {
  10812. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10813. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10814. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10815. };
  10816. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10817. for (var i = 0; i < 6; i++) {
  10818. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10819. return false;
  10820. }
  10821. return true;
  10822. };
  10823. BoundingSphere.prototype.intersectsPoint = function (point) {
  10824. var x = this.centerWorld.x - point.x;
  10825. var y = this.centerWorld.y - point.y;
  10826. var z = this.centerWorld.z - point.z;
  10827. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10828. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10829. return false;
  10830. return true;
  10831. };
  10832. // Statics
  10833. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10834. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10835. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10836. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10837. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10838. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10839. return false;
  10840. return true;
  10841. };
  10842. return BoundingSphere;
  10843. }());
  10844. BABYLON.BoundingSphere = BoundingSphere;
  10845. })(BABYLON || (BABYLON = {}));
  10846. //# sourceMappingURL=babylon.boundingSphere.js.map
  10847. var BABYLON;
  10848. (function (BABYLON) {
  10849. var BoundingBox = (function () {
  10850. function BoundingBox(minimum, maximum) {
  10851. this.minimum = minimum;
  10852. this.maximum = maximum;
  10853. this.vectors = new Array();
  10854. this.vectorsWorld = new Array();
  10855. // Bounding vectors
  10856. this.vectors.push(this.minimum.clone());
  10857. this.vectors.push(this.maximum.clone());
  10858. this.vectors.push(this.minimum.clone());
  10859. this.vectors[2].x = this.maximum.x;
  10860. this.vectors.push(this.minimum.clone());
  10861. this.vectors[3].y = this.maximum.y;
  10862. this.vectors.push(this.minimum.clone());
  10863. this.vectors[4].z = this.maximum.z;
  10864. this.vectors.push(this.maximum.clone());
  10865. this.vectors[5].z = this.minimum.z;
  10866. this.vectors.push(this.maximum.clone());
  10867. this.vectors[6].x = this.minimum.x;
  10868. this.vectors.push(this.maximum.clone());
  10869. this.vectors[7].y = this.minimum.y;
  10870. // OBB
  10871. this.center = this.maximum.add(this.minimum).scale(0.5);
  10872. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10873. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10874. // World
  10875. for (var index = 0; index < this.vectors.length; index++) {
  10876. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10877. }
  10878. this.minimumWorld = BABYLON.Vector3.Zero();
  10879. this.maximumWorld = BABYLON.Vector3.Zero();
  10880. this.centerWorld = BABYLON.Vector3.Zero();
  10881. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10882. this._update(BABYLON.Matrix.Identity());
  10883. }
  10884. // Methods
  10885. BoundingBox.prototype.getWorldMatrix = function () {
  10886. return this._worldMatrix;
  10887. };
  10888. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10889. this._worldMatrix.copyFrom(matrix);
  10890. return this;
  10891. };
  10892. BoundingBox.prototype._update = function (world) {
  10893. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10894. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10895. for (var index = 0; index < this.vectors.length; index++) {
  10896. var v = this.vectorsWorld[index];
  10897. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10898. if (v.x < this.minimumWorld.x)
  10899. this.minimumWorld.x = v.x;
  10900. if (v.y < this.minimumWorld.y)
  10901. this.minimumWorld.y = v.y;
  10902. if (v.z < this.minimumWorld.z)
  10903. this.minimumWorld.z = v.z;
  10904. if (v.x > this.maximumWorld.x)
  10905. this.maximumWorld.x = v.x;
  10906. if (v.y > this.maximumWorld.y)
  10907. this.maximumWorld.y = v.y;
  10908. if (v.z > this.maximumWorld.z)
  10909. this.maximumWorld.z = v.z;
  10910. }
  10911. // Extend
  10912. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10913. this.extendSizeWorld.scaleInPlace(0.5);
  10914. // OBB
  10915. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10916. this.centerWorld.scaleInPlace(0.5);
  10917. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10918. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10919. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10920. this._worldMatrix = world;
  10921. };
  10922. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10923. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10924. };
  10925. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10926. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10927. };
  10928. BoundingBox.prototype.intersectsPoint = function (point) {
  10929. var delta = -BABYLON.Epsilon;
  10930. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10931. return false;
  10932. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10933. return false;
  10934. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10935. return false;
  10936. return true;
  10937. };
  10938. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10939. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10940. };
  10941. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10942. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10943. return false;
  10944. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10945. return false;
  10946. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10947. return false;
  10948. return true;
  10949. };
  10950. // Statics
  10951. BoundingBox.Intersects = function (box0, box1) {
  10952. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10953. return false;
  10954. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10955. return false;
  10956. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10957. return false;
  10958. return true;
  10959. };
  10960. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10961. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10962. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10963. return (num <= (sphereRadius * sphereRadius));
  10964. };
  10965. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10966. for (var p = 0; p < 6; p++) {
  10967. for (var i = 0; i < 8; i++) {
  10968. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10969. return false;
  10970. }
  10971. }
  10972. }
  10973. return true;
  10974. };
  10975. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10976. for (var p = 0; p < 6; p++) {
  10977. var inCount = 8;
  10978. for (var i = 0; i < 8; i++) {
  10979. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10980. --inCount;
  10981. }
  10982. else {
  10983. break;
  10984. }
  10985. }
  10986. if (inCount === 0)
  10987. return false;
  10988. }
  10989. return true;
  10990. };
  10991. return BoundingBox;
  10992. }());
  10993. BABYLON.BoundingBox = BoundingBox;
  10994. })(BABYLON || (BABYLON = {}));
  10995. //# sourceMappingURL=babylon.boundingBox.js.map
  10996. var BABYLON;
  10997. (function (BABYLON) {
  10998. var computeBoxExtents = function (axis, box) {
  10999. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11000. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11001. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11002. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11003. var r = r0 + r1 + r2;
  11004. return {
  11005. min: p - r,
  11006. max: p + r
  11007. };
  11008. };
  11009. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11010. var axisOverlap = function (axis, box0, box1) {
  11011. var result0 = computeBoxExtents(axis, box0);
  11012. var result1 = computeBoxExtents(axis, box1);
  11013. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11014. };
  11015. var BoundingInfo = (function () {
  11016. function BoundingInfo(minimum, maximum) {
  11017. this.minimum = minimum;
  11018. this.maximum = maximum;
  11019. this._isLocked = false;
  11020. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11021. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11022. }
  11023. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11024. get: function () {
  11025. return this._isLocked;
  11026. },
  11027. set: function (value) {
  11028. this._isLocked = value;
  11029. },
  11030. enumerable: true,
  11031. configurable: true
  11032. });
  11033. // Methods
  11034. BoundingInfo.prototype.update = function (world) {
  11035. if (this._isLocked) {
  11036. return;
  11037. }
  11038. this.boundingBox._update(world);
  11039. this.boundingSphere._update(world);
  11040. };
  11041. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11042. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11043. return false;
  11044. return this.boundingBox.isInFrustum(frustumPlanes);
  11045. };
  11046. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11047. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11048. };
  11049. BoundingInfo.prototype._checkCollision = function (collider) {
  11050. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11051. };
  11052. BoundingInfo.prototype.intersectsPoint = function (point) {
  11053. if (!this.boundingSphere.centerWorld) {
  11054. return false;
  11055. }
  11056. if (!this.boundingSphere.intersectsPoint(point)) {
  11057. return false;
  11058. }
  11059. if (!this.boundingBox.intersectsPoint(point)) {
  11060. return false;
  11061. }
  11062. return true;
  11063. };
  11064. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11065. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11066. return false;
  11067. }
  11068. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11069. return false;
  11070. }
  11071. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11072. return false;
  11073. }
  11074. if (!precise) {
  11075. return true;
  11076. }
  11077. var box0 = this.boundingBox;
  11078. var box1 = boundingInfo.boundingBox;
  11079. if (!axisOverlap(box0.directions[0], box0, box1))
  11080. return false;
  11081. if (!axisOverlap(box0.directions[1], box0, box1))
  11082. return false;
  11083. if (!axisOverlap(box0.directions[2], box0, box1))
  11084. return false;
  11085. if (!axisOverlap(box1.directions[0], box0, box1))
  11086. return false;
  11087. if (!axisOverlap(box1.directions[1], box0, box1))
  11088. return false;
  11089. if (!axisOverlap(box1.directions[2], box0, box1))
  11090. return false;
  11091. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11092. return false;
  11093. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11094. return false;
  11095. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11096. return false;
  11097. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11098. return false;
  11099. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11100. return false;
  11101. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11102. return false;
  11103. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11104. return false;
  11105. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11106. return false;
  11107. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11108. return false;
  11109. return true;
  11110. };
  11111. return BoundingInfo;
  11112. }());
  11113. BABYLON.BoundingInfo = BoundingInfo;
  11114. })(BABYLON || (BABYLON = {}));
  11115. //# sourceMappingURL=babylon.boundingInfo.js.map
  11116. var BABYLON;
  11117. (function (BABYLON) {
  11118. var AbstractMesh = (function (_super) {
  11119. __extends(AbstractMesh, _super);
  11120. // Constructor
  11121. function AbstractMesh(name, scene) {
  11122. var _this = _super.call(this, name, scene) || this;
  11123. _this._facetNb = 0; // facet number
  11124. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11125. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11126. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11127. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11128. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11129. _this._subDiv = {
  11130. max: 1,
  11131. X: 1,
  11132. Y: 1,
  11133. Z: 1
  11134. };
  11135. // Events
  11136. /**
  11137. * An event triggered when this mesh collides with another one
  11138. * @type {BABYLON.Observable}
  11139. */
  11140. _this.onCollideObservable = new BABYLON.Observable();
  11141. /**
  11142. * An event triggered when the collision's position changes
  11143. * @type {BABYLON.Observable}
  11144. */
  11145. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11146. /**
  11147. * An event triggered after the world matrix is updated
  11148. * @type {BABYLON.Observable}
  11149. */
  11150. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11151. // Properties
  11152. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11153. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11154. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11155. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11156. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11157. _this.visibility = 1.0;
  11158. _this.alphaIndex = Number.MAX_VALUE;
  11159. _this.infiniteDistance = false;
  11160. _this.isVisible = true;
  11161. _this.isPickable = true;
  11162. _this.showBoundingBox = false;
  11163. _this.showSubMeshesBoundingBox = false;
  11164. _this.isBlocker = false;
  11165. _this.renderingGroupId = 0;
  11166. _this._receiveShadows = false;
  11167. _this.renderOutline = false;
  11168. _this.outlineColor = BABYLON.Color3.Red();
  11169. _this.outlineWidth = 0.02;
  11170. _this.renderOverlay = false;
  11171. _this.overlayColor = BABYLON.Color3.Red();
  11172. _this.overlayAlpha = 0.5;
  11173. _this._hasVertexAlpha = false;
  11174. _this._useVertexColors = true;
  11175. _this._computeBonesUsingShaders = true;
  11176. _this._numBoneInfluencers = 4;
  11177. _this._applyFog = true;
  11178. _this.scalingDeterminant = 1;
  11179. _this.useOctreeForRenderingSelection = true;
  11180. _this.useOctreeForPicking = true;
  11181. _this.useOctreeForCollisions = true;
  11182. _this.layerMask = 0x0FFFFFFF;
  11183. /**
  11184. * True if the mesh must be rendered in any case.
  11185. */
  11186. _this.alwaysSelectAsActiveMesh = false;
  11187. // Collisions
  11188. _this._checkCollisions = false;
  11189. _this._collisionMask = -1;
  11190. _this._collisionGroup = -1;
  11191. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11192. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11193. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11194. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11195. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11196. // Edges
  11197. _this.edgesWidth = 1;
  11198. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11199. // Cache
  11200. _this._localWorld = BABYLON.Matrix.Zero();
  11201. _this._worldMatrix = BABYLON.Matrix.Zero();
  11202. _this._absolutePosition = BABYLON.Vector3.Zero();
  11203. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11204. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11205. _this._isDirty = false;
  11206. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11207. _this._isDisposed = false;
  11208. _this._renderId = 0;
  11209. _this._intersectionsInProgress = new Array();
  11210. _this._isWorldMatrixFrozen = false;
  11211. _this._unIndexed = false;
  11212. _this._lightSources = new Array();
  11213. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11214. if (collidedMesh === void 0) { collidedMesh = null; }
  11215. //TODO move this to the collision coordinator!
  11216. if (_this.getScene().workerCollisions)
  11217. newPosition.multiplyInPlace(_this._collider.radius);
  11218. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11219. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11220. _this.position.addInPlace(_this._diffPositionForCollisions);
  11221. }
  11222. if (collidedMesh) {
  11223. _this.onCollideObservable.notifyObservers(collidedMesh);
  11224. }
  11225. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11226. };
  11227. _this.getScene().addMesh(_this);
  11228. _this._resyncLightSources();
  11229. return _this;
  11230. }
  11231. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11232. get: function () {
  11233. return AbstractMesh._BILLBOARDMODE_NONE;
  11234. },
  11235. enumerable: true,
  11236. configurable: true
  11237. });
  11238. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11239. get: function () {
  11240. return AbstractMesh._BILLBOARDMODE_X;
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11246. get: function () {
  11247. return AbstractMesh._BILLBOARDMODE_Y;
  11248. },
  11249. enumerable: true,
  11250. configurable: true
  11251. });
  11252. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11253. get: function () {
  11254. return AbstractMesh._BILLBOARDMODE_Z;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11260. get: function () {
  11261. return AbstractMesh._BILLBOARDMODE_ALL;
  11262. },
  11263. enumerable: true,
  11264. configurable: true
  11265. });
  11266. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11267. /**
  11268. * Read-only : the number of facets in the mesh
  11269. */
  11270. get: function () {
  11271. return this._facetNb;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11277. /**
  11278. * The number (integer) of subdivisions per axis in the partioning space
  11279. */
  11280. get: function () {
  11281. return this._partitioningSubdivisions;
  11282. },
  11283. set: function (nb) {
  11284. this._partitioningSubdivisions = nb;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11290. /**
  11291. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11292. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11293. */
  11294. get: function () {
  11295. return this._partitioningBBoxRatio;
  11296. },
  11297. set: function (ratio) {
  11298. this._partitioningBBoxRatio = ratio;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11304. /**
  11305. * Read-only boolean : is the feature facetData enabled ?
  11306. */
  11307. get: function () {
  11308. return this._facetDataEnabled;
  11309. },
  11310. enumerable: true,
  11311. configurable: true
  11312. });
  11313. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11314. set: function (callback) {
  11315. if (this._onCollideObserver) {
  11316. this.onCollideObservable.remove(this._onCollideObserver);
  11317. }
  11318. this._onCollideObserver = this.onCollideObservable.add(callback);
  11319. },
  11320. enumerable: true,
  11321. configurable: true
  11322. });
  11323. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11324. set: function (callback) {
  11325. if (this._onCollisionPositionChangeObserver) {
  11326. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11327. }
  11328. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11329. },
  11330. enumerable: true,
  11331. configurable: true
  11332. });
  11333. Object.defineProperty(AbstractMesh.prototype, "material", {
  11334. get: function () {
  11335. return this._material;
  11336. },
  11337. set: function (value) {
  11338. if (this._material === value) {
  11339. return;
  11340. }
  11341. this._material = value;
  11342. if (!this.subMeshes) {
  11343. return;
  11344. }
  11345. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11346. var subMesh = _a[_i];
  11347. subMesh.setEffect(null);
  11348. }
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11354. get: function () {
  11355. return this._receiveShadows;
  11356. },
  11357. set: function (value) {
  11358. if (this._receiveShadows === value) {
  11359. return;
  11360. }
  11361. this._receiveShadows = value;
  11362. this._markSubMeshesAsLightDirty();
  11363. },
  11364. enumerable: true,
  11365. configurable: true
  11366. });
  11367. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11368. get: function () {
  11369. return this._hasVertexAlpha;
  11370. },
  11371. set: function (value) {
  11372. if (this._hasVertexAlpha === value) {
  11373. return;
  11374. }
  11375. this._hasVertexAlpha = value;
  11376. this._markSubMeshesAsAttributesDirty();
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11382. get: function () {
  11383. return this._useVertexColors;
  11384. },
  11385. set: function (value) {
  11386. if (this._useVertexColors === value) {
  11387. return;
  11388. }
  11389. this._useVertexColors = value;
  11390. this._markSubMeshesAsAttributesDirty();
  11391. },
  11392. enumerable: true,
  11393. configurable: true
  11394. });
  11395. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11396. get: function () {
  11397. return this._computeBonesUsingShaders;
  11398. },
  11399. set: function (value) {
  11400. if (this._computeBonesUsingShaders === value) {
  11401. return;
  11402. }
  11403. this._computeBonesUsingShaders = value;
  11404. this._markSubMeshesAsAttributesDirty();
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11410. get: function () {
  11411. return this._numBoneInfluencers;
  11412. },
  11413. set: function (value) {
  11414. if (this._numBoneInfluencers === value) {
  11415. return;
  11416. }
  11417. this._numBoneInfluencers = value;
  11418. this._markSubMeshesAsAttributesDirty();
  11419. },
  11420. enumerable: true,
  11421. configurable: true
  11422. });
  11423. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11424. get: function () {
  11425. return this._applyFog;
  11426. },
  11427. set: function (value) {
  11428. if (this._applyFog === value) {
  11429. return;
  11430. }
  11431. this._applyFog = value;
  11432. this._markSubMeshesAsMiscDirty();
  11433. },
  11434. enumerable: true,
  11435. configurable: true
  11436. });
  11437. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11438. get: function () {
  11439. return this._collisionMask;
  11440. },
  11441. set: function (mask) {
  11442. this._collisionMask = !isNaN(mask) ? mask : -1;
  11443. },
  11444. enumerable: true,
  11445. configurable: true
  11446. });
  11447. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11448. get: function () {
  11449. return this._collisionGroup;
  11450. },
  11451. set: function (mask) {
  11452. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11458. get: function () {
  11459. return null;
  11460. },
  11461. enumerable: true,
  11462. configurable: true
  11463. });
  11464. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11465. get: function () {
  11466. return this._skeleton;
  11467. },
  11468. set: function (value) {
  11469. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11470. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11471. }
  11472. if (value && value.needInitialSkinMatrix) {
  11473. value._registerMeshWithPoseMatrix(this);
  11474. }
  11475. this._skeleton = value;
  11476. if (!this._skeleton) {
  11477. this._bonesTransformMatrices = null;
  11478. }
  11479. this._markSubMeshesAsAttributesDirty();
  11480. },
  11481. enumerable: true,
  11482. configurable: true
  11483. });
  11484. /**
  11485. * Returns the string "AbstractMesh"
  11486. */
  11487. AbstractMesh.prototype.getClassName = function () {
  11488. return "AbstractMesh";
  11489. };
  11490. /**
  11491. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11492. */
  11493. AbstractMesh.prototype.toString = function (fullDetails) {
  11494. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11495. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11496. if (this._skeleton) {
  11497. ret += ", skeleton: " + this._skeleton.name;
  11498. }
  11499. if (fullDetails) {
  11500. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11501. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11502. }
  11503. return ret;
  11504. };
  11505. AbstractMesh.prototype._resyncLightSources = function () {
  11506. this._lightSources.length = 0;
  11507. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11508. var light = _a[_i];
  11509. if (!light.isEnabled()) {
  11510. continue;
  11511. }
  11512. if (light.canAffectMesh(this)) {
  11513. this._lightSources.push(light);
  11514. }
  11515. }
  11516. this._markSubMeshesAsLightDirty();
  11517. };
  11518. AbstractMesh.prototype._resyncLighSource = function (light) {
  11519. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11520. var index = this._lightSources.indexOf(light);
  11521. if (index === -1) {
  11522. if (!isIn) {
  11523. return;
  11524. }
  11525. this._lightSources.push(light);
  11526. }
  11527. else {
  11528. if (isIn) {
  11529. return;
  11530. }
  11531. this._lightSources.splice(index, 1);
  11532. }
  11533. this._markSubMeshesAsLightDirty();
  11534. };
  11535. AbstractMesh.prototype._removeLightSource = function (light) {
  11536. var index = this._lightSources.indexOf(light);
  11537. if (index === -1) {
  11538. return;
  11539. }
  11540. this._lightSources.splice(index, 1);
  11541. };
  11542. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11543. if (!this.subMeshes) {
  11544. return;
  11545. }
  11546. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11547. var subMesh = _a[_i];
  11548. if (subMesh._materialDefines) {
  11549. func(subMesh._materialDefines);
  11550. }
  11551. }
  11552. };
  11553. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11554. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11555. };
  11556. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11557. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11558. };
  11559. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11560. if (!this.subMeshes) {
  11561. return;
  11562. }
  11563. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11564. var subMesh = _a[_i];
  11565. var material = subMesh.getMaterial();
  11566. if (material) {
  11567. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11568. }
  11569. }
  11570. };
  11571. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11572. /**
  11573. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11574. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11575. * Default : (0.0, 0.0, 0.0)
  11576. */
  11577. get: function () {
  11578. return this._rotation;
  11579. },
  11580. set: function (newRotation) {
  11581. this._rotation = newRotation;
  11582. },
  11583. enumerable: true,
  11584. configurable: true
  11585. });
  11586. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11587. /**
  11588. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11589. * Default : (1.0, 1.0, 1.0)
  11590. */
  11591. get: function () {
  11592. return this._scaling;
  11593. },
  11594. set: function (newScaling) {
  11595. this._scaling = newScaling;
  11596. if (this.physicsImpostor) {
  11597. this.physicsImpostor.forceUpdate();
  11598. }
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11604. /**
  11605. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11606. * It's null by default.
  11607. * 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)
  11608. */
  11609. get: function () {
  11610. return this._rotationQuaternion;
  11611. },
  11612. set: function (quaternion) {
  11613. this._rotationQuaternion = quaternion;
  11614. //reset the rotation vector.
  11615. if (quaternion && this.rotation.length()) {
  11616. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11617. }
  11618. },
  11619. enumerable: true,
  11620. configurable: true
  11621. });
  11622. // Methods
  11623. /**
  11624. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11625. * Returns the AbstractMesh.
  11626. */
  11627. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11628. this._poseMatrix.copyFrom(matrix);
  11629. return this;
  11630. };
  11631. /**
  11632. * Returns the mesh Pose matrix.
  11633. * Returned object : Matrix
  11634. */
  11635. AbstractMesh.prototype.getPoseMatrix = function () {
  11636. return this._poseMatrix;
  11637. };
  11638. /**
  11639. * Disables the mesh edger rendering mode.
  11640. * Returns the AbstractMesh.
  11641. */
  11642. AbstractMesh.prototype.disableEdgesRendering = function () {
  11643. if (this._edgesRenderer !== undefined) {
  11644. this._edgesRenderer.dispose();
  11645. this._edgesRenderer = undefined;
  11646. }
  11647. return this;
  11648. };
  11649. /**
  11650. * Enables the edge rendering mode on the mesh.
  11651. * This mode makes the mesh edges visible.
  11652. * Returns the AbstractMesh.
  11653. */
  11654. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11655. if (epsilon === void 0) { epsilon = 0.95; }
  11656. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11657. this.disableEdgesRendering();
  11658. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11659. return this;
  11660. };
  11661. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11662. /**
  11663. * Returns true if the mesh is blocked. Used by the class Mesh.
  11664. * Returns the boolean `false` by default.
  11665. */
  11666. get: function () {
  11667. return false;
  11668. },
  11669. enumerable: true,
  11670. configurable: true
  11671. });
  11672. /**
  11673. * Returns the mesh itself by default, used by the class Mesh.
  11674. * Returned type : AbstractMesh
  11675. */
  11676. AbstractMesh.prototype.getLOD = function (camera) {
  11677. return this;
  11678. };
  11679. /**
  11680. * Returns 0 by default, used by the class Mesh.
  11681. * Returns an integer.
  11682. */
  11683. AbstractMesh.prototype.getTotalVertices = function () {
  11684. return 0;
  11685. };
  11686. /**
  11687. * Returns null by default, used by the class Mesh.
  11688. * Returned type : integer array
  11689. */
  11690. AbstractMesh.prototype.getIndices = function () {
  11691. return null;
  11692. };
  11693. /**
  11694. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11695. * Returned type : float array or Float32Array
  11696. */
  11697. AbstractMesh.prototype.getVerticesData = function (kind) {
  11698. return null;
  11699. };
  11700. /**
  11701. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11702. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11703. * The `data` are either a numeric array either a Float32Array.
  11704. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11705. * 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).
  11706. * Note that a new underlying VertexBuffer object is created each call.
  11707. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11708. *
  11709. * Possible `kind` values :
  11710. * - BABYLON.VertexBuffer.PositionKind
  11711. * - BABYLON.VertexBuffer.UVKind
  11712. * - BABYLON.VertexBuffer.UV2Kind
  11713. * - BABYLON.VertexBuffer.UV3Kind
  11714. * - BABYLON.VertexBuffer.UV4Kind
  11715. * - BABYLON.VertexBuffer.UV5Kind
  11716. * - BABYLON.VertexBuffer.UV6Kind
  11717. * - BABYLON.VertexBuffer.ColorKind
  11718. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11719. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11720. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11721. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11722. *
  11723. * Returns the Mesh.
  11724. */
  11725. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11726. return null;
  11727. };
  11728. /**
  11729. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11730. * If the mesh has no geometry, it is simply returned as it is.
  11731. * The `data` are either a numeric array either a Float32Array.
  11732. * No new underlying VertexBuffer object is created.
  11733. * 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.
  11734. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11735. *
  11736. * Possible `kind` values :
  11737. * - BABYLON.VertexBuffer.PositionKind
  11738. * - BABYLON.VertexBuffer.UVKind
  11739. * - BABYLON.VertexBuffer.UV2Kind
  11740. * - BABYLON.VertexBuffer.UV3Kind
  11741. * - BABYLON.VertexBuffer.UV4Kind
  11742. * - BABYLON.VertexBuffer.UV5Kind
  11743. * - BABYLON.VertexBuffer.UV6Kind
  11744. * - BABYLON.VertexBuffer.ColorKind
  11745. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11746. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11747. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11748. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11749. *
  11750. * Returns the Mesh.
  11751. */
  11752. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11753. return null;
  11754. };
  11755. /**
  11756. * Sets the mesh indices.
  11757. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11758. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11759. * This method creates a new index buffer each call.
  11760. * Returns the Mesh.
  11761. */
  11762. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11763. return null;
  11764. };
  11765. /** Returns false by default, used by the class Mesh.
  11766. * Returns a boolean
  11767. */
  11768. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11769. return false;
  11770. };
  11771. /**
  11772. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11773. * Returns a BoundingInfo
  11774. */
  11775. AbstractMesh.prototype.getBoundingInfo = function () {
  11776. if (this._masterMesh) {
  11777. return this._masterMesh.getBoundingInfo();
  11778. }
  11779. if (!this._boundingInfo) {
  11780. this._updateBoundingInfo();
  11781. }
  11782. return this._boundingInfo;
  11783. };
  11784. /**
  11785. * Sets a mesh new object BoundingInfo.
  11786. * Returns the AbstractMesh.
  11787. */
  11788. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11789. this._boundingInfo = boundingInfo;
  11790. return this;
  11791. };
  11792. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11793. get: function () {
  11794. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. AbstractMesh.prototype._preActivate = function () {
  11800. };
  11801. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11802. };
  11803. AbstractMesh.prototype._activate = function (renderId) {
  11804. this._renderId = renderId;
  11805. };
  11806. /**
  11807. * Returns the last update of the World matrix
  11808. * Returns a Matrix.
  11809. */
  11810. AbstractMesh.prototype.getWorldMatrix = function () {
  11811. if (this._masterMesh) {
  11812. return this._masterMesh.getWorldMatrix();
  11813. }
  11814. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11815. this.computeWorldMatrix();
  11816. }
  11817. return this._worldMatrix;
  11818. };
  11819. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11820. /**
  11821. * Returns directly the last state of the mesh World matrix.
  11822. * A Matrix is returned.
  11823. */
  11824. get: function () {
  11825. return this._worldMatrix;
  11826. },
  11827. enumerable: true,
  11828. configurable: true
  11829. });
  11830. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11831. /**
  11832. * Returns the current mesh absolute position.
  11833. * Retuns a Vector3.
  11834. */
  11835. get: function () {
  11836. return this._absolutePosition;
  11837. },
  11838. enumerable: true,
  11839. configurable: true
  11840. });
  11841. /**
  11842. * Prevents the World matrix to be computed any longer.
  11843. * Returns the AbstractMesh.
  11844. */
  11845. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11846. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11847. this.computeWorldMatrix(true);
  11848. this._isWorldMatrixFrozen = true;
  11849. return this;
  11850. };
  11851. /**
  11852. * Allows back the World matrix computation.
  11853. * Returns the AbstractMesh.
  11854. */
  11855. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11856. this._isWorldMatrixFrozen = false;
  11857. this.computeWorldMatrix(true);
  11858. return this;
  11859. };
  11860. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11861. /**
  11862. * True if the World matrix has been frozen.
  11863. * Returns a boolean.
  11864. */
  11865. get: function () {
  11866. return this._isWorldMatrixFrozen;
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. /**
  11872. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11873. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11874. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11875. * The passed axis is also normalized.
  11876. * Returns the AbstractMesh.
  11877. */
  11878. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11879. axis.normalize();
  11880. if (!this.rotationQuaternion) {
  11881. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11882. this.rotation = BABYLON.Vector3.Zero();
  11883. }
  11884. var rotationQuaternion;
  11885. if (!space || space === BABYLON.Space.LOCAL) {
  11886. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11887. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11888. }
  11889. else {
  11890. if (this.parent) {
  11891. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11892. invertParentWorldMatrix.invert();
  11893. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11894. }
  11895. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11896. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11897. }
  11898. return this;
  11899. };
  11900. /**
  11901. * Translates the mesh along the axis vector for the passed distance in the given space.
  11902. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11903. * Returns the AbstractMesh.
  11904. */
  11905. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11906. var displacementVector = axis.scale(distance);
  11907. if (!space || space === BABYLON.Space.LOCAL) {
  11908. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11909. this.setPositionWithLocalVector(tempV3);
  11910. }
  11911. else {
  11912. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11913. }
  11914. return this;
  11915. };
  11916. /**
  11917. * Adds a rotation step to the mesh current rotation.
  11918. * x, y, z are Euler angles expressed in radians.
  11919. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11920. * This means this rotation is made in the mesh local space only.
  11921. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11922. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11923. * ```javascript
  11924. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11925. * ```
  11926. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11927. * 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.
  11928. * Returns the AbstractMesh.
  11929. */
  11930. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11931. var rotationQuaternion;
  11932. if (this.rotationQuaternion) {
  11933. rotationQuaternion = this.rotationQuaternion;
  11934. }
  11935. else {
  11936. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11937. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11938. }
  11939. var accumulation = BABYLON.Tmp.Quaternion[0];
  11940. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11941. rotationQuaternion.multiplyInPlace(accumulation);
  11942. if (!this.rotationQuaternion) {
  11943. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11944. }
  11945. return this;
  11946. };
  11947. /**
  11948. * Retuns the mesh absolute position in the World.
  11949. * Returns a Vector3.
  11950. */
  11951. AbstractMesh.prototype.getAbsolutePosition = function () {
  11952. this.computeWorldMatrix();
  11953. return this._absolutePosition;
  11954. };
  11955. /**
  11956. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11957. * Returns the AbstractMesh.
  11958. */
  11959. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11960. if (!absolutePosition) {
  11961. return;
  11962. }
  11963. var absolutePositionX;
  11964. var absolutePositionY;
  11965. var absolutePositionZ;
  11966. if (absolutePosition.x === undefined) {
  11967. if (arguments.length < 3) {
  11968. return;
  11969. }
  11970. absolutePositionX = arguments[0];
  11971. absolutePositionY = arguments[1];
  11972. absolutePositionZ = arguments[2];
  11973. }
  11974. else {
  11975. absolutePositionX = absolutePosition.x;
  11976. absolutePositionY = absolutePosition.y;
  11977. absolutePositionZ = absolutePosition.z;
  11978. }
  11979. if (this.parent) {
  11980. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11981. invertParentWorldMatrix.invert();
  11982. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11983. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11984. }
  11985. else {
  11986. this.position.x = absolutePositionX;
  11987. this.position.y = absolutePositionY;
  11988. this.position.z = absolutePositionZ;
  11989. }
  11990. return this;
  11991. };
  11992. // ================================== Point of View Movement =================================
  11993. /**
  11994. * Perform relative position change from the point of view of behind the front of the mesh.
  11995. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11996. * Supports definition of mesh facing forward or backward.
  11997. * @param {number} amountRight
  11998. * @param {number} amountUp
  11999. * @param {number} amountForward
  12000. *
  12001. * Returns the AbstractMesh.
  12002. */
  12003. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12004. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12005. return this;
  12006. };
  12007. /**
  12008. * Calculate relative position change from the point of view of behind the front of the mesh.
  12009. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12010. * Supports definition of mesh facing forward or backward.
  12011. * @param {number} amountRight
  12012. * @param {number} amountUp
  12013. * @param {number} amountForward
  12014. *
  12015. * Returns a new Vector3.
  12016. */
  12017. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12018. var rotMatrix = new BABYLON.Matrix();
  12019. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12020. rotQuaternion.toRotationMatrix(rotMatrix);
  12021. var translationDelta = BABYLON.Vector3.Zero();
  12022. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12023. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12024. return translationDelta;
  12025. };
  12026. // ================================== Point of View Rotation =================================
  12027. /**
  12028. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12029. * Supports definition of mesh facing forward or backward.
  12030. * @param {number} flipBack
  12031. * @param {number} twirlClockwise
  12032. * @param {number} tiltRight
  12033. *
  12034. * Returns the AbstractMesh.
  12035. */
  12036. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12037. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12038. return this;
  12039. };
  12040. /**
  12041. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12042. * Supports definition of mesh facing forward or backward.
  12043. * @param {number} flipBack
  12044. * @param {number} twirlClockwise
  12045. * @param {number} tiltRight
  12046. *
  12047. * Returns a new Vector3.
  12048. */
  12049. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12050. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12051. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12052. };
  12053. /**
  12054. * Sets a new pivot matrix to the mesh.
  12055. * Returns the AbstractMesh.
  12056. */
  12057. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12058. this._pivotMatrix = matrix;
  12059. this._cache.pivotMatrixUpdated = true;
  12060. return this;
  12061. };
  12062. /**
  12063. * Returns the mesh pivot matrix.
  12064. * Default : Identity.
  12065. * A Matrix is returned.
  12066. */
  12067. AbstractMesh.prototype.getPivotMatrix = function () {
  12068. return this._pivotMatrix;
  12069. };
  12070. AbstractMesh.prototype._isSynchronized = function () {
  12071. if (this._isDirty) {
  12072. return false;
  12073. }
  12074. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12075. return false;
  12076. if (this._cache.pivotMatrixUpdated) {
  12077. return false;
  12078. }
  12079. if (this.infiniteDistance) {
  12080. return false;
  12081. }
  12082. if (!this._cache.position.equals(this.position))
  12083. return false;
  12084. if (this.rotationQuaternion) {
  12085. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12086. return false;
  12087. }
  12088. if (!this._cache.rotation.equals(this.rotation))
  12089. return false;
  12090. if (!this._cache.scaling.equals(this.scaling))
  12091. return false;
  12092. return true;
  12093. };
  12094. AbstractMesh.prototype._initCache = function () {
  12095. _super.prototype._initCache.call(this);
  12096. this._cache.localMatrixUpdated = false;
  12097. this._cache.position = BABYLON.Vector3.Zero();
  12098. this._cache.scaling = BABYLON.Vector3.Zero();
  12099. this._cache.rotation = BABYLON.Vector3.Zero();
  12100. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12101. this._cache.billboardMode = -1;
  12102. };
  12103. AbstractMesh.prototype.markAsDirty = function (property) {
  12104. if (property === "rotation") {
  12105. this.rotationQuaternion = null;
  12106. }
  12107. this._currentRenderId = Number.MAX_VALUE;
  12108. this._isDirty = true;
  12109. return this;
  12110. };
  12111. /**
  12112. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12113. * Returns the AbstractMesh.
  12114. */
  12115. AbstractMesh.prototype._updateBoundingInfo = function () {
  12116. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12117. this._boundingInfo.update(this.worldMatrixFromCache);
  12118. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12119. return this;
  12120. };
  12121. /**
  12122. * Update a mesh's children BoundingInfo objects only.
  12123. * Returns the AbstractMesh.
  12124. */
  12125. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12126. if (!this.subMeshes) {
  12127. return;
  12128. }
  12129. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12130. var subMesh = this.subMeshes[subIndex];
  12131. if (!subMesh.IsGlobal) {
  12132. subMesh.updateBoundingInfo(matrix);
  12133. }
  12134. }
  12135. return this;
  12136. };
  12137. /**
  12138. * Computes the mesh World matrix and returns it.
  12139. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12140. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12141. * If the parameter `force`is set to `true`, the actual computation is done.
  12142. * Returns the mesh World Matrix.
  12143. */
  12144. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12145. if (this._isWorldMatrixFrozen) {
  12146. return this._worldMatrix;
  12147. }
  12148. if (!force && this.isSynchronized(true)) {
  12149. this._currentRenderId = this.getScene().getRenderId();
  12150. return this._worldMatrix;
  12151. }
  12152. this._cache.position.copyFrom(this.position);
  12153. this._cache.scaling.copyFrom(this.scaling);
  12154. this._cache.pivotMatrixUpdated = false;
  12155. this._cache.billboardMode = this.billboardMode;
  12156. this._currentRenderId = this.getScene().getRenderId();
  12157. this._isDirty = false;
  12158. // Scaling
  12159. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12160. // Rotation
  12161. //rotate, if quaternion is set and rotation was used
  12162. if (this.rotationQuaternion) {
  12163. var len = this.rotation.length();
  12164. if (len) {
  12165. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12166. this.rotation.copyFromFloats(0, 0, 0);
  12167. }
  12168. }
  12169. if (this.rotationQuaternion) {
  12170. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12171. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12172. }
  12173. else {
  12174. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12175. this._cache.rotation.copyFrom(this.rotation);
  12176. }
  12177. // Translation
  12178. if (this.infiniteDistance && !this.parent) {
  12179. var camera = this.getScene().activeCamera;
  12180. if (camera) {
  12181. var cameraWorldMatrix = camera.getWorldMatrix();
  12182. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12183. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12184. }
  12185. }
  12186. else {
  12187. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12188. }
  12189. // Composing transformations
  12190. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12191. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12192. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12193. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12194. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12195. // Need to decompose each rotation here
  12196. var currentPosition = BABYLON.Tmp.Vector3[3];
  12197. if (this.parent && this.parent.getWorldMatrix) {
  12198. if (this._meshToBoneReferal) {
  12199. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12201. }
  12202. else {
  12203. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12204. }
  12205. }
  12206. else {
  12207. currentPosition.copyFrom(this.position);
  12208. }
  12209. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12210. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12211. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12212. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12213. }
  12214. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12215. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12216. }
  12217. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12218. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12219. }
  12220. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12221. }
  12222. else {
  12223. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12224. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12225. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12226. }
  12227. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12228. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12229. }
  12230. // Local world
  12231. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12232. // Parent
  12233. if (this.parent && this.parent.getWorldMatrix) {
  12234. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12235. if (this._meshToBoneReferal) {
  12236. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12237. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12238. }
  12239. else {
  12240. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12241. }
  12242. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12243. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12244. this._worldMatrix.copyFrom(this._localWorld);
  12245. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12246. }
  12247. else {
  12248. if (this._meshToBoneReferal) {
  12249. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12250. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12251. }
  12252. else {
  12253. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12254. }
  12255. }
  12256. this._markSyncedWithParent();
  12257. }
  12258. else {
  12259. this._worldMatrix.copyFrom(this._localWorld);
  12260. }
  12261. // Bounding info
  12262. this._updateBoundingInfo();
  12263. // Absolute position
  12264. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12265. // Callbacks
  12266. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12267. if (!this._poseMatrix) {
  12268. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12269. }
  12270. return this._worldMatrix;
  12271. };
  12272. /**
  12273. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12274. * @param func: callback function to add
  12275. *
  12276. * Returns the AbstractMesh.
  12277. */
  12278. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12279. this.onAfterWorldMatrixUpdateObservable.add(func);
  12280. return this;
  12281. };
  12282. /**
  12283. * Removes a registered callback function.
  12284. * Returns the AbstractMesh.
  12285. */
  12286. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12287. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12288. return this;
  12289. };
  12290. /**
  12291. * Sets the mesh position in its local space.
  12292. * Returns the AbstractMesh.
  12293. */
  12294. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12295. this.computeWorldMatrix();
  12296. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12297. return this;
  12298. };
  12299. /**
  12300. * Returns the mesh position in the local space from the current World matrix values.
  12301. * Returns a new Vector3.
  12302. */
  12303. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12304. this.computeWorldMatrix();
  12305. var invLocalWorldMatrix = this._localWorld.clone();
  12306. invLocalWorldMatrix.invert();
  12307. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12308. };
  12309. /**
  12310. * Translates the mesh along the passed Vector3 in its local space.
  12311. * Returns the AbstractMesh.
  12312. */
  12313. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12314. this.computeWorldMatrix(true);
  12315. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12316. return this;
  12317. };
  12318. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12319. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12320. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12321. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12322. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12323. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12324. /// <returns>Mesh oriented towards targetMesh</returns>
  12325. if (yawCor === void 0) { yawCor = 0; }
  12326. if (pitchCor === void 0) { pitchCor = 0; }
  12327. if (rollCor === void 0) { rollCor = 0; }
  12328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12329. var dv = AbstractMesh._lookAtVectorCache;
  12330. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12331. targetPoint.subtractToRef(pos, dv);
  12332. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12333. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12334. var pitch = Math.atan2(dv.y, len);
  12335. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12336. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12337. return this;
  12338. };
  12339. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12340. this._meshToBoneReferal = affectedMesh;
  12341. this.parent = bone;
  12342. if (bone.getWorldMatrix().determinant() < 0) {
  12343. this.scalingDeterminant *= -1;
  12344. }
  12345. return this;
  12346. };
  12347. AbstractMesh.prototype.detachFromBone = function () {
  12348. if (this.parent.getWorldMatrix().determinant() < 0) {
  12349. this.scalingDeterminant *= -1;
  12350. }
  12351. this._meshToBoneReferal = null;
  12352. this.parent = null;
  12353. return this;
  12354. };
  12355. /**
  12356. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12357. * A mesh is in the frustum if its bounding box intersects the frustum.
  12358. * Boolean returned.
  12359. */
  12360. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12361. return this._boundingInfo.isInFrustum(frustumPlanes);
  12362. };
  12363. /**
  12364. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12365. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12366. * Boolean returned.
  12367. */
  12368. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12369. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12370. ;
  12371. };
  12372. /**
  12373. * True if the mesh intersects another mesh or a SolidParticle object.
  12374. * 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)
  12375. * Returns a boolean.
  12376. */
  12377. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12378. if (!this._boundingInfo || !mesh._boundingInfo) {
  12379. return false;
  12380. }
  12381. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12382. };
  12383. /**
  12384. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12385. * Returns a boolean.
  12386. */
  12387. AbstractMesh.prototype.intersectsPoint = function (point) {
  12388. if (!this._boundingInfo) {
  12389. return false;
  12390. }
  12391. return this._boundingInfo.intersectsPoint(point);
  12392. };
  12393. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12394. return this.physicsImpostor;
  12395. };
  12396. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12397. if (!camera) {
  12398. camera = this.getScene().activeCamera;
  12399. }
  12400. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12401. };
  12402. /**
  12403. * Returns the distance from the mesh to the active camera.
  12404. * Returns a float.
  12405. */
  12406. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12407. if (!camera) {
  12408. camera = this.getScene().activeCamera;
  12409. }
  12410. return this.absolutePosition.subtract(camera.position).length();
  12411. };
  12412. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12413. if (!this.physicsImpostor) {
  12414. return;
  12415. }
  12416. this.physicsImpostor.applyImpulse(force, contactPoint);
  12417. return this;
  12418. };
  12419. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12420. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12421. return;
  12422. }
  12423. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12424. mainPivot: pivot1,
  12425. connectedPivot: pivot2,
  12426. nativeParams: options
  12427. });
  12428. return this;
  12429. };
  12430. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12431. // Collisions
  12432. /**
  12433. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12434. * Default `false`.
  12435. */
  12436. get: function () {
  12437. return this._checkCollisions;
  12438. },
  12439. set: function (collisionEnabled) {
  12440. this._checkCollisions = collisionEnabled;
  12441. if (this.getScene().workerCollisions) {
  12442. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12443. }
  12444. },
  12445. enumerable: true,
  12446. configurable: true
  12447. });
  12448. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12449. var globalPosition = this.getAbsolutePosition();
  12450. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12451. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12452. if (!this._collider) {
  12453. this._collider = new BABYLON.Collider();
  12454. }
  12455. this._collider.radius = this.ellipsoid;
  12456. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12457. return this;
  12458. };
  12459. // Submeshes octree
  12460. /**
  12461. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12462. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12463. * Returns an Octree of submeshes.
  12464. */
  12465. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12466. if (maxCapacity === void 0) { maxCapacity = 64; }
  12467. if (maxDepth === void 0) { maxDepth = 2; }
  12468. if (!this._submeshesOctree) {
  12469. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12470. }
  12471. this.computeWorldMatrix(true);
  12472. // Update octree
  12473. var bbox = this.getBoundingInfo().boundingBox;
  12474. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12475. return this._submeshesOctree;
  12476. };
  12477. // Collisions
  12478. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12479. this._generatePointsArray();
  12480. // Transformation
  12481. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12482. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12483. subMesh._lastColliderWorldVertices = [];
  12484. subMesh._trianglePlanes = [];
  12485. var start = subMesh.verticesStart;
  12486. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12487. for (var i = start; i < end; i++) {
  12488. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12489. }
  12490. }
  12491. // Collide
  12492. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12493. if (collider.collisionFound) {
  12494. collider.collidedMesh = this;
  12495. }
  12496. return this;
  12497. };
  12498. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12499. var subMeshes;
  12500. var len;
  12501. // Octrees
  12502. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12503. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12504. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12505. len = intersections.length;
  12506. subMeshes = intersections.data;
  12507. }
  12508. else {
  12509. subMeshes = this.subMeshes;
  12510. len = subMeshes.length;
  12511. }
  12512. for (var index = 0; index < len; index++) {
  12513. var subMesh = subMeshes[index];
  12514. // Bounding test
  12515. if (len > 1 && !subMesh._checkCollision(collider))
  12516. continue;
  12517. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12518. }
  12519. return this;
  12520. };
  12521. AbstractMesh.prototype._checkCollision = function (collider) {
  12522. // Bounding box test
  12523. if (!this._boundingInfo._checkCollision(collider))
  12524. return this;
  12525. // Transformation matrix
  12526. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12527. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12528. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12529. return this;
  12530. };
  12531. // Picking
  12532. AbstractMesh.prototype._generatePointsArray = function () {
  12533. return false;
  12534. };
  12535. /**
  12536. * Checks if the passed Ray intersects with the mesh.
  12537. * Returns an object PickingInfo.
  12538. */
  12539. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12540. var pickingInfo = new BABYLON.PickingInfo();
  12541. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12542. return pickingInfo;
  12543. }
  12544. if (!this._generatePointsArray()) {
  12545. return pickingInfo;
  12546. }
  12547. var intersectInfo = null;
  12548. // Octrees
  12549. var subMeshes;
  12550. var len;
  12551. if (this._submeshesOctree && this.useOctreeForPicking) {
  12552. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12553. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12554. len = intersections.length;
  12555. subMeshes = intersections.data;
  12556. }
  12557. else {
  12558. subMeshes = this.subMeshes;
  12559. len = subMeshes.length;
  12560. }
  12561. for (var index = 0; index < len; index++) {
  12562. var subMesh = subMeshes[index];
  12563. // Bounding test
  12564. if (len > 1 && !subMesh.canIntersects(ray))
  12565. continue;
  12566. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12567. if (currentIntersectInfo) {
  12568. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12569. intersectInfo = currentIntersectInfo;
  12570. intersectInfo.subMeshId = index;
  12571. if (fastCheck) {
  12572. break;
  12573. }
  12574. }
  12575. }
  12576. }
  12577. if (intersectInfo) {
  12578. // Get picked point
  12579. var world = this.getWorldMatrix();
  12580. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12581. var direction = ray.direction.clone();
  12582. direction = direction.scale(intersectInfo.distance);
  12583. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12584. var pickedPoint = worldOrigin.add(worldDirection);
  12585. // Return result
  12586. pickingInfo.hit = true;
  12587. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12588. pickingInfo.pickedPoint = pickedPoint;
  12589. pickingInfo.pickedMesh = this;
  12590. pickingInfo.bu = intersectInfo.bu;
  12591. pickingInfo.bv = intersectInfo.bv;
  12592. pickingInfo.faceId = intersectInfo.faceId;
  12593. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12594. return pickingInfo;
  12595. }
  12596. return pickingInfo;
  12597. };
  12598. /**
  12599. * Clones the mesh, used by the class Mesh.
  12600. * Just returns `null` for an AbstractMesh.
  12601. */
  12602. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12603. return null;
  12604. };
  12605. /**
  12606. * Disposes all the mesh submeshes.
  12607. * Returns the AbstractMesh.
  12608. */
  12609. AbstractMesh.prototype.releaseSubMeshes = function () {
  12610. if (this.subMeshes) {
  12611. while (this.subMeshes.length) {
  12612. this.subMeshes[0].dispose();
  12613. }
  12614. }
  12615. else {
  12616. this.subMeshes = new Array();
  12617. }
  12618. return this;
  12619. };
  12620. /**
  12621. * Disposes the AbstractMesh.
  12622. * Some internal references are kept for further use.
  12623. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12624. * Returns nothing.
  12625. */
  12626. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12627. var _this = this;
  12628. var index;
  12629. // Action manager
  12630. if (this.actionManager) {
  12631. this.actionManager.dispose();
  12632. this.actionManager = null;
  12633. }
  12634. // Skeleton
  12635. this.skeleton = null;
  12636. // Animations
  12637. this.getScene().stopAnimation(this);
  12638. // Physics
  12639. if (this.physicsImpostor) {
  12640. this.physicsImpostor.dispose();
  12641. }
  12642. // Intersections in progress
  12643. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12644. var other = this._intersectionsInProgress[index];
  12645. var pos = other._intersectionsInProgress.indexOf(this);
  12646. other._intersectionsInProgress.splice(pos, 1);
  12647. }
  12648. this._intersectionsInProgress = [];
  12649. // Lights
  12650. var lights = this.getScene().lights;
  12651. lights.forEach(function (light) {
  12652. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12653. if (meshIndex !== -1) {
  12654. light.includedOnlyMeshes.splice(meshIndex, 1);
  12655. }
  12656. meshIndex = light.excludedMeshes.indexOf(_this);
  12657. if (meshIndex !== -1) {
  12658. light.excludedMeshes.splice(meshIndex, 1);
  12659. }
  12660. // Shadow generators
  12661. var generator = light.getShadowGenerator();
  12662. if (generator) {
  12663. var shadowMap = generator.getShadowMap();
  12664. meshIndex = shadowMap.renderList.indexOf(_this);
  12665. if (meshIndex !== -1) {
  12666. shadowMap.renderList.splice(meshIndex, 1);
  12667. }
  12668. }
  12669. });
  12670. // Edges
  12671. if (this._edgesRenderer) {
  12672. this._edgesRenderer.dispose();
  12673. this._edgesRenderer = null;
  12674. }
  12675. // SubMeshes
  12676. if (this.getClassName() !== "InstancedMesh") {
  12677. this.releaseSubMeshes();
  12678. }
  12679. // Octree
  12680. var sceneOctree = this.getScene().selectionOctree;
  12681. if (sceneOctree) {
  12682. var index = sceneOctree.dynamicContent.indexOf(this);
  12683. if (index !== -1) {
  12684. sceneOctree.dynamicContent.splice(index, 1);
  12685. }
  12686. }
  12687. // Engine
  12688. this.getScene().getEngine().wipeCaches();
  12689. // Remove from scene
  12690. this.getScene().removeMesh(this);
  12691. if (!doNotRecurse) {
  12692. // Particles
  12693. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12694. if (this.getScene().particleSystems[index].emitter === this) {
  12695. this.getScene().particleSystems[index].dispose();
  12696. index--;
  12697. }
  12698. }
  12699. // Children
  12700. var objects = this.getDescendants(true);
  12701. for (index = 0; index < objects.length; index++) {
  12702. objects[index].dispose();
  12703. }
  12704. }
  12705. else {
  12706. var childMeshes = this.getChildMeshes(true);
  12707. for (index = 0; index < childMeshes.length; index++) {
  12708. var child = childMeshes[index];
  12709. child.parent = null;
  12710. child.computeWorldMatrix(true);
  12711. }
  12712. }
  12713. // facet data
  12714. if (this._facetDataEnabled) {
  12715. this.disableFacetData();
  12716. }
  12717. this.onAfterWorldMatrixUpdateObservable.clear();
  12718. this.onCollideObservable.clear();
  12719. this.onCollisionPositionChangeObservable.clear();
  12720. this._isDisposed = true;
  12721. _super.prototype.dispose.call(this);
  12722. };
  12723. /**
  12724. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12725. * This Vector3 is expressed in the World space.
  12726. */
  12727. AbstractMesh.prototype.getDirection = function (localAxis) {
  12728. var result = BABYLON.Vector3.Zero();
  12729. this.getDirectionToRef(localAxis, result);
  12730. return result;
  12731. };
  12732. /**
  12733. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12734. * localAxis is expressed in the mesh local space.
  12735. * result is computed in the Wordl space from the mesh World matrix.
  12736. * Returns the AbstractMesh.
  12737. */
  12738. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12739. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12740. return this;
  12741. };
  12742. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12744. if (this.getScene().getRenderId() == 0) {
  12745. this.computeWorldMatrix(true);
  12746. }
  12747. var wm = this.getWorldMatrix();
  12748. if (space == BABYLON.Space.WORLD) {
  12749. var tmat = BABYLON.Tmp.Matrix[0];
  12750. wm.invertToRef(tmat);
  12751. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12752. }
  12753. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12754. this._pivotMatrix.m[12] = -point.x;
  12755. this._pivotMatrix.m[13] = -point.y;
  12756. this._pivotMatrix.m[14] = -point.z;
  12757. this._cache.pivotMatrixUpdated = true;
  12758. return this;
  12759. };
  12760. /**
  12761. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12762. */
  12763. AbstractMesh.prototype.getPivotPoint = function () {
  12764. var point = BABYLON.Vector3.Zero();
  12765. this.getPivotPointToRef(point);
  12766. return point;
  12767. };
  12768. /**
  12769. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12770. * Returns the AbstractMesh.
  12771. */
  12772. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12773. result.x = -this._pivotMatrix.m[12];
  12774. result.y = -this._pivotMatrix.m[13];
  12775. result.z = -this._pivotMatrix.m[14];
  12776. return this;
  12777. };
  12778. /**
  12779. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12780. */
  12781. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12782. var point = BABYLON.Vector3.Zero();
  12783. this.getAbsolutePivotPointToRef(point);
  12784. return point;
  12785. };
  12786. /**
  12787. * Defines the passed mesh as the parent of the current mesh.
  12788. * Returns the AbstractMesh.
  12789. */
  12790. AbstractMesh.prototype.setParent = function (mesh) {
  12791. var child = this;
  12792. var parent = mesh;
  12793. if (mesh == null) {
  12794. var rotation = BABYLON.Tmp.Quaternion[0];
  12795. var position = BABYLON.Tmp.Vector3[0];
  12796. var scale = BABYLON.Tmp.Vector3[1];
  12797. child.getWorldMatrix().decompose(scale, rotation, position);
  12798. if (child.rotationQuaternion) {
  12799. child.rotationQuaternion.copyFrom(rotation);
  12800. }
  12801. else {
  12802. rotation.toEulerAnglesToRef(child.rotation);
  12803. }
  12804. child.position.x = position.x;
  12805. child.position.y = position.y;
  12806. child.position.z = position.z;
  12807. }
  12808. else {
  12809. var rotation = BABYLON.Tmp.Quaternion[0];
  12810. var position = BABYLON.Tmp.Vector3[0];
  12811. var scale = BABYLON.Tmp.Vector3[1];
  12812. var m1 = BABYLON.Tmp.Matrix[0];
  12813. var m2 = BABYLON.Tmp.Matrix[1];
  12814. parent.getWorldMatrix().decompose(scale, rotation, position);
  12815. rotation.toRotationMatrix(m1);
  12816. m2.setTranslation(position);
  12817. m2.multiplyToRef(m1, m1);
  12818. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12819. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12820. m.decompose(scale, rotation, position);
  12821. if (child.rotationQuaternion) {
  12822. child.rotationQuaternion.copyFrom(rotation);
  12823. }
  12824. else {
  12825. rotation.toEulerAnglesToRef(child.rotation);
  12826. }
  12827. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12828. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12829. m.decompose(scale, rotation, position);
  12830. child.position.x = position.x;
  12831. child.position.y = position.y;
  12832. child.position.z = position.z;
  12833. }
  12834. child.parent = parent;
  12835. return this;
  12836. };
  12837. /**
  12838. * Adds the passed mesh as a child to the current mesh.
  12839. * Returns the AbstractMesh.
  12840. */
  12841. AbstractMesh.prototype.addChild = function (mesh) {
  12842. mesh.setParent(this);
  12843. return this;
  12844. };
  12845. /**
  12846. * Removes the passed mesh from the current mesh children list.
  12847. * Returns the AbstractMesh.
  12848. */
  12849. AbstractMesh.prototype.removeChild = function (mesh) {
  12850. mesh.setParent(null);
  12851. return this;
  12852. };
  12853. /**
  12854. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12855. * Returns the AbstractMesh.
  12856. */
  12857. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12858. result.x = this._pivotMatrix.m[12];
  12859. result.y = this._pivotMatrix.m[13];
  12860. result.z = this._pivotMatrix.m[14];
  12861. this.getPivotPointToRef(result);
  12862. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12863. return this;
  12864. };
  12865. // Facet data
  12866. /**
  12867. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12868. * Returns the AbstractMesh.
  12869. */
  12870. AbstractMesh.prototype._initFacetData = function () {
  12871. if (!this._facetNormals) {
  12872. this._facetNormals = new Array();
  12873. }
  12874. if (!this._facetPositions) {
  12875. this._facetPositions = new Array();
  12876. }
  12877. if (!this._facetPartitioning) {
  12878. this._facetPartitioning = new Array();
  12879. }
  12880. this._facetNb = this.getIndices().length / 3;
  12881. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12882. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12883. for (var f = 0; f < this._facetNb; f++) {
  12884. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12885. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12886. }
  12887. this._facetDataEnabled = true;
  12888. return this;
  12889. };
  12890. /**
  12891. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12892. * This method can be called within the render loop.
  12893. * 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.
  12894. * Returns the AbstractMesh.
  12895. */
  12896. AbstractMesh.prototype.updateFacetData = function () {
  12897. if (!this._facetDataEnabled) {
  12898. this._initFacetData();
  12899. }
  12900. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12901. var indices = this.getIndices();
  12902. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12903. var bInfo = this.getBoundingInfo();
  12904. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12905. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12906. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12907. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12908. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12909. this._subDiv.max = this._partitioningSubdivisions;
  12910. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12911. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12912. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12913. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12914. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12915. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12916. // set the parameters for ComputeNormals()
  12917. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12918. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12919. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12920. this._facetParameters.bInfo = bInfo;
  12921. this._facetParameters.bbSize = this._bbSize;
  12922. this._facetParameters.subDiv = this._subDiv;
  12923. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12924. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12925. return this;
  12926. };
  12927. /**
  12928. * Returns the facetLocalNormals array.
  12929. * The normals are expressed in the mesh local space.
  12930. */
  12931. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12932. if (!this._facetNormals) {
  12933. this.updateFacetData();
  12934. }
  12935. return this._facetNormals;
  12936. };
  12937. /**
  12938. * Returns the facetLocalPositions array.
  12939. * The facet positions are expressed in the mesh local space.
  12940. */
  12941. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12942. if (!this._facetPositions) {
  12943. this.updateFacetData();
  12944. }
  12945. return this._facetPositions;
  12946. };
  12947. /**
  12948. * Returns the facetLocalPartioning array.
  12949. */
  12950. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12951. if (!this._facetPartitioning) {
  12952. this.updateFacetData();
  12953. }
  12954. return this._facetPartitioning;
  12955. };
  12956. /**
  12957. * Returns the i-th facet position in the world system.
  12958. * This method allocates a new Vector3 per call.
  12959. */
  12960. AbstractMesh.prototype.getFacetPosition = function (i) {
  12961. var pos = BABYLON.Vector3.Zero();
  12962. this.getFacetPositionToRef(i, pos);
  12963. return pos;
  12964. };
  12965. /**
  12966. * Sets the reference Vector3 with the i-th facet position in the world system.
  12967. * Returns the AbstractMesh.
  12968. */
  12969. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12970. var localPos = (this.getFacetLocalPositions())[i];
  12971. var world = this.getWorldMatrix();
  12972. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12973. return this;
  12974. };
  12975. /**
  12976. * Returns the i-th facet normal in the world system.
  12977. * This method allocates a new Vector3 per call.
  12978. */
  12979. AbstractMesh.prototype.getFacetNormal = function (i) {
  12980. var norm = BABYLON.Vector3.Zero();
  12981. this.getFacetNormalToRef(i, norm);
  12982. return norm;
  12983. };
  12984. /**
  12985. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12986. * Returns the AbstractMesh.
  12987. */
  12988. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12989. var localNorm = (this.getFacetLocalNormals())[i];
  12990. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12991. return this;
  12992. };
  12993. /**
  12994. * 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).
  12995. */
  12996. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12997. var bInfo = this.getBoundingInfo();
  12998. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12999. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13000. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13001. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13002. return null;
  13003. }
  13004. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13005. };
  13006. /**
  13007. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13008. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13009. * 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.
  13010. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13011. * 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.
  13012. */
  13013. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13014. if (checkFace === void 0) { checkFace = false; }
  13015. if (facing === void 0) { facing = true; }
  13016. var world = this.getWorldMatrix();
  13017. var invMat = BABYLON.Tmp.Matrix[5];
  13018. world.invertToRef(invMat);
  13019. var invVect = BABYLON.Tmp.Vector3[8];
  13020. var closest = null;
  13021. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13022. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13023. if (projected) {
  13024. // tranform the local computed projected vector to world coordinates
  13025. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13026. }
  13027. return closest;
  13028. };
  13029. /**
  13030. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13031. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13032. * 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.
  13033. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13034. * 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.
  13035. */
  13036. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13037. if (checkFace === void 0) { checkFace = false; }
  13038. if (facing === void 0) { facing = true; }
  13039. var closest = null;
  13040. var tmpx = 0.0;
  13041. var tmpy = 0.0;
  13042. var tmpz = 0.0;
  13043. var d = 0.0; // tmp dot facet normal * facet position
  13044. var t0 = 0.0;
  13045. var projx = 0.0;
  13046. var projy = 0.0;
  13047. var projz = 0.0;
  13048. // Get all the facets in the same partitioning block than (x, y, z)
  13049. var facetPositions = this.getFacetLocalPositions();
  13050. var facetNormals = this.getFacetLocalNormals();
  13051. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13052. if (!facetsInBlock) {
  13053. return null;
  13054. }
  13055. // Get the closest facet to (x, y, z)
  13056. var shortest = Number.MAX_VALUE; // init distance vars
  13057. var tmpDistance = shortest;
  13058. var fib; // current facet in the block
  13059. var norm; // current facet normal
  13060. var p0; // current facet barycenter position
  13061. // loop on all the facets in the current partitioning block
  13062. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13063. fib = facetsInBlock[idx];
  13064. norm = facetNormals[fib];
  13065. p0 = facetPositions[fib];
  13066. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13067. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13068. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13069. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13070. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13071. projx = x + norm.x * t0;
  13072. projy = y + norm.y * t0;
  13073. projz = z + norm.z * t0;
  13074. tmpx = projx - x;
  13075. tmpy = projy - y;
  13076. tmpz = projz - z;
  13077. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13078. if (tmpDistance < shortest) {
  13079. shortest = tmpDistance;
  13080. closest = fib;
  13081. if (projected) {
  13082. projected.x = projx;
  13083. projected.y = projy;
  13084. projected.z = projz;
  13085. }
  13086. }
  13087. }
  13088. }
  13089. return closest;
  13090. };
  13091. /**
  13092. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13093. */
  13094. AbstractMesh.prototype.getFacetDataParameters = function () {
  13095. return this._facetParameters;
  13096. };
  13097. /**
  13098. * Disables the feature FacetData and frees the related memory.
  13099. * Returns the AbstractMesh.
  13100. */
  13101. AbstractMesh.prototype.disableFacetData = function () {
  13102. if (this._facetDataEnabled) {
  13103. this._facetDataEnabled = false;
  13104. this._facetPositions = null;
  13105. this._facetNormals = null;
  13106. this._facetPartitioning = null;
  13107. this._facetParameters = null;
  13108. }
  13109. return this;
  13110. };
  13111. /**
  13112. * Creates new normals data for the mesh.
  13113. * @param updatable.
  13114. */
  13115. AbstractMesh.prototype.createNormals = function (updatable) {
  13116. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13117. var indices = this.getIndices();
  13118. var normals;
  13119. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13120. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13121. }
  13122. else {
  13123. normals = [];
  13124. }
  13125. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13126. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13127. };
  13128. return AbstractMesh;
  13129. }(BABYLON.Node));
  13130. // Statics
  13131. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13132. AbstractMesh._BILLBOARDMODE_X = 1;
  13133. AbstractMesh._BILLBOARDMODE_Y = 2;
  13134. AbstractMesh._BILLBOARDMODE_Z = 4;
  13135. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13136. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13137. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13138. BABYLON.AbstractMesh = AbstractMesh;
  13139. })(BABYLON || (BABYLON = {}));
  13140. //# sourceMappingURL=babylon.abstractMesh.js.map
  13141. var BABYLON;
  13142. (function (BABYLON) {
  13143. var Light = (function (_super) {
  13144. __extends(Light, _super);
  13145. /**
  13146. * Creates a Light object in the scene.
  13147. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13148. */
  13149. function Light(name, scene) {
  13150. var _this = _super.call(this, name, scene) || this;
  13151. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13152. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13153. _this.intensity = 1.0;
  13154. _this.range = Number.MAX_VALUE;
  13155. /**
  13156. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13157. * of light.
  13158. */
  13159. _this._photometricScale = 1.0;
  13160. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13161. _this._radius = 0.00001;
  13162. _this.renderPriority = 0;
  13163. /**
  13164. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13165. * the current shadow generator.
  13166. */
  13167. _this.shadowEnabled = true;
  13168. _this._excludeWithLayerMask = 0;
  13169. _this._includeOnlyWithLayerMask = 0;
  13170. _this._lightmapMode = 0;
  13171. _this._excludedMeshesIds = new Array();
  13172. _this._includedOnlyMeshesIds = new Array();
  13173. _this.getScene().addLight(_this);
  13174. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13175. _this._buildUniformLayout();
  13176. _this.includedOnlyMeshes = new Array();
  13177. _this.excludedMeshes = new Array();
  13178. _this._resyncMeshes();
  13179. return _this;
  13180. }
  13181. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13182. /**
  13183. * If every light affecting the material is in this lightmapMode,
  13184. * material.lightmapTexture adds or multiplies
  13185. * (depends on material.useLightmapAsShadowmap)
  13186. * after every other light calculations.
  13187. */
  13188. get: function () {
  13189. return Light._LIGHTMAP_DEFAULT;
  13190. },
  13191. enumerable: true,
  13192. configurable: true
  13193. });
  13194. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13195. /**
  13196. * material.lightmapTexture as only diffuse lighting from this light
  13197. * adds pnly specular lighting from this light
  13198. * adds dynamic shadows
  13199. */
  13200. get: function () {
  13201. return Light._LIGHTMAP_SPECULAR;
  13202. },
  13203. enumerable: true,
  13204. configurable: true
  13205. });
  13206. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13207. /**
  13208. * material.lightmapTexture as only lighting
  13209. * no light calculation from this light
  13210. * only adds dynamic shadows from this light
  13211. */
  13212. get: function () {
  13213. return Light._LIGHTMAP_SHADOWSONLY;
  13214. },
  13215. enumerable: true,
  13216. configurable: true
  13217. });
  13218. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13219. /**
  13220. * Each light type uses the default quantity according to its type:
  13221. * point/spot lights use luminous intensity
  13222. * directional lights use illuminance
  13223. */
  13224. get: function () {
  13225. return Light._INTENSITYMODE_AUTOMATIC;
  13226. },
  13227. enumerable: true,
  13228. configurable: true
  13229. });
  13230. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13231. /**
  13232. * lumen (lm)
  13233. */
  13234. get: function () {
  13235. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13236. },
  13237. enumerable: true,
  13238. configurable: true
  13239. });
  13240. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13241. /**
  13242. * candela (lm/sr)
  13243. */
  13244. get: function () {
  13245. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13246. },
  13247. enumerable: true,
  13248. configurable: true
  13249. });
  13250. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13251. /**
  13252. * lux (lm/m^2)
  13253. */
  13254. get: function () {
  13255. return Light._INTENSITYMODE_ILLUMINANCE;
  13256. },
  13257. enumerable: true,
  13258. configurable: true
  13259. });
  13260. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13261. /**
  13262. * nit (cd/m^2)
  13263. */
  13264. get: function () {
  13265. return Light._INTENSITYMODE_LUMINANCE;
  13266. },
  13267. enumerable: true,
  13268. configurable: true
  13269. });
  13270. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13271. /**
  13272. * Light type const id of the point light.
  13273. */
  13274. get: function () {
  13275. return Light._LIGHTTYPEID_POINTLIGHT;
  13276. },
  13277. enumerable: true,
  13278. configurable: true
  13279. });
  13280. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13281. /**
  13282. * Light type const id of the directional light.
  13283. */
  13284. get: function () {
  13285. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13286. },
  13287. enumerable: true,
  13288. configurable: true
  13289. });
  13290. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13291. /**
  13292. * Light type const id of the spot light.
  13293. */
  13294. get: function () {
  13295. return Light._LIGHTTYPEID_SPOTLIGHT;
  13296. },
  13297. enumerable: true,
  13298. configurable: true
  13299. });
  13300. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13301. /**
  13302. * Light type const id of the hemispheric light.
  13303. */
  13304. get: function () {
  13305. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. Object.defineProperty(Light.prototype, "intensityMode", {
  13311. /**
  13312. * Gets the photometric scale used to interpret the intensity.
  13313. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13314. */
  13315. get: function () {
  13316. return this._intensityMode;
  13317. },
  13318. /**
  13319. * Sets the photometric scale used to interpret the intensity.
  13320. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13321. */
  13322. set: function (value) {
  13323. this._intensityMode = value;
  13324. this._computePhotometricScale();
  13325. },
  13326. enumerable: true,
  13327. configurable: true
  13328. });
  13329. ;
  13330. ;
  13331. Object.defineProperty(Light.prototype, "radius", {
  13332. /**
  13333. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13334. */
  13335. get: function () {
  13336. return this._radius;
  13337. },
  13338. /**
  13339. * sets the light radius used by PBR Materials to simulate soft area lights.
  13340. */
  13341. set: function (value) {
  13342. this._radius = value;
  13343. this._computePhotometricScale();
  13344. },
  13345. enumerable: true,
  13346. configurable: true
  13347. });
  13348. ;
  13349. ;
  13350. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13351. get: function () {
  13352. return this._includedOnlyMeshes;
  13353. },
  13354. set: function (value) {
  13355. this._includedOnlyMeshes = value;
  13356. this._hookArrayForIncludedOnly(value);
  13357. },
  13358. enumerable: true,
  13359. configurable: true
  13360. });
  13361. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13362. get: function () {
  13363. return this._excludedMeshes;
  13364. },
  13365. set: function (value) {
  13366. this._excludedMeshes = value;
  13367. this._hookArrayForExcluded(value);
  13368. },
  13369. enumerable: true,
  13370. configurable: true
  13371. });
  13372. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13373. get: function () {
  13374. return this._excludeWithLayerMask;
  13375. },
  13376. set: function (value) {
  13377. this._excludeWithLayerMask = value;
  13378. this._resyncMeshes();
  13379. },
  13380. enumerable: true,
  13381. configurable: true
  13382. });
  13383. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13384. get: function () {
  13385. return this._includeOnlyWithLayerMask;
  13386. },
  13387. set: function (value) {
  13388. this._includeOnlyWithLayerMask = value;
  13389. this._resyncMeshes();
  13390. },
  13391. enumerable: true,
  13392. configurable: true
  13393. });
  13394. Object.defineProperty(Light.prototype, "lightmapMode", {
  13395. get: function () {
  13396. return this._lightmapMode;
  13397. },
  13398. set: function (value) {
  13399. if (this._lightmapMode === value) {
  13400. return;
  13401. }
  13402. this._lightmapMode = value;
  13403. this._markMeshesAsLightDirty();
  13404. },
  13405. enumerable: true,
  13406. configurable: true
  13407. });
  13408. Light.prototype._buildUniformLayout = function () {
  13409. // Overridden
  13410. };
  13411. /**
  13412. * Returns the string "Light".
  13413. */
  13414. Light.prototype.getClassName = function () {
  13415. return "Light";
  13416. };
  13417. /**
  13418. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13419. */
  13420. Light.prototype.toString = function (fullDetails) {
  13421. var ret = "Name: " + this.name;
  13422. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13423. if (this.animations) {
  13424. for (var i = 0; i < this.animations.length; i++) {
  13425. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13426. }
  13427. }
  13428. if (fullDetails) {
  13429. }
  13430. return ret;
  13431. };
  13432. /**
  13433. * Set the enabled state of this node.
  13434. * @param {boolean} value - the new enabled state
  13435. * @see isEnabled
  13436. */
  13437. Light.prototype.setEnabled = function (value) {
  13438. _super.prototype.setEnabled.call(this, value);
  13439. this._resyncMeshes();
  13440. };
  13441. /**
  13442. * Returns the Light associated shadow generator.
  13443. */
  13444. Light.prototype.getShadowGenerator = function () {
  13445. return this._shadowGenerator;
  13446. };
  13447. /**
  13448. * Returns a Vector3, the absolute light position in the World.
  13449. */
  13450. Light.prototype.getAbsolutePosition = function () {
  13451. return BABYLON.Vector3.Zero();
  13452. };
  13453. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13454. };
  13455. Light.prototype._getWorldMatrix = function () {
  13456. return BABYLON.Matrix.Identity();
  13457. };
  13458. /**
  13459. * Boolean : True if the light will affect the passed mesh.
  13460. */
  13461. Light.prototype.canAffectMesh = function (mesh) {
  13462. if (!mesh) {
  13463. return true;
  13464. }
  13465. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13466. return false;
  13467. }
  13468. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13469. return false;
  13470. }
  13471. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13472. return false;
  13473. }
  13474. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13475. return false;
  13476. }
  13477. return true;
  13478. };
  13479. /**
  13480. * Returns the light World matrix.
  13481. */
  13482. Light.prototype.getWorldMatrix = function () {
  13483. this._currentRenderId = this.getScene().getRenderId();
  13484. var worldMatrix = this._getWorldMatrix();
  13485. if (this.parent && this.parent.getWorldMatrix) {
  13486. if (!this._parentedWorldMatrix) {
  13487. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13488. }
  13489. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13490. this._markSyncedWithParent();
  13491. return this._parentedWorldMatrix;
  13492. }
  13493. return worldMatrix;
  13494. };
  13495. /**
  13496. * Sort function to order lights for rendering.
  13497. * @param a First Light object to compare to second.
  13498. * @param b Second Light object to compare first.
  13499. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13500. */
  13501. Light.compareLightsPriority = function (a, b) {
  13502. //shadow-casting lights have priority over non-shadow-casting lights
  13503. //the renderPrioirty is a secondary sort criterion
  13504. if (a.shadowEnabled !== b.shadowEnabled) {
  13505. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13506. }
  13507. return b.renderPriority - a.renderPriority;
  13508. };
  13509. /**
  13510. * Disposes the light.
  13511. */
  13512. Light.prototype.dispose = function () {
  13513. if (this._shadowGenerator) {
  13514. this._shadowGenerator.dispose();
  13515. this._shadowGenerator = null;
  13516. }
  13517. // Animations
  13518. this.getScene().stopAnimation(this);
  13519. // Remove from meshes
  13520. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13521. var mesh = _a[_i];
  13522. mesh._removeLightSource(this);
  13523. }
  13524. this._uniformBuffer.dispose();
  13525. // Remove from scene
  13526. this.getScene().removeLight(this);
  13527. _super.prototype.dispose.call(this);
  13528. };
  13529. /**
  13530. * Returns the light type ID (integer).
  13531. */
  13532. Light.prototype.getTypeID = function () {
  13533. return 0;
  13534. };
  13535. /**
  13536. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13537. */
  13538. Light.prototype.getScaledIntensity = function () {
  13539. return this._photometricScale * this.intensity;
  13540. };
  13541. /**
  13542. * Returns a new Light object, named "name", from the current one.
  13543. */
  13544. Light.prototype.clone = function (name) {
  13545. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13546. };
  13547. /**
  13548. * Serializes the current light into a Serialization object.
  13549. * Returns the serialized object.
  13550. */
  13551. Light.prototype.serialize = function () {
  13552. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13553. // Type
  13554. serializationObject.type = this.getTypeID();
  13555. // Parent
  13556. if (this.parent) {
  13557. serializationObject.parentId = this.parent.id;
  13558. }
  13559. // Inclusion / exclusions
  13560. if (this.excludedMeshes.length > 0) {
  13561. serializationObject.excludedMeshesIds = [];
  13562. this.excludedMeshes.forEach(function (mesh) {
  13563. serializationObject.excludedMeshesIds.push(mesh.id);
  13564. });
  13565. }
  13566. if (this.includedOnlyMeshes.length > 0) {
  13567. serializationObject.includedOnlyMeshesIds = [];
  13568. this.includedOnlyMeshes.forEach(function (mesh) {
  13569. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13570. });
  13571. }
  13572. // Animations
  13573. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13574. serializationObject.ranges = this.serializeAnimationRanges();
  13575. return serializationObject;
  13576. };
  13577. /**
  13578. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13579. * This new light is named "name" and added to the passed scene.
  13580. */
  13581. Light.GetConstructorFromName = function (type, name, scene) {
  13582. switch (type) {
  13583. case 0:
  13584. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13585. case 1:
  13586. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13587. case 2:
  13588. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13589. case 3:
  13590. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13591. }
  13592. };
  13593. /**
  13594. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13595. */
  13596. Light.Parse = function (parsedLight, scene) {
  13597. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13598. // Inclusion / exclusions
  13599. if (parsedLight.excludedMeshesIds) {
  13600. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13601. }
  13602. if (parsedLight.includedOnlyMeshesIds) {
  13603. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13604. }
  13605. // Parent
  13606. if (parsedLight.parentId) {
  13607. light._waitingParentId = parsedLight.parentId;
  13608. }
  13609. // Animations
  13610. if (parsedLight.animations) {
  13611. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13612. var parsedAnimation = parsedLight.animations[animationIndex];
  13613. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13614. }
  13615. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13616. }
  13617. if (parsedLight.autoAnimate) {
  13618. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13619. }
  13620. return light;
  13621. };
  13622. Light.prototype._hookArrayForExcluded = function (array) {
  13623. var _this = this;
  13624. var oldPush = array.push;
  13625. array.push = function () {
  13626. var items = [];
  13627. for (var _i = 0; _i < arguments.length; _i++) {
  13628. items[_i] = arguments[_i];
  13629. }
  13630. var result = oldPush.apply(array, items);
  13631. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13632. var item = items_1[_a];
  13633. item._resyncLighSource(_this);
  13634. }
  13635. return result;
  13636. };
  13637. var oldSplice = array.splice;
  13638. array.splice = function (index, deleteCount) {
  13639. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13640. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13641. var item = deleted_1[_i];
  13642. item._resyncLighSource(_this);
  13643. }
  13644. return deleted;
  13645. };
  13646. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13647. var item = array_1[_i];
  13648. item._resyncLighSource(this);
  13649. }
  13650. };
  13651. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13652. var _this = this;
  13653. var oldPush = array.push;
  13654. array.push = function () {
  13655. var items = [];
  13656. for (var _i = 0; _i < arguments.length; _i++) {
  13657. items[_i] = arguments[_i];
  13658. }
  13659. var result = oldPush.apply(array, items);
  13660. _this._resyncMeshes();
  13661. return result;
  13662. };
  13663. var oldSplice = array.splice;
  13664. array.splice = function (index, deleteCount) {
  13665. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13666. _this._resyncMeshes();
  13667. return deleted;
  13668. };
  13669. this._resyncMeshes();
  13670. };
  13671. Light.prototype._resyncMeshes = function () {
  13672. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13673. var mesh = _a[_i];
  13674. mesh._resyncLighSource(this);
  13675. }
  13676. };
  13677. Light.prototype._markMeshesAsLightDirty = function () {
  13678. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13679. var mesh = _a[_i];
  13680. if (mesh._lightSources.indexOf(this) !== -1) {
  13681. mesh._markSubMeshesAsLightDirty();
  13682. }
  13683. }
  13684. };
  13685. /**
  13686. * Recomputes the cached photometric scale if needed.
  13687. */
  13688. Light.prototype._computePhotometricScale = function () {
  13689. this._photometricScale = this._getPhotometricScale();
  13690. this.getScene().resetCachedMaterial();
  13691. };
  13692. /**
  13693. * Returns the Photometric Scale according to the light type and intensity mode.
  13694. */
  13695. Light.prototype._getPhotometricScale = function () {
  13696. var photometricScale = 0.0;
  13697. var lightTypeID = this.getTypeID();
  13698. //get photometric mode
  13699. var photometricMode = this.intensityMode;
  13700. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13701. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13702. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13703. }
  13704. else {
  13705. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13706. }
  13707. }
  13708. //compute photometric scale
  13709. switch (lightTypeID) {
  13710. case Light.LIGHTTYPEID_POINTLIGHT:
  13711. case Light.LIGHTTYPEID_SPOTLIGHT:
  13712. switch (photometricMode) {
  13713. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13714. photometricScale = 1.0 / (4.0 * Math.PI);
  13715. break;
  13716. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13717. photometricScale = 1.0;
  13718. break;
  13719. case Light.INTENSITYMODE_LUMINANCE:
  13720. photometricScale = this.radius * this.radius;
  13721. break;
  13722. }
  13723. break;
  13724. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13725. switch (photometricMode) {
  13726. case Light.INTENSITYMODE_ILLUMINANCE:
  13727. photometricScale = 1.0;
  13728. break;
  13729. case Light.INTENSITYMODE_LUMINANCE:
  13730. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13731. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13732. var apexAngleRadians = this.radius;
  13733. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13734. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13735. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13736. photometricScale = solidAngle;
  13737. break;
  13738. }
  13739. break;
  13740. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13741. // No fall off in hemisperic light.
  13742. photometricScale = 1.0;
  13743. break;
  13744. }
  13745. return photometricScale;
  13746. };
  13747. Light.prototype._reorderLightsInScene = function () {
  13748. var scene = this.getScene();
  13749. if (this.renderPriority != 0) {
  13750. scene.requireLightSorting = true;
  13751. }
  13752. this.getScene().sortLightsByPriority();
  13753. };
  13754. return Light;
  13755. }(BABYLON.Node));
  13756. //lightmapMode Consts
  13757. Light._LIGHTMAP_DEFAULT = 0;
  13758. Light._LIGHTMAP_SPECULAR = 1;
  13759. Light._LIGHTMAP_SHADOWSONLY = 2;
  13760. // Intensity Mode Consts
  13761. Light._INTENSITYMODE_AUTOMATIC = 0;
  13762. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13763. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13764. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13765. Light._INTENSITYMODE_LUMINANCE = 4;
  13766. // Light types ids const.
  13767. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13768. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13769. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13770. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13771. __decorate([
  13772. BABYLON.serializeAsColor3()
  13773. ], Light.prototype, "diffuse", void 0);
  13774. __decorate([
  13775. BABYLON.serializeAsColor3()
  13776. ], Light.prototype, "specular", void 0);
  13777. __decorate([
  13778. BABYLON.serialize()
  13779. ], Light.prototype, "intensity", void 0);
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], Light.prototype, "range", void 0);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], Light.prototype, "intensityMode", null);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], Light.prototype, "radius", null);
  13789. __decorate([
  13790. BABYLON.serialize()
  13791. ], Light.prototype, "_renderPriority", void 0);
  13792. __decorate([
  13793. BABYLON.expandToProperty("_reorderLightsInScene")
  13794. ], Light.prototype, "renderPriority", void 0);
  13795. __decorate([
  13796. BABYLON.serialize()
  13797. ], Light.prototype, "shadowEnabled", void 0);
  13798. __decorate([
  13799. BABYLON.serialize("excludeWithLayerMask")
  13800. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13801. __decorate([
  13802. BABYLON.serialize("includeOnlyWithLayerMask")
  13803. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13804. __decorate([
  13805. BABYLON.serialize("lightmapMode")
  13806. ], Light.prototype, "_lightmapMode", void 0);
  13807. BABYLON.Light = Light;
  13808. })(BABYLON || (BABYLON = {}));
  13809. //# sourceMappingURL=babylon.light.js.map
  13810. var BABYLON;
  13811. (function (BABYLON) {
  13812. var Camera = (function (_super) {
  13813. __extends(Camera, _super);
  13814. function Camera(name, position, scene) {
  13815. var _this = _super.call(this, name, scene) || this;
  13816. _this.upVector = BABYLON.Vector3.Up();
  13817. _this.orthoLeft = null;
  13818. _this.orthoRight = null;
  13819. _this.orthoBottom = null;
  13820. _this.orthoTop = null;
  13821. _this.fov = 0.8;
  13822. _this.minZ = 1.0;
  13823. _this.maxZ = 10000.0;
  13824. _this.inertia = 0.9;
  13825. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13826. _this.isIntermediate = false;
  13827. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13828. _this.layerMask = 0x0FFFFFFF;
  13829. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13830. // Camera rig members
  13831. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13832. _this._rigCameras = new Array();
  13833. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13834. // Cache
  13835. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13836. _this._projectionMatrix = new BABYLON.Matrix();
  13837. _this._doNotComputeProjectionMatrix = false;
  13838. _this._postProcesses = new Array();
  13839. _this._transformMatrix = BABYLON.Matrix.Zero();
  13840. _this._activeMeshes = new BABYLON.SmartArray(256);
  13841. _this._globalPosition = BABYLON.Vector3.Zero();
  13842. _this._refreshFrustumPlanes = true;
  13843. _this.getScene().addCamera(_this);
  13844. if (!_this.getScene().activeCamera) {
  13845. _this.getScene().activeCamera = _this;
  13846. }
  13847. _this.position = position;
  13848. return _this;
  13849. }
  13850. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13851. get: function () {
  13852. return Camera._PERSPECTIVE_CAMERA;
  13853. },
  13854. enumerable: true,
  13855. configurable: true
  13856. });
  13857. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13858. get: function () {
  13859. return Camera._ORTHOGRAPHIC_CAMERA;
  13860. },
  13861. enumerable: true,
  13862. configurable: true
  13863. });
  13864. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13865. get: function () {
  13866. return Camera._FOVMODE_VERTICAL_FIXED;
  13867. },
  13868. enumerable: true,
  13869. configurable: true
  13870. });
  13871. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13872. get: function () {
  13873. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13874. },
  13875. enumerable: true,
  13876. configurable: true
  13877. });
  13878. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13879. get: function () {
  13880. return Camera._RIG_MODE_NONE;
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13886. get: function () {
  13887. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13888. },
  13889. enumerable: true,
  13890. configurable: true
  13891. });
  13892. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13893. get: function () {
  13894. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13900. get: function () {
  13901. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13902. },
  13903. enumerable: true,
  13904. configurable: true
  13905. });
  13906. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13907. get: function () {
  13908. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13909. },
  13910. enumerable: true,
  13911. configurable: true
  13912. });
  13913. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13914. get: function () {
  13915. return Camera._RIG_MODE_VR;
  13916. },
  13917. enumerable: true,
  13918. configurable: true
  13919. });
  13920. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13921. get: function () {
  13922. return Camera._RIG_MODE_WEBVR;
  13923. },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. Camera.prototype.getClassName = function () {
  13928. return "Camera";
  13929. };
  13930. /**
  13931. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13932. */
  13933. Camera.prototype.toString = function (fullDetails) {
  13934. var ret = "Name: " + this.name;
  13935. ret += ", type: " + this.getClassName();
  13936. if (this.animations) {
  13937. for (var i = 0; i < this.animations.length; i++) {
  13938. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13939. }
  13940. }
  13941. if (fullDetails) {
  13942. }
  13943. return ret;
  13944. };
  13945. Object.defineProperty(Camera.prototype, "globalPosition", {
  13946. get: function () {
  13947. return this._globalPosition;
  13948. },
  13949. enumerable: true,
  13950. configurable: true
  13951. });
  13952. Camera.prototype.getActiveMeshes = function () {
  13953. return this._activeMeshes;
  13954. };
  13955. Camera.prototype.isActiveMesh = function (mesh) {
  13956. return (this._activeMeshes.indexOf(mesh) !== -1);
  13957. };
  13958. //Cache
  13959. Camera.prototype._initCache = function () {
  13960. _super.prototype._initCache.call(this);
  13961. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13962. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13963. this._cache.mode = undefined;
  13964. this._cache.minZ = undefined;
  13965. this._cache.maxZ = undefined;
  13966. this._cache.fov = undefined;
  13967. this._cache.fovMode = undefined;
  13968. this._cache.aspectRatio = undefined;
  13969. this._cache.orthoLeft = undefined;
  13970. this._cache.orthoRight = undefined;
  13971. this._cache.orthoBottom = undefined;
  13972. this._cache.orthoTop = undefined;
  13973. this._cache.renderWidth = undefined;
  13974. this._cache.renderHeight = undefined;
  13975. };
  13976. Camera.prototype._updateCache = function (ignoreParentClass) {
  13977. if (!ignoreParentClass) {
  13978. _super.prototype._updateCache.call(this);
  13979. }
  13980. var engine = this.getEngine();
  13981. this._cache.position.copyFrom(this.position);
  13982. this._cache.upVector.copyFrom(this.upVector);
  13983. this._cache.mode = this.mode;
  13984. this._cache.minZ = this.minZ;
  13985. this._cache.maxZ = this.maxZ;
  13986. this._cache.fov = this.fov;
  13987. this._cache.fovMode = this.fovMode;
  13988. this._cache.aspectRatio = engine.getAspectRatio(this);
  13989. this._cache.orthoLeft = this.orthoLeft;
  13990. this._cache.orthoRight = this.orthoRight;
  13991. this._cache.orthoBottom = this.orthoBottom;
  13992. this._cache.orthoTop = this.orthoTop;
  13993. this._cache.renderWidth = engine.getRenderWidth();
  13994. this._cache.renderHeight = engine.getRenderHeight();
  13995. };
  13996. Camera.prototype._updateFromScene = function () {
  13997. this.updateCache();
  13998. this.update();
  13999. };
  14000. // Synchronized
  14001. Camera.prototype._isSynchronized = function () {
  14002. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14003. };
  14004. Camera.prototype._isSynchronizedViewMatrix = function () {
  14005. if (!_super.prototype._isSynchronized.call(this))
  14006. return false;
  14007. return this._cache.position.equals(this.position)
  14008. && this._cache.upVector.equals(this.upVector)
  14009. && this.isSynchronizedWithParent();
  14010. };
  14011. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14012. var check = this._cache.mode === this.mode
  14013. && this._cache.minZ === this.minZ
  14014. && this._cache.maxZ === this.maxZ;
  14015. if (!check) {
  14016. return false;
  14017. }
  14018. var engine = this.getEngine();
  14019. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14020. check = this._cache.fov === this.fov
  14021. && this._cache.fovMode === this.fovMode
  14022. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14023. }
  14024. else {
  14025. check = this._cache.orthoLeft === this.orthoLeft
  14026. && this._cache.orthoRight === this.orthoRight
  14027. && this._cache.orthoBottom === this.orthoBottom
  14028. && this._cache.orthoTop === this.orthoTop
  14029. && this._cache.renderWidth === engine.getRenderWidth()
  14030. && this._cache.renderHeight === engine.getRenderHeight();
  14031. }
  14032. return check;
  14033. };
  14034. // Controls
  14035. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14036. };
  14037. Camera.prototype.detachControl = function (element) {
  14038. };
  14039. Camera.prototype.update = function () {
  14040. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14041. this._updateRigCameras();
  14042. }
  14043. this._checkInputs();
  14044. };
  14045. Camera.prototype._checkInputs = function () {
  14046. };
  14047. Object.defineProperty(Camera.prototype, "rigCameras", {
  14048. get: function () {
  14049. return this._rigCameras;
  14050. },
  14051. enumerable: true,
  14052. configurable: true
  14053. });
  14054. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14055. get: function () {
  14056. return this._rigPostProcess;
  14057. },
  14058. enumerable: true,
  14059. configurable: true
  14060. });
  14061. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14062. // invalidate framebuffer
  14063. if (this._postProcesses.length > 0) {
  14064. this._postProcesses[0].markTextureDirty();
  14065. }
  14066. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14067. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14068. var cam = this._rigCameras[i];
  14069. var rigPostProcess = cam._rigPostProcess;
  14070. // for VR rig, there does not have to be a post process
  14071. if (rigPostProcess) {
  14072. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14073. if (isPass) {
  14074. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14075. cam.isIntermediate = this._postProcesses.length === 0;
  14076. }
  14077. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14078. rigPostProcess.markTextureDirty();
  14079. }
  14080. else {
  14081. cam._postProcesses = this._postProcesses.slice(0);
  14082. }
  14083. }
  14084. };
  14085. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14086. if (insertAt === void 0) { insertAt = null; }
  14087. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14088. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14089. return 0;
  14090. }
  14091. if (insertAt == null || insertAt < 0) {
  14092. this._postProcesses.push(postProcess);
  14093. }
  14094. else {
  14095. this._postProcesses.splice(insertAt, 0, postProcess);
  14096. }
  14097. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14098. return this._postProcesses.indexOf(postProcess);
  14099. };
  14100. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14101. if (atIndices === void 0) { atIndices = null; }
  14102. var result = [];
  14103. var i;
  14104. var index;
  14105. if (!atIndices) {
  14106. var idx = this._postProcesses.indexOf(postProcess);
  14107. if (idx !== -1) {
  14108. this._postProcesses.splice(idx, 1);
  14109. }
  14110. }
  14111. else {
  14112. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14113. // iterate descending, so can just splice as we go
  14114. for (i = atIndices.length - 1; i >= 0; i--) {
  14115. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14116. result.push(i);
  14117. continue;
  14118. }
  14119. index = atIndices[i];
  14120. this._postProcesses.splice(index, 1);
  14121. }
  14122. }
  14123. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14124. return result;
  14125. };
  14126. Camera.prototype.getWorldMatrix = function () {
  14127. if (!this._worldMatrix) {
  14128. this._worldMatrix = BABYLON.Matrix.Identity();
  14129. }
  14130. var viewMatrix = this.getViewMatrix();
  14131. viewMatrix.invertToRef(this._worldMatrix);
  14132. return this._worldMatrix;
  14133. };
  14134. Camera.prototype._getViewMatrix = function () {
  14135. return BABYLON.Matrix.Identity();
  14136. };
  14137. Camera.prototype.getViewMatrix = function (force) {
  14138. this._computedViewMatrix = this._computeViewMatrix(force);
  14139. if (!force && this._isSynchronizedViewMatrix()) {
  14140. return this._computedViewMatrix;
  14141. }
  14142. this._refreshFrustumPlanes = true;
  14143. if (!this.parent || !this.parent.getWorldMatrix) {
  14144. this._globalPosition.copyFrom(this.position);
  14145. }
  14146. else {
  14147. if (!this._worldMatrix) {
  14148. this._worldMatrix = BABYLON.Matrix.Identity();
  14149. }
  14150. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14151. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14152. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14153. this._computedViewMatrix.invert();
  14154. this._markSyncedWithParent();
  14155. }
  14156. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14157. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14158. }
  14159. this._currentRenderId = this.getScene().getRenderId();
  14160. return this._computedViewMatrix;
  14161. };
  14162. Camera.prototype._computeViewMatrix = function (force) {
  14163. if (!force && this._isSynchronizedViewMatrix()) {
  14164. return this._computedViewMatrix;
  14165. }
  14166. this._computedViewMatrix = this._getViewMatrix();
  14167. this._currentRenderId = this.getScene().getRenderId();
  14168. return this._computedViewMatrix;
  14169. };
  14170. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14171. this._doNotComputeProjectionMatrix = true;
  14172. if (projection !== undefined) {
  14173. this._projectionMatrix = projection;
  14174. }
  14175. };
  14176. ;
  14177. Camera.prototype.unfreezeProjectionMatrix = function () {
  14178. this._doNotComputeProjectionMatrix = false;
  14179. };
  14180. ;
  14181. Camera.prototype.getProjectionMatrix = function (force) {
  14182. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14183. return this._projectionMatrix;
  14184. }
  14185. this._refreshFrustumPlanes = true;
  14186. var engine = this.getEngine();
  14187. var scene = this.getScene();
  14188. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14189. if (this.minZ <= 0) {
  14190. this.minZ = 0.1;
  14191. }
  14192. if (scene.useRightHandedSystem) {
  14193. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14194. }
  14195. else {
  14196. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14197. }
  14198. return this._projectionMatrix;
  14199. }
  14200. var halfWidth = engine.getRenderWidth() / 2.0;
  14201. var halfHeight = engine.getRenderHeight() / 2.0;
  14202. if (scene.useRightHandedSystem) {
  14203. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14204. }
  14205. else {
  14206. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14207. }
  14208. return this._projectionMatrix;
  14209. };
  14210. Camera.prototype.getTranformationMatrix = function () {
  14211. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14212. return this._transformMatrix;
  14213. };
  14214. Camera.prototype.updateFrustumPlanes = function () {
  14215. if (!this._refreshFrustumPlanes) {
  14216. return;
  14217. }
  14218. this.getTranformationMatrix();
  14219. if (!this._frustumPlanes) {
  14220. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14221. }
  14222. else {
  14223. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14224. }
  14225. this._refreshFrustumPlanes = false;
  14226. };
  14227. Camera.prototype.isInFrustum = function (target) {
  14228. this.updateFrustumPlanes();
  14229. return target.isInFrustum(this._frustumPlanes);
  14230. };
  14231. Camera.prototype.isCompletelyInFrustum = function (target) {
  14232. this.updateFrustumPlanes();
  14233. return target.isCompletelyInFrustum(this._frustumPlanes);
  14234. };
  14235. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14236. if (length === void 0) { length = 100; }
  14237. if (!transform) {
  14238. transform = this.getWorldMatrix();
  14239. }
  14240. if (!origin) {
  14241. origin = this.position;
  14242. }
  14243. var forward = new BABYLON.Vector3(0, 0, 1);
  14244. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14245. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14246. return new BABYLON.Ray(origin, direction, length);
  14247. };
  14248. Camera.prototype.dispose = function () {
  14249. // Animations
  14250. this.getScene().stopAnimation(this);
  14251. // Remove from scene
  14252. this.getScene().removeCamera(this);
  14253. while (this._rigCameras.length > 0) {
  14254. this._rigCameras.pop().dispose();
  14255. }
  14256. // Postprocesses
  14257. var i = this._postProcesses.length;
  14258. while (--i >= 0) {
  14259. this._postProcesses[i].dispose(this);
  14260. }
  14261. _super.prototype.dispose.call(this);
  14262. };
  14263. Object.defineProperty(Camera.prototype, "leftCamera", {
  14264. // ---- Camera rigs section ----
  14265. get: function () {
  14266. if (this._rigCameras.length < 1) {
  14267. return undefined;
  14268. }
  14269. return this._rigCameras[0];
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(Camera.prototype, "rightCamera", {
  14275. get: function () {
  14276. if (this._rigCameras.length < 2) {
  14277. return undefined;
  14278. }
  14279. return this._rigCameras[1];
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Camera.prototype.getLeftTarget = function () {
  14285. if (this._rigCameras.length < 1) {
  14286. return undefined;
  14287. }
  14288. return this._rigCameras[0].getTarget();
  14289. };
  14290. Camera.prototype.getRightTarget = function () {
  14291. if (this._rigCameras.length < 2) {
  14292. return undefined;
  14293. }
  14294. return this._rigCameras[1].getTarget();
  14295. };
  14296. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14297. while (this._rigCameras.length > 0) {
  14298. this._rigCameras.pop().dispose();
  14299. }
  14300. this.cameraRigMode = mode;
  14301. this._cameraRigParams = {};
  14302. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14303. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14304. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14305. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14306. // create the rig cameras, unless none
  14307. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14308. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14309. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14310. }
  14311. switch (this.cameraRigMode) {
  14312. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14313. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14314. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14315. break;
  14316. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14317. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14318. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14319. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14320. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14321. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14322. break;
  14323. case Camera.RIG_MODE_VR:
  14324. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14325. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14326. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14327. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14328. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14329. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14330. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14331. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14332. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14333. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14334. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14335. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14336. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14337. if (metrics.compensateDistortion) {
  14338. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14339. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14340. }
  14341. break;
  14342. case Camera.RIG_MODE_WEBVR:
  14343. if (rigParams.vrDisplay) {
  14344. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14345. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14346. //Left eye
  14347. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14348. this._rigCameras[0].setCameraRigParameter("left", true);
  14349. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14350. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14351. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14352. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14353. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14354. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14355. this._rigCameras[0].parent = this;
  14356. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14357. //Right eye
  14358. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14359. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14360. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14361. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14362. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14363. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14364. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14365. this._rigCameras[1].parent = this;
  14366. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14367. }
  14368. break;
  14369. }
  14370. this._cascadePostProcessesToRigCams();
  14371. this.
  14372. update();
  14373. };
  14374. Camera.prototype._getVRProjectionMatrix = function () {
  14375. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14376. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14377. return this._projectionMatrix;
  14378. };
  14379. Camera.prototype._updateCameraRotationMatrix = function () {
  14380. //Here for WebVR
  14381. };
  14382. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14383. //Here for WebVR
  14384. };
  14385. /**
  14386. * This function MUST be overwritten by the different WebVR cameras available.
  14387. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14388. */
  14389. Camera.prototype._getWebVRProjectionMatrix = function () {
  14390. return BABYLON.Matrix.Identity();
  14391. };
  14392. /**
  14393. * This function MUST be overwritten by the different WebVR cameras available.
  14394. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14395. */
  14396. Camera.prototype._getWebVRViewMatrix = function () {
  14397. return BABYLON.Matrix.Identity();
  14398. };
  14399. Camera.prototype.setCameraRigParameter = function (name, value) {
  14400. if (!this._cameraRigParams) {
  14401. this._cameraRigParams = {};
  14402. }
  14403. this._cameraRigParams[name] = value;
  14404. //provisionnally:
  14405. if (name === "interaxialDistance") {
  14406. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14407. }
  14408. };
  14409. /**
  14410. * needs to be overridden by children so sub has required properties to be copied
  14411. */
  14412. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14413. return null;
  14414. };
  14415. /**
  14416. * May need to be overridden by children
  14417. */
  14418. Camera.prototype._updateRigCameras = function () {
  14419. for (var i = 0; i < this._rigCameras.length; i++) {
  14420. this._rigCameras[i].minZ = this.minZ;
  14421. this._rigCameras[i].maxZ = this.maxZ;
  14422. this._rigCameras[i].fov = this.fov;
  14423. }
  14424. // only update viewport when ANAGLYPH
  14425. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14426. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14427. }
  14428. };
  14429. Camera.prototype._setupInputs = function () {
  14430. };
  14431. Camera.prototype.serialize = function () {
  14432. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14433. // Type
  14434. serializationObject.type = this.getClassName();
  14435. // Parent
  14436. if (this.parent) {
  14437. serializationObject.parentId = this.parent.id;
  14438. }
  14439. if (this.inputs) {
  14440. this.inputs.serialize(serializationObject);
  14441. }
  14442. // Animations
  14443. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14444. serializationObject.ranges = this.serializeAnimationRanges();
  14445. return serializationObject;
  14446. };
  14447. Camera.prototype.clone = function (name) {
  14448. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14449. };
  14450. Camera.prototype.getDirection = function (localAxis) {
  14451. var result = BABYLON.Vector3.Zero();
  14452. this.getDirectionToRef(localAxis, result);
  14453. return result;
  14454. };
  14455. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14456. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14457. };
  14458. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14459. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14460. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14461. switch (type) {
  14462. case "ArcRotateCamera":
  14463. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14464. case "DeviceOrientationCamera":
  14465. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14466. case "FollowCamera":
  14467. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14468. case "ArcFollowCamera":
  14469. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14470. case "GamepadCamera":
  14471. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14472. case "TouchCamera":
  14473. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14474. case "VirtualJoysticksCamera":
  14475. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14476. case "WebVRFreeCamera":
  14477. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14478. case "WebVRGamepadCamera":
  14479. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14480. case "VRDeviceOrientationFreeCamera":
  14481. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14482. case "VRDeviceOrientationGamepadCamera":
  14483. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14484. case "AnaglyphArcRotateCamera":
  14485. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14486. case "AnaglyphFreeCamera":
  14487. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14488. case "AnaglyphGamepadCamera":
  14489. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14490. case "AnaglyphUniversalCamera":
  14491. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14492. case "StereoscopicArcRotateCamera":
  14493. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14494. case "StereoscopicFreeCamera":
  14495. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14496. case "StereoscopicGamepadCamera":
  14497. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14498. case "StereoscopicUniversalCamera":
  14499. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14500. case "FreeCamera":
  14501. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14502. default:
  14503. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14504. }
  14505. };
  14506. Camera.Parse = function (parsedCamera, scene) {
  14507. var type = parsedCamera.type;
  14508. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14509. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14510. // Parent
  14511. if (parsedCamera.parentId) {
  14512. camera._waitingParentId = parsedCamera.parentId;
  14513. }
  14514. //If camera has an input manager, let it parse inputs settings
  14515. if (camera.inputs) {
  14516. camera.inputs.parse(parsedCamera);
  14517. camera._setupInputs();
  14518. }
  14519. // Target
  14520. if (parsedCamera.target) {
  14521. if (camera.setTarget) {
  14522. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14523. }
  14524. }
  14525. // Apply 3d rig, when found
  14526. if (parsedCamera.cameraRigMode) {
  14527. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14528. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14529. }
  14530. // Animations
  14531. if (parsedCamera.animations) {
  14532. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14533. var parsedAnimation = parsedCamera.animations[animationIndex];
  14534. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14535. }
  14536. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14537. }
  14538. if (parsedCamera.autoAnimate) {
  14539. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14540. }
  14541. return camera;
  14542. };
  14543. return Camera;
  14544. }(BABYLON.Node));
  14545. // Statics
  14546. Camera._PERSPECTIVE_CAMERA = 0;
  14547. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14548. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14549. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14550. Camera._RIG_MODE_NONE = 0;
  14551. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14552. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14553. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14554. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14555. Camera._RIG_MODE_VR = 20;
  14556. Camera._RIG_MODE_WEBVR = 21;
  14557. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14558. __decorate([
  14559. BABYLON.serializeAsVector3()
  14560. ], Camera.prototype, "position", void 0);
  14561. __decorate([
  14562. BABYLON.serializeAsVector3()
  14563. ], Camera.prototype, "upVector", void 0);
  14564. __decorate([
  14565. BABYLON.serialize()
  14566. ], Camera.prototype, "orthoLeft", void 0);
  14567. __decorate([
  14568. BABYLON.serialize()
  14569. ], Camera.prototype, "orthoRight", void 0);
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], Camera.prototype, "orthoBottom", void 0);
  14573. __decorate([
  14574. BABYLON.serialize()
  14575. ], Camera.prototype, "orthoTop", void 0);
  14576. __decorate([
  14577. BABYLON.serialize()
  14578. ], Camera.prototype, "fov", void 0);
  14579. __decorate([
  14580. BABYLON.serialize()
  14581. ], Camera.prototype, "minZ", void 0);
  14582. __decorate([
  14583. BABYLON.serialize()
  14584. ], Camera.prototype, "maxZ", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], Camera.prototype, "inertia", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "mode", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "layerMask", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "fovMode", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "cameraRigMode", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "interaxialDistance", void 0);
  14603. __decorate([
  14604. BABYLON.serialize()
  14605. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14606. BABYLON.Camera = Camera;
  14607. })(BABYLON || (BABYLON = {}));
  14608. //# sourceMappingURL=babylon.camera.js.map
  14609. var BABYLON;
  14610. (function (BABYLON) {
  14611. var RenderingManager = (function () {
  14612. function RenderingManager(scene) {
  14613. this._renderingGroups = new Array();
  14614. this._autoClearDepthStencil = {};
  14615. this._customOpaqueSortCompareFn = {};
  14616. this._customAlphaTestSortCompareFn = {};
  14617. this._customTransparentSortCompareFn = {};
  14618. this._renderinGroupInfo = null;
  14619. this._scene = scene;
  14620. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14621. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14622. }
  14623. }
  14624. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14625. if (depth === void 0) { depth = true; }
  14626. if (stencil === void 0) { stencil = true; }
  14627. if (this._depthStencilBufferAlreadyCleaned) {
  14628. return;
  14629. }
  14630. this._scene.getEngine().clear(null, false, depth, stencil);
  14631. this._depthStencilBufferAlreadyCleaned = true;
  14632. };
  14633. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14634. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14635. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14636. var info = null;
  14637. if (observable) {
  14638. if (!this._renderinGroupInfo) {
  14639. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14640. }
  14641. info = this._renderinGroupInfo;
  14642. info.scene = this._scene;
  14643. info.camera = this._scene.activeCamera;
  14644. }
  14645. // Dispatch sprites
  14646. if (renderSprites) {
  14647. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14648. var manager = this._scene.spriteManagers[index];
  14649. this.dispatchSprites(manager);
  14650. }
  14651. }
  14652. // Render
  14653. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14654. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14655. var renderingGroup = this._renderingGroups[index];
  14656. if (!renderingGroup && !observable)
  14657. continue;
  14658. this._currentIndex = index;
  14659. var renderingGroupMask = 0;
  14660. // Fire PRECLEAR stage
  14661. if (observable) {
  14662. renderingGroupMask = Math.pow(2, index);
  14663. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14664. info.renderingGroupId = index;
  14665. observable.notifyObservers(info, renderingGroupMask);
  14666. }
  14667. // Clear depth/stencil if needed
  14668. if (RenderingManager.AUTOCLEAR) {
  14669. var autoClear = this._autoClearDepthStencil[index];
  14670. if (autoClear && autoClear.autoClear) {
  14671. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14672. }
  14673. }
  14674. if (observable) {
  14675. // Fire PREOPAQUE stage
  14676. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14677. observable.notifyObservers(info, renderingGroupMask);
  14678. // Fire PRETRANSPARENT stage
  14679. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14680. observable.notifyObservers(info, renderingGroupMask);
  14681. }
  14682. if (renderingGroup)
  14683. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14684. // Fire POSTTRANSPARENT stage
  14685. if (observable) {
  14686. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14687. observable.notifyObservers(info, renderingGroupMask);
  14688. }
  14689. }
  14690. };
  14691. RenderingManager.prototype.reset = function () {
  14692. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14693. var renderingGroup = this._renderingGroups[index];
  14694. if (renderingGroup) {
  14695. renderingGroup.prepare();
  14696. }
  14697. }
  14698. };
  14699. RenderingManager.prototype.dispose = function () {
  14700. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14701. var renderingGroup = this._renderingGroups[index];
  14702. if (renderingGroup) {
  14703. renderingGroup.dispose();
  14704. }
  14705. }
  14706. this._renderingGroups.length = 0;
  14707. };
  14708. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14709. if (!this._renderingGroups[renderingGroupId]) {
  14710. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14711. }
  14712. };
  14713. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14714. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14715. this._prepareRenderingGroup(renderingGroupId);
  14716. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14717. };
  14718. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14719. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14720. this._prepareRenderingGroup(renderingGroupId);
  14721. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14722. };
  14723. RenderingManager.prototype.dispatch = function (subMesh) {
  14724. var mesh = subMesh.getMesh();
  14725. var renderingGroupId = mesh.renderingGroupId || 0;
  14726. this._prepareRenderingGroup(renderingGroupId);
  14727. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14728. };
  14729. /**
  14730. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14731. * This allowed control for front to back rendering or reversly depending of the special needs.
  14732. *
  14733. * @param renderingGroupId The rendering group id corresponding to its index
  14734. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14735. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14736. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14737. */
  14738. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14739. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14740. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14741. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14742. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14743. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14744. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14745. if (this._renderingGroups[renderingGroupId]) {
  14746. var group = this._renderingGroups[renderingGroupId];
  14747. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14748. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14749. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14750. }
  14751. };
  14752. /**
  14753. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14754. *
  14755. * @param renderingGroupId The rendering group id corresponding to its index
  14756. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14757. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14758. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14759. */
  14760. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14761. if (depth === void 0) { depth = true; }
  14762. if (stencil === void 0) { stencil = true; }
  14763. this._autoClearDepthStencil[renderingGroupId] = {
  14764. autoClear: autoClearDepthStencil,
  14765. depth: depth,
  14766. stencil: stencil
  14767. };
  14768. };
  14769. return RenderingManager;
  14770. }());
  14771. /**
  14772. * The max id used for rendering groups (not included)
  14773. */
  14774. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14775. /**
  14776. * The min id used for rendering groups (included)
  14777. */
  14778. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14779. /**
  14780. * Used to globally prevent autoclearing scenes.
  14781. */
  14782. RenderingManager.AUTOCLEAR = true;
  14783. BABYLON.RenderingManager = RenderingManager;
  14784. })(BABYLON || (BABYLON = {}));
  14785. //# sourceMappingURL=babylon.renderingManager.js.map
  14786. var BABYLON;
  14787. (function (BABYLON) {
  14788. var RenderingGroup = (function () {
  14789. /**
  14790. * Creates a new rendering group.
  14791. * @param index The rendering group index
  14792. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14793. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14794. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14795. */
  14796. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14797. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14798. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14799. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14800. this.index = index;
  14801. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14802. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14803. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14804. this._particleSystems = new BABYLON.SmartArray(256);
  14805. this._spriteManagers = new BABYLON.SmartArray(256);
  14806. this._edgesRenderers = new BABYLON.SmartArray(16);
  14807. this._scene = scene;
  14808. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14809. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14810. this.transparentSortCompareFn = transparentSortCompareFn;
  14811. }
  14812. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14813. /**
  14814. * Set the opaque sort comparison function.
  14815. * If null the sub meshes will be render in the order they were created
  14816. */
  14817. set: function (value) {
  14818. this._opaqueSortCompareFn = value;
  14819. if (value) {
  14820. this._renderOpaque = this.renderOpaqueSorted;
  14821. }
  14822. else {
  14823. this._renderOpaque = RenderingGroup.renderUnsorted;
  14824. }
  14825. },
  14826. enumerable: true,
  14827. configurable: true
  14828. });
  14829. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14830. /**
  14831. * Set the alpha test sort comparison function.
  14832. * If null the sub meshes will be render in the order they were created
  14833. */
  14834. set: function (value) {
  14835. this._alphaTestSortCompareFn = value;
  14836. if (value) {
  14837. this._renderAlphaTest = this.renderAlphaTestSorted;
  14838. }
  14839. else {
  14840. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14841. }
  14842. },
  14843. enumerable: true,
  14844. configurable: true
  14845. });
  14846. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14847. /**
  14848. * Set the transparent sort comparison function.
  14849. * If null the sub meshes will be render in the order they were created
  14850. */
  14851. set: function (value) {
  14852. if (value) {
  14853. this._transparentSortCompareFn = value;
  14854. }
  14855. else {
  14856. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14857. }
  14858. this._renderTransparent = this.renderTransparentSorted;
  14859. },
  14860. enumerable: true,
  14861. configurable: true
  14862. });
  14863. /**
  14864. * Render all the sub meshes contained in the group.
  14865. * @param customRenderFunction Used to override the default render behaviour of the group.
  14866. * @returns true if rendered some submeshes.
  14867. */
  14868. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14869. if (customRenderFunction) {
  14870. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14871. return;
  14872. }
  14873. var engine = this._scene.getEngine();
  14874. // Opaque
  14875. if (this._opaqueSubMeshes.length !== 0) {
  14876. this._renderOpaque(this._opaqueSubMeshes);
  14877. }
  14878. // Alpha test
  14879. if (this._alphaTestSubMeshes.length !== 0) {
  14880. engine.setAlphaTesting(true);
  14881. this._renderAlphaTest(this._alphaTestSubMeshes);
  14882. engine.setAlphaTesting(false);
  14883. }
  14884. var stencilState = engine.getStencilBuffer();
  14885. engine.setStencilBuffer(false);
  14886. // Sprites
  14887. if (renderSprites) {
  14888. this._renderSprites();
  14889. }
  14890. // Particles
  14891. if (renderParticles) {
  14892. this._renderParticles(activeMeshes);
  14893. }
  14894. if (this.onBeforeTransparentRendering) {
  14895. this.onBeforeTransparentRendering();
  14896. }
  14897. // Transparent
  14898. if (this._transparentSubMeshes.length !== 0) {
  14899. this._renderTransparent(this._transparentSubMeshes);
  14900. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14901. }
  14902. engine.setStencilBuffer(stencilState);
  14903. // Edges
  14904. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14905. this._edgesRenderers.data[edgesRendererIndex].render();
  14906. }
  14907. };
  14908. /**
  14909. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14910. * @param subMeshes The submeshes to render
  14911. */
  14912. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14913. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14914. };
  14915. /**
  14916. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14917. * @param subMeshes The submeshes to render
  14918. */
  14919. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14920. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14921. };
  14922. /**
  14923. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14924. * @param subMeshes The submeshes to render
  14925. */
  14926. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14927. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14928. };
  14929. /**
  14930. * Renders the submeshes in a specified order.
  14931. * @param subMeshes The submeshes to sort before render
  14932. * @param sortCompareFn The comparison function use to sort
  14933. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14934. * @param transparent Specifies to activate blending if true
  14935. */
  14936. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14937. var subIndex = 0;
  14938. var subMesh;
  14939. for (; subIndex < subMeshes.length; subIndex++) {
  14940. subMesh = subMeshes.data[subIndex];
  14941. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14942. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14943. }
  14944. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14945. sortedArray.sort(sortCompareFn);
  14946. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14947. subMesh = sortedArray[subIndex];
  14948. subMesh.render(transparent);
  14949. }
  14950. };
  14951. /**
  14952. * Renders the submeshes in the order they were dispatched (no sort applied).
  14953. * @param subMeshes The submeshes to render
  14954. */
  14955. RenderingGroup.renderUnsorted = function (subMeshes) {
  14956. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14957. var submesh = subMeshes.data[subIndex];
  14958. submesh.render(false);
  14959. }
  14960. };
  14961. /**
  14962. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14963. * are rendered back to front if in the same alpha index.
  14964. *
  14965. * @param a The first submesh
  14966. * @param b The second submesh
  14967. * @returns The result of the comparison
  14968. */
  14969. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14970. // Alpha index first
  14971. if (a._alphaIndex > b._alphaIndex) {
  14972. return 1;
  14973. }
  14974. if (a._alphaIndex < b._alphaIndex) {
  14975. return -1;
  14976. }
  14977. // Then distance to camera
  14978. return RenderingGroup.backToFrontSortCompare(a, b);
  14979. };
  14980. /**
  14981. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14982. * are rendered back to front.
  14983. *
  14984. * @param a The first submesh
  14985. * @param b The second submesh
  14986. * @returns The result of the comparison
  14987. */
  14988. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14989. // Then distance to camera
  14990. if (a._distanceToCamera < b._distanceToCamera) {
  14991. return 1;
  14992. }
  14993. if (a._distanceToCamera > b._distanceToCamera) {
  14994. return -1;
  14995. }
  14996. return 0;
  14997. };
  14998. /**
  14999. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15000. * are rendered front to back (prevent overdraw).
  15001. *
  15002. * @param a The first submesh
  15003. * @param b The second submesh
  15004. * @returns The result of the comparison
  15005. */
  15006. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15007. // Then distance to camera
  15008. if (a._distanceToCamera < b._distanceToCamera) {
  15009. return -1;
  15010. }
  15011. if (a._distanceToCamera > b._distanceToCamera) {
  15012. return 1;
  15013. }
  15014. return 0;
  15015. };
  15016. /**
  15017. * Resets the different lists of submeshes to prepare a new frame.
  15018. */
  15019. RenderingGroup.prototype.prepare = function () {
  15020. this._opaqueSubMeshes.reset();
  15021. this._transparentSubMeshes.reset();
  15022. this._alphaTestSubMeshes.reset();
  15023. this._particleSystems.reset();
  15024. this._spriteManagers.reset();
  15025. this._edgesRenderers.reset();
  15026. };
  15027. RenderingGroup.prototype.dispose = function () {
  15028. this._opaqueSubMeshes.dispose();
  15029. this._transparentSubMeshes.dispose();
  15030. this._alphaTestSubMeshes.dispose();
  15031. this._particleSystems.dispose();
  15032. this._spriteManagers.dispose();
  15033. this._edgesRenderers.dispose();
  15034. };
  15035. /**
  15036. * Inserts the submesh in its correct queue depending on its material.
  15037. * @param subMesh The submesh to dispatch
  15038. */
  15039. RenderingGroup.prototype.dispatch = function (subMesh) {
  15040. var material = subMesh.getMaterial();
  15041. var mesh = subMesh.getMesh();
  15042. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15043. this._transparentSubMeshes.push(subMesh);
  15044. }
  15045. else if (material.needAlphaTesting()) {
  15046. this._alphaTestSubMeshes.push(subMesh);
  15047. }
  15048. else {
  15049. this._opaqueSubMeshes.push(subMesh); // Opaque
  15050. }
  15051. if (mesh._edgesRenderer) {
  15052. this._edgesRenderers.push(mesh._edgesRenderer);
  15053. }
  15054. };
  15055. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15056. this._spriteManagers.push(spriteManager);
  15057. };
  15058. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15059. this._particleSystems.push(particleSystem);
  15060. };
  15061. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15062. if (this._particleSystems.length === 0) {
  15063. return;
  15064. }
  15065. // Particles
  15066. var activeCamera = this._scene.activeCamera;
  15067. this._scene._particlesDuration.beginMonitoring();
  15068. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15069. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15070. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15071. continue;
  15072. }
  15073. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15074. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15075. }
  15076. }
  15077. this._scene._particlesDuration.endMonitoring(false);
  15078. };
  15079. RenderingGroup.prototype._renderSprites = function () {
  15080. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15081. return;
  15082. }
  15083. // Sprites
  15084. var activeCamera = this._scene.activeCamera;
  15085. this._scene._spritesDuration.beginMonitoring();
  15086. for (var id = 0; id < this._spriteManagers.length; id++) {
  15087. var spriteManager = this._spriteManagers.data[id];
  15088. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15089. spriteManager.render();
  15090. }
  15091. }
  15092. this._scene._spritesDuration.endMonitoring(false);
  15093. };
  15094. return RenderingGroup;
  15095. }());
  15096. BABYLON.RenderingGroup = RenderingGroup;
  15097. })(BABYLON || (BABYLON = {}));
  15098. //# sourceMappingURL=babylon.renderingGroup.js.map
  15099. var BABYLON;
  15100. (function (BABYLON) {
  15101. var ClickInfo = (function () {
  15102. function ClickInfo() {
  15103. this._singleClick = false;
  15104. this._doubleClick = false;
  15105. this._hasSwiped = false;
  15106. this._ignore = false;
  15107. }
  15108. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15109. get: function () {
  15110. return this._singleClick;
  15111. },
  15112. set: function (b) {
  15113. this._singleClick = b;
  15114. },
  15115. enumerable: true,
  15116. configurable: true
  15117. });
  15118. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15119. get: function () {
  15120. return this._doubleClick;
  15121. },
  15122. set: function (b) {
  15123. this._doubleClick = b;
  15124. },
  15125. enumerable: true,
  15126. configurable: true
  15127. });
  15128. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15129. get: function () {
  15130. return this._hasSwiped;
  15131. },
  15132. set: function (b) {
  15133. this._hasSwiped = b;
  15134. },
  15135. enumerable: true,
  15136. configurable: true
  15137. });
  15138. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15139. get: function () {
  15140. return this._ignore;
  15141. },
  15142. set: function (b) {
  15143. this._ignore = b;
  15144. },
  15145. enumerable: true,
  15146. configurable: true
  15147. });
  15148. return ClickInfo;
  15149. }());
  15150. var PointerEventTypes = (function () {
  15151. function PointerEventTypes() {
  15152. }
  15153. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15154. get: function () {
  15155. return PointerEventTypes._POINTERDOWN;
  15156. },
  15157. enumerable: true,
  15158. configurable: true
  15159. });
  15160. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15161. get: function () {
  15162. return PointerEventTypes._POINTERUP;
  15163. },
  15164. enumerable: true,
  15165. configurable: true
  15166. });
  15167. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15168. get: function () {
  15169. return PointerEventTypes._POINTERMOVE;
  15170. },
  15171. enumerable: true,
  15172. configurable: true
  15173. });
  15174. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15175. get: function () {
  15176. return PointerEventTypes._POINTERWHEEL;
  15177. },
  15178. enumerable: true,
  15179. configurable: true
  15180. });
  15181. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15182. get: function () {
  15183. return PointerEventTypes._POINTERPICK;
  15184. },
  15185. enumerable: true,
  15186. configurable: true
  15187. });
  15188. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15189. get: function () {
  15190. return PointerEventTypes._POINTERTAP;
  15191. },
  15192. enumerable: true,
  15193. configurable: true
  15194. });
  15195. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15196. get: function () {
  15197. return PointerEventTypes._POINTERDOUBLETAP;
  15198. },
  15199. enumerable: true,
  15200. configurable: true
  15201. });
  15202. return PointerEventTypes;
  15203. }());
  15204. PointerEventTypes._POINTERDOWN = 0x01;
  15205. PointerEventTypes._POINTERUP = 0x02;
  15206. PointerEventTypes._POINTERMOVE = 0x04;
  15207. PointerEventTypes._POINTERWHEEL = 0x08;
  15208. PointerEventTypes._POINTERPICK = 0x10;
  15209. PointerEventTypes._POINTERTAP = 0x20;
  15210. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15211. BABYLON.PointerEventTypes = PointerEventTypes;
  15212. var PointerInfoBase = (function () {
  15213. function PointerInfoBase(type, event) {
  15214. this.type = type;
  15215. this.event = event;
  15216. }
  15217. return PointerInfoBase;
  15218. }());
  15219. BABYLON.PointerInfoBase = PointerInfoBase;
  15220. /**
  15221. * This class is used to store pointer related info for the onPrePointerObservable event.
  15222. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15223. */
  15224. var PointerInfoPre = (function (_super) {
  15225. __extends(PointerInfoPre, _super);
  15226. function PointerInfoPre(type, event, localX, localY) {
  15227. var _this = _super.call(this, type, event) || this;
  15228. _this.skipOnPointerObservable = false;
  15229. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15230. return _this;
  15231. }
  15232. return PointerInfoPre;
  15233. }(PointerInfoBase));
  15234. BABYLON.PointerInfoPre = PointerInfoPre;
  15235. /**
  15236. * This type contains all the data related to a pointer event in Babylon.js.
  15237. * 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.
  15238. */
  15239. var PointerInfo = (function (_super) {
  15240. __extends(PointerInfo, _super);
  15241. function PointerInfo(type, event, pickInfo) {
  15242. var _this = _super.call(this, type, event) || this;
  15243. _this.pickInfo = pickInfo;
  15244. return _this;
  15245. }
  15246. return PointerInfo;
  15247. }(PointerInfoBase));
  15248. BABYLON.PointerInfo = PointerInfo;
  15249. /**
  15250. * This class is used by the onRenderingGroupObservable
  15251. */
  15252. var RenderingGroupInfo = (function () {
  15253. function RenderingGroupInfo() {
  15254. }
  15255. return RenderingGroupInfo;
  15256. }());
  15257. /**
  15258. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15259. * This stage will be fired no matter what
  15260. */
  15261. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15262. /**
  15263. * Called before opaque object are rendered.
  15264. * This stage will be fired only if there's 3D Opaque content to render
  15265. */
  15266. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15267. /**
  15268. * Called after the opaque objects are rendered and before the transparent ones
  15269. * This stage will be fired only if there's 3D transparent content to render
  15270. */
  15271. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15272. /**
  15273. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15274. * This stage will be fired no matter what
  15275. */
  15276. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15277. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15278. /**
  15279. * Represents a scene to be rendered by the engine.
  15280. * @see http://doc.babylonjs.com/page.php?p=21911
  15281. */
  15282. var Scene = (function () {
  15283. /**
  15284. * @constructor
  15285. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15286. */
  15287. function Scene(engine) {
  15288. // Members
  15289. this.autoClear = true;
  15290. this.autoClearDepthAndStencil = true;
  15291. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15292. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15293. this.forceWireframe = false;
  15294. this._forcePointsCloud = false;
  15295. this.forceShowBoundingBoxes = false;
  15296. this.animationsEnabled = true;
  15297. this.constantlyUpdateMeshUnderPointer = false;
  15298. this.hoverCursor = "pointer";
  15299. // Metadata
  15300. this.metadata = null;
  15301. // Events
  15302. /**
  15303. * An event triggered when the scene is disposed.
  15304. * @type {BABYLON.Observable}
  15305. */
  15306. this.onDisposeObservable = new BABYLON.Observable();
  15307. /**
  15308. * An event triggered before rendering the scene
  15309. * @type {BABYLON.Observable}
  15310. */
  15311. this.onBeforeRenderObservable = new BABYLON.Observable();
  15312. /**
  15313. * An event triggered after rendering the scene
  15314. * @type {BABYLON.Observable}
  15315. */
  15316. this.onAfterRenderObservable = new BABYLON.Observable();
  15317. /**
  15318. * An event triggered when the scene is ready
  15319. * @type {BABYLON.Observable}
  15320. */
  15321. this.onReadyObservable = new BABYLON.Observable();
  15322. /**
  15323. * An event triggered before rendering a camera
  15324. * @type {BABYLON.Observable}
  15325. */
  15326. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15327. /**
  15328. * An event triggered after rendering a camera
  15329. * @type {BABYLON.Observable}
  15330. */
  15331. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15332. /**
  15333. * An event triggered when a camera is created
  15334. * @type {BABYLON.Observable}
  15335. */
  15336. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15337. /**
  15338. * An event triggered when a camera is removed
  15339. * @type {BABYLON.Observable}
  15340. */
  15341. this.onCameraRemovedObservable = new BABYLON.Observable();
  15342. /**
  15343. * An event triggered when a light is created
  15344. * @type {BABYLON.Observable}
  15345. */
  15346. this.onNewLightAddedObservable = new BABYLON.Observable();
  15347. /**
  15348. * An event triggered when a light is removed
  15349. * @type {BABYLON.Observable}
  15350. */
  15351. this.onLightRemovedObservable = new BABYLON.Observable();
  15352. /**
  15353. * An event triggered when a geometry is created
  15354. * @type {BABYLON.Observable}
  15355. */
  15356. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15357. /**
  15358. * An event triggered when a geometry is removed
  15359. * @type {BABYLON.Observable}
  15360. */
  15361. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15362. /**
  15363. * An event triggered when a mesh is created
  15364. * @type {BABYLON.Observable}
  15365. */
  15366. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15367. /**
  15368. * An event triggered when a mesh is removed
  15369. * @type {BABYLON.Observable}
  15370. */
  15371. this.onMeshRemovedObservable = new BABYLON.Observable();
  15372. /**
  15373. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15374. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15375. * 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)
  15376. */
  15377. this.onRenderingGroupObservable = new BABYLON.Observable();
  15378. // Animations
  15379. this.animations = [];
  15380. /**
  15381. * 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).
  15382. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15383. */
  15384. this.onPrePointerObservable = new BABYLON.Observable();
  15385. /**
  15386. * Observable event triggered each time an input event is received from the rendering canvas
  15387. */
  15388. this.onPointerObservable = new BABYLON.Observable();
  15389. this._meshPickProceed = false;
  15390. this._previousHasSwiped = false;
  15391. this._currentPickResult = null;
  15392. this._previousPickResult = null;
  15393. this._isButtonPressed = false;
  15394. this._doubleClickOccured = false;
  15395. 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
  15396. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15397. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15398. this._startingPointerTime = 0;
  15399. this._previousStartingPointerTime = 0;
  15400. // Coordinate system
  15401. /**
  15402. * use right-handed coordinate system on this scene.
  15403. * @type {boolean}
  15404. */
  15405. this._useRightHandedSystem = false;
  15406. // Fog
  15407. /**
  15408. * is fog enabled on this scene.
  15409. * @type {boolean}
  15410. */
  15411. this._fogEnabled = true;
  15412. this._fogMode = Scene.FOGMODE_NONE;
  15413. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15414. this.fogDensity = 0.1;
  15415. this.fogStart = 0;
  15416. this.fogEnd = 1000.0;
  15417. // Lights
  15418. /**
  15419. * is shadow enabled on this scene.
  15420. * @type {boolean}
  15421. */
  15422. this._shadowsEnabled = true;
  15423. /**
  15424. * is light enabled on this scene.
  15425. * @type {boolean}
  15426. */
  15427. this._lightsEnabled = true;
  15428. /**
  15429. * All of the lights added to this scene.
  15430. * @see BABYLON.Light
  15431. * @type {BABYLON.Light[]}
  15432. */
  15433. this.lights = new Array();
  15434. // Cameras
  15435. /**
  15436. * All of the cameras added to this scene.
  15437. * @see BABYLON.Camera
  15438. * @type {BABYLON.Camera[]}
  15439. */
  15440. this.cameras = new Array();
  15441. this.activeCameras = new Array();
  15442. // Meshes
  15443. /**
  15444. * All of the (abstract) meshes added to this scene.
  15445. * @see BABYLON.AbstractMesh
  15446. * @type {BABYLON.AbstractMesh[]}
  15447. */
  15448. this.meshes = new Array();
  15449. // Geometries
  15450. this._geometries = new Array();
  15451. this.materials = new Array();
  15452. this.multiMaterials = new Array();
  15453. // Textures
  15454. this._texturesEnabled = true;
  15455. this.textures = new Array();
  15456. // Particles
  15457. this.particlesEnabled = true;
  15458. this.particleSystems = new Array();
  15459. // Sprites
  15460. this.spritesEnabled = true;
  15461. this.spriteManagers = new Array();
  15462. // Layers
  15463. this.layers = new Array();
  15464. this.highlightLayers = new Array();
  15465. // Skeletons
  15466. this._skeletonsEnabled = true;
  15467. this.skeletons = new Array();
  15468. // Morph targets
  15469. this.morphTargetManagers = new Array();
  15470. // Lens flares
  15471. this.lensFlaresEnabled = true;
  15472. this.lensFlareSystems = new Array();
  15473. // Collisions
  15474. this.collisionsEnabled = true;
  15475. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15476. // Postprocesses
  15477. this.postProcessesEnabled = true;
  15478. // Customs render targets
  15479. this.renderTargetsEnabled = true;
  15480. this.dumpNextRenderTargets = false;
  15481. this.customRenderTargets = new Array();
  15482. // Imported meshes
  15483. this.importedMeshesFiles = new Array();
  15484. // Probes
  15485. this.probesEnabled = true;
  15486. this.reflectionProbes = new Array();
  15487. this._actionManagers = new Array();
  15488. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15489. // Procedural textures
  15490. this.proceduralTexturesEnabled = true;
  15491. this._proceduralTextures = new Array();
  15492. this.soundTracks = new Array();
  15493. this._audioEnabled = true;
  15494. this._headphone = false;
  15495. // Performance counters
  15496. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15497. this._totalLightsCounter = new BABYLON.PerfCounter();
  15498. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15499. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15500. this._totalVertices = new BABYLON.PerfCounter();
  15501. this._activeIndices = new BABYLON.PerfCounter();
  15502. this._activeParticles = new BABYLON.PerfCounter();
  15503. this._lastFrameDuration = new BABYLON.PerfCounter();
  15504. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15505. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15506. this._particlesDuration = new BABYLON.PerfCounter();
  15507. this._renderDuration = new BABYLON.PerfCounter();
  15508. this._spritesDuration = new BABYLON.PerfCounter();
  15509. this._activeBones = new BABYLON.PerfCounter();
  15510. this._animationTime = 0;
  15511. this.animationTimeScale = 1;
  15512. this._renderId = 0;
  15513. this._executeWhenReadyTimeoutId = -1;
  15514. this._intermediateRendering = false;
  15515. this._viewUpdateFlag = -1;
  15516. this._projectionUpdateFlag = -1;
  15517. this._toBeDisposed = new BABYLON.SmartArray(256);
  15518. this._pendingData = []; //ANY
  15519. this._activeMeshes = new BABYLON.SmartArray(256);
  15520. this._processedMaterials = new BABYLON.SmartArray(256);
  15521. this._renderTargets = new BABYLON.SmartArray(256);
  15522. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15523. this._activeSkeletons = new BABYLON.SmartArray(32);
  15524. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15525. this._activeAnimatables = new Array();
  15526. this._transformMatrix = BABYLON.Matrix.Zero();
  15527. this.requireLightSorting = false;
  15528. this._uniqueIdCounter = 0;
  15529. this.offscreenRenderTarget = null;
  15530. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15531. this._engine.scenes.push(this);
  15532. this._uid = null;
  15533. this._renderingManager = new BABYLON.RenderingManager(this);
  15534. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15535. if (BABYLON.OutlineRenderer) {
  15536. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15537. }
  15538. this.attachControl();
  15539. if (BABYLON.SoundTrack) {
  15540. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15541. }
  15542. //simplification queue
  15543. if (BABYLON.SimplificationQueue) {
  15544. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15545. }
  15546. //collision coordinator initialization. For now legacy per default.
  15547. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15548. // Uniform Buffer
  15549. this._createUbo();
  15550. }
  15551. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15552. get: function () {
  15553. return Scene._FOGMODE_NONE;
  15554. },
  15555. enumerable: true,
  15556. configurable: true
  15557. });
  15558. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15559. get: function () {
  15560. return Scene._FOGMODE_EXP;
  15561. },
  15562. enumerable: true,
  15563. configurable: true
  15564. });
  15565. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15566. get: function () {
  15567. return Scene._FOGMODE_EXP2;
  15568. },
  15569. enumerable: true,
  15570. configurable: true
  15571. });
  15572. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15573. get: function () {
  15574. return Scene._FOGMODE_LINEAR;
  15575. },
  15576. enumerable: true,
  15577. configurable: true
  15578. });
  15579. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15580. /**
  15581. * Texture used in all pbr material as the reflection texture.
  15582. * As in the majority of the scene they are the same (exception for multi room and so on),
  15583. * this is easier to reference from here than from all the materials.
  15584. */
  15585. get: function () {
  15586. return this._environmentTexture;
  15587. },
  15588. /**
  15589. * Texture used in all pbr material as the reflection texture.
  15590. * As in the majority of the scene they are the same (exception for multi room and so on),
  15591. * this is easier to set here than in all the materials.
  15592. */
  15593. set: function (value) {
  15594. this._environmentTexture = value;
  15595. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15596. },
  15597. enumerable: true,
  15598. configurable: true
  15599. });
  15600. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15601. get: function () {
  15602. return this._forcePointsCloud;
  15603. },
  15604. set: function (value) {
  15605. if (this._forcePointsCloud === value) {
  15606. return;
  15607. }
  15608. this._forcePointsCloud = value;
  15609. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15610. },
  15611. enumerable: true,
  15612. configurable: true
  15613. });
  15614. Object.defineProperty(Scene.prototype, "onDispose", {
  15615. set: function (callback) {
  15616. if (this._onDisposeObserver) {
  15617. this.onDisposeObservable.remove(this._onDisposeObserver);
  15618. }
  15619. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15620. },
  15621. enumerable: true,
  15622. configurable: true
  15623. });
  15624. Object.defineProperty(Scene.prototype, "beforeRender", {
  15625. set: function (callback) {
  15626. if (this._onBeforeRenderObserver) {
  15627. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15628. }
  15629. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15630. },
  15631. enumerable: true,
  15632. configurable: true
  15633. });
  15634. Object.defineProperty(Scene.prototype, "afterRender", {
  15635. set: function (callback) {
  15636. if (this._onAfterRenderObserver) {
  15637. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15638. }
  15639. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15640. },
  15641. enumerable: true,
  15642. configurable: true
  15643. });
  15644. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15645. set: function (callback) {
  15646. if (this._onBeforeCameraRenderObserver) {
  15647. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15648. }
  15649. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15650. },
  15651. enumerable: true,
  15652. configurable: true
  15653. });
  15654. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15655. set: function (callback) {
  15656. if (this._onAfterCameraRenderObserver) {
  15657. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15658. }
  15659. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15665. get: function () {
  15666. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15672. get: function () {
  15673. return this._useRightHandedSystem;
  15674. },
  15675. set: function (value) {
  15676. if (this._useRightHandedSystem === value) {
  15677. return;
  15678. }
  15679. this._useRightHandedSystem = value;
  15680. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15686. get: function () {
  15687. return this._fogEnabled;
  15688. },
  15689. set: function (value) {
  15690. if (this._fogEnabled === value) {
  15691. return;
  15692. }
  15693. this._fogEnabled = value;
  15694. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15695. },
  15696. enumerable: true,
  15697. configurable: true
  15698. });
  15699. Object.defineProperty(Scene.prototype, "fogMode", {
  15700. get: function () {
  15701. return this._fogMode;
  15702. },
  15703. set: function (value) {
  15704. if (this._fogMode === value) {
  15705. return;
  15706. }
  15707. this._fogMode = value;
  15708. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15709. },
  15710. enumerable: true,
  15711. configurable: true
  15712. });
  15713. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15714. get: function () {
  15715. return this._shadowsEnabled;
  15716. },
  15717. set: function (value) {
  15718. if (this._shadowsEnabled === value) {
  15719. return;
  15720. }
  15721. this._shadowsEnabled = value;
  15722. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15723. },
  15724. enumerable: true,
  15725. configurable: true
  15726. });
  15727. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15728. get: function () {
  15729. return this._lightsEnabled;
  15730. },
  15731. set: function (value) {
  15732. if (this._lightsEnabled === value) {
  15733. return;
  15734. }
  15735. this._lightsEnabled = value;
  15736. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15737. },
  15738. enumerable: true,
  15739. configurable: true
  15740. });
  15741. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15742. get: function () {
  15743. if (!this._defaultMaterial) {
  15744. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15745. }
  15746. return this._defaultMaterial;
  15747. },
  15748. set: function (value) {
  15749. this._defaultMaterial = value;
  15750. },
  15751. enumerable: true,
  15752. configurable: true
  15753. });
  15754. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15755. get: function () {
  15756. return this._texturesEnabled;
  15757. },
  15758. set: function (value) {
  15759. if (this._texturesEnabled === value) {
  15760. return;
  15761. }
  15762. this._texturesEnabled = value;
  15763. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15764. },
  15765. enumerable: true,
  15766. configurable: true
  15767. });
  15768. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15769. get: function () {
  15770. return this._skeletonsEnabled;
  15771. },
  15772. set: function (value) {
  15773. if (this._skeletonsEnabled === value) {
  15774. return;
  15775. }
  15776. this._skeletonsEnabled = value;
  15777. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15778. },
  15779. enumerable: true,
  15780. configurable: true
  15781. });
  15782. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15783. get: function () {
  15784. if (!this._postProcessRenderPipelineManager) {
  15785. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15786. }
  15787. return this._postProcessRenderPipelineManager;
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15793. get: function () {
  15794. return this._frustumPlanes;
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Scene.prototype, "debugLayer", {
  15800. // Properties
  15801. get: function () {
  15802. if (!this._debugLayer) {
  15803. this._debugLayer = new BABYLON.DebugLayer(this);
  15804. }
  15805. return this._debugLayer;
  15806. },
  15807. enumerable: true,
  15808. configurable: true
  15809. });
  15810. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15811. get: function () {
  15812. return this._workerCollisions;
  15813. },
  15814. set: function (enabled) {
  15815. if (!BABYLON.CollisionCoordinatorLegacy) {
  15816. return;
  15817. }
  15818. enabled = (enabled && !!Worker);
  15819. this._workerCollisions = enabled;
  15820. if (this.collisionCoordinator) {
  15821. this.collisionCoordinator.destroy();
  15822. }
  15823. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15824. this.collisionCoordinator.init(this);
  15825. },
  15826. enumerable: true,
  15827. configurable: true
  15828. });
  15829. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15830. get: function () {
  15831. return this._selectionOctree;
  15832. },
  15833. enumerable: true,
  15834. configurable: true
  15835. });
  15836. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15837. /**
  15838. * The mesh that is currently under the pointer.
  15839. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15840. */
  15841. get: function () {
  15842. return this._pointerOverMesh;
  15843. },
  15844. enumerable: true,
  15845. configurable: true
  15846. });
  15847. Object.defineProperty(Scene.prototype, "pointerX", {
  15848. /**
  15849. * Current on-screen X position of the pointer
  15850. * @return {number} X position of the pointer
  15851. */
  15852. get: function () {
  15853. return this._pointerX;
  15854. },
  15855. enumerable: true,
  15856. configurable: true
  15857. });
  15858. Object.defineProperty(Scene.prototype, "pointerY", {
  15859. /**
  15860. * Current on-screen Y position of the pointer
  15861. * @return {number} Y position of the pointer
  15862. */
  15863. get: function () {
  15864. return this._pointerY;
  15865. },
  15866. enumerable: true,
  15867. configurable: true
  15868. });
  15869. Scene.prototype.getCachedMaterial = function () {
  15870. return this._cachedMaterial;
  15871. };
  15872. Scene.prototype.getCachedEffect = function () {
  15873. return this._cachedEffect;
  15874. };
  15875. Scene.prototype.getCachedVisibility = function () {
  15876. return this._cachedVisibility;
  15877. };
  15878. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15879. if (visibility === void 0) { visibility = 0; }
  15880. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15881. };
  15882. Scene.prototype.getBoundingBoxRenderer = function () {
  15883. if (!this._boundingBoxRenderer) {
  15884. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15885. }
  15886. return this._boundingBoxRenderer;
  15887. };
  15888. Scene.prototype.getOutlineRenderer = function () {
  15889. return this._outlineRenderer;
  15890. };
  15891. Scene.prototype.getEngine = function () {
  15892. return this._engine;
  15893. };
  15894. Scene.prototype.getTotalVertices = function () {
  15895. return this._totalVertices.current;
  15896. };
  15897. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15898. get: function () {
  15899. return this._totalVertices;
  15900. },
  15901. enumerable: true,
  15902. configurable: true
  15903. });
  15904. Scene.prototype.getActiveIndices = function () {
  15905. return this._activeIndices.current;
  15906. };
  15907. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15908. get: function () {
  15909. return this._activeIndices;
  15910. },
  15911. enumerable: true,
  15912. configurable: true
  15913. });
  15914. Scene.prototype.getActiveParticles = function () {
  15915. return this._activeParticles.current;
  15916. };
  15917. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15918. get: function () {
  15919. return this._activeParticles;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. Scene.prototype.getActiveBones = function () {
  15925. return this._activeBones.current;
  15926. };
  15927. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15928. get: function () {
  15929. return this._activeBones;
  15930. },
  15931. enumerable: true,
  15932. configurable: true
  15933. });
  15934. // Stats
  15935. Scene.prototype.getLastFrameDuration = function () {
  15936. return this._lastFrameDuration.current;
  15937. };
  15938. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15939. get: function () {
  15940. return this._lastFrameDuration;
  15941. },
  15942. enumerable: true,
  15943. configurable: true
  15944. });
  15945. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15946. return this._evaluateActiveMeshesDuration.current;
  15947. };
  15948. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15949. get: function () {
  15950. return this._evaluateActiveMeshesDuration;
  15951. },
  15952. enumerable: true,
  15953. configurable: true
  15954. });
  15955. Scene.prototype.getActiveMeshes = function () {
  15956. return this._activeMeshes;
  15957. };
  15958. Scene.prototype.getRenderTargetsDuration = function () {
  15959. return this._renderTargetsDuration.current;
  15960. };
  15961. Scene.prototype.getRenderDuration = function () {
  15962. return this._renderDuration.current;
  15963. };
  15964. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15965. get: function () {
  15966. return this._renderDuration;
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. Scene.prototype.getParticlesDuration = function () {
  15972. return this._particlesDuration.current;
  15973. };
  15974. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15975. get: function () {
  15976. return this._particlesDuration;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Scene.prototype.getSpritesDuration = function () {
  15982. return this._spritesDuration.current;
  15983. };
  15984. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15985. get: function () {
  15986. return this._spritesDuration;
  15987. },
  15988. enumerable: true,
  15989. configurable: true
  15990. });
  15991. Scene.prototype.getAnimationRatio = function () {
  15992. return this._animationRatio;
  15993. };
  15994. Scene.prototype.getRenderId = function () {
  15995. return this._renderId;
  15996. };
  15997. Scene.prototype.incrementRenderId = function () {
  15998. this._renderId++;
  15999. };
  16000. Scene.prototype._updatePointerPosition = function (evt) {
  16001. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16002. this._pointerX = evt.clientX - canvasRect.left;
  16003. this._pointerY = evt.clientY - canvasRect.top;
  16004. this._unTranslatedPointerX = this._pointerX;
  16005. this._unTranslatedPointerY = this._pointerY;
  16006. if (this.cameraToUseForPointers) {
  16007. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16008. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16009. }
  16010. };
  16011. Scene.prototype._createUbo = function () {
  16012. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16013. this._sceneUbo.addUniform("viewProjection", 16);
  16014. this._sceneUbo.addUniform("view", 16);
  16015. };
  16016. // Pointers handling
  16017. /**
  16018. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16019. * @param attachUp defines if you want to attach events to pointerup
  16020. * @param attachDown defines if you want to attach events to pointerdown
  16021. * @param attachMove defines if you want to attach events to pointermove
  16022. */
  16023. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16024. var _this = this;
  16025. if (attachUp === void 0) { attachUp = true; }
  16026. if (attachDown === void 0) { attachDown = true; }
  16027. if (attachMove === void 0) { attachMove = true; }
  16028. this._initActionManager = function (act, clickInfo) {
  16029. if (!_this._meshPickProceed) {
  16030. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16031. _this._currentPickResult = pickResult;
  16032. if (pickResult) {
  16033. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16034. }
  16035. _this._meshPickProceed = true;
  16036. }
  16037. return act;
  16038. };
  16039. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16040. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16041. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16042. btn !== _this._previousButtonPressed) {
  16043. _this._doubleClickOccured = false;
  16044. clickInfo.singleClick = true;
  16045. clickInfo.ignore = false;
  16046. cb(clickInfo, _this._currentPickResult);
  16047. }
  16048. };
  16049. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16050. var clickInfo = new ClickInfo();
  16051. _this._currentPickResult = null;
  16052. var act;
  16053. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16054. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16055. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16056. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16057. act = _this._initActionManager(act, clickInfo);
  16058. if (act)
  16059. checkPicking = act.hasPickTriggers;
  16060. }
  16061. if (checkPicking) {
  16062. var btn = evt.button;
  16063. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16064. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16065. if (!clickInfo.hasSwiped) {
  16066. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16067. if (!checkSingleClickImmediately) {
  16068. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16069. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16070. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16071. act = _this._initActionManager(act, clickInfo);
  16072. if (act)
  16073. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16074. }
  16075. }
  16076. if (checkSingleClickImmediately) {
  16077. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16078. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16079. btn !== _this._previousButtonPressed) {
  16080. clickInfo.singleClick = true;
  16081. cb(clickInfo, _this._currentPickResult);
  16082. }
  16083. }
  16084. else {
  16085. // wait that no double click has been raised during the double click delay
  16086. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16087. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16088. }
  16089. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16090. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16091. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16092. act = _this._initActionManager(act, clickInfo);
  16093. if (act)
  16094. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16095. }
  16096. if (checkDoubleClick) {
  16097. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16098. if (btn === _this._previousButtonPressed &&
  16099. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16100. !_this._doubleClickOccured) {
  16101. // pointer has not moved for 2 clicks, it's a double click
  16102. if (!clickInfo.hasSwiped &&
  16103. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16104. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16105. _this._previousStartingPointerTime = 0;
  16106. _this._doubleClickOccured = true;
  16107. clickInfo.doubleClick = true;
  16108. clickInfo.ignore = false;
  16109. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16110. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16111. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16112. cb(clickInfo, _this._currentPickResult);
  16113. }
  16114. else {
  16115. _this._doubleClickOccured = false;
  16116. _this._previousStartingPointerTime = _this._startingPointerTime;
  16117. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16118. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16119. _this._previousButtonPressed = btn;
  16120. _this._previousHasSwiped = clickInfo.hasSwiped;
  16121. if (Scene.ExclusiveDoubleClickMode) {
  16122. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16123. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16124. }
  16125. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16126. cb(clickInfo, _this._previousPickResult);
  16127. }
  16128. else {
  16129. cb(clickInfo, _this._currentPickResult);
  16130. }
  16131. }
  16132. }
  16133. else {
  16134. _this._doubleClickOccured = false;
  16135. _this._previousStartingPointerTime = _this._startingPointerTime;
  16136. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16137. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16138. _this._previousButtonPressed = btn;
  16139. _this._previousHasSwiped = clickInfo.hasSwiped;
  16140. }
  16141. }
  16142. }
  16143. }
  16144. clickInfo.ignore = true;
  16145. cb(clickInfo, _this._currentPickResult);
  16146. };
  16147. var spritePredicate = function (sprite) {
  16148. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16149. };
  16150. this._onPointerMove = function (evt) {
  16151. _this._updatePointerPosition(evt);
  16152. // PreObservable support
  16153. if (_this.onPrePointerObservable.hasObservers()) {
  16154. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16155. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16156. _this.onPrePointerObservable.notifyObservers(pi, type);
  16157. if (pi.skipOnPointerObservable) {
  16158. return;
  16159. }
  16160. }
  16161. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16162. return;
  16163. }
  16164. var canvas = _this._engine.getRenderingCanvas();
  16165. if (!_this.pointerMovePredicate) {
  16166. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16167. }
  16168. // Meshes
  16169. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16170. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16171. _this.setPointerOverSprite(null);
  16172. _this.setPointerOverMesh(pickResult.pickedMesh);
  16173. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16174. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16175. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16176. }
  16177. else {
  16178. canvas.style.cursor = _this.hoverCursor;
  16179. }
  16180. }
  16181. else {
  16182. canvas.style.cursor = "";
  16183. }
  16184. }
  16185. else {
  16186. _this.setPointerOverMesh(null);
  16187. // Sprites
  16188. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16189. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16190. _this.setPointerOverSprite(pickResult.pickedSprite);
  16191. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16192. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16193. }
  16194. else {
  16195. canvas.style.cursor = _this.hoverCursor;
  16196. }
  16197. }
  16198. else {
  16199. _this.setPointerOverSprite(null);
  16200. // Restore pointer
  16201. canvas.style.cursor = "";
  16202. }
  16203. }
  16204. if (_this.onPointerMove) {
  16205. _this.onPointerMove(evt, pickResult);
  16206. }
  16207. if (_this.onPointerObservable.hasObservers()) {
  16208. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16209. var pi = new PointerInfo(type, evt, pickResult);
  16210. _this.onPointerObservable.notifyObservers(pi, type);
  16211. }
  16212. };
  16213. this._onPointerDown = function (evt) {
  16214. _this._isButtonPressed = true;
  16215. _this._pickedDownMesh = null;
  16216. _this._meshPickProceed = false;
  16217. _this._updatePointerPosition(evt);
  16218. // PreObservable support
  16219. if (_this.onPrePointerObservable.hasObservers()) {
  16220. var type = PointerEventTypes.POINTERDOWN;
  16221. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16222. _this.onPrePointerObservable.notifyObservers(pi, type);
  16223. if (pi.skipOnPointerObservable) {
  16224. return;
  16225. }
  16226. }
  16227. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16228. return;
  16229. }
  16230. _this._startingPointerPosition.x = _this._pointerX;
  16231. _this._startingPointerPosition.y = _this._pointerY;
  16232. _this._startingPointerTime = new Date().getTime();
  16233. if (!_this.pointerDownPredicate) {
  16234. _this.pointerDownPredicate = function (mesh) {
  16235. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16236. };
  16237. }
  16238. // Meshes
  16239. _this._pickedDownMesh = null;
  16240. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16241. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16242. _this._pickedDownMesh = pickResult.pickedMesh;
  16243. var actionManager = pickResult.pickedMesh.actionManager;
  16244. if (actionManager) {
  16245. if (actionManager.hasPickTriggers) {
  16246. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16247. switch (evt.button) {
  16248. case 0:
  16249. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16250. break;
  16251. case 1:
  16252. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16253. break;
  16254. case 2:
  16255. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16256. break;
  16257. }
  16258. }
  16259. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16260. window.setTimeout((function () {
  16261. var _this = this;
  16262. 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);
  16263. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16264. if (this._isButtonPressed &&
  16265. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16266. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16267. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16268. this._startingPointerTime = 0;
  16269. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16270. }
  16271. }
  16272. }).bind(_this), Scene.LongPressDelay);
  16273. }
  16274. }
  16275. }
  16276. if (_this.onPointerDown) {
  16277. _this.onPointerDown(evt, pickResult);
  16278. }
  16279. if (_this.onPointerObservable.hasObservers()) {
  16280. var type = PointerEventTypes.POINTERDOWN;
  16281. var pi = new PointerInfo(type, evt, pickResult);
  16282. _this.onPointerObservable.notifyObservers(pi, type);
  16283. }
  16284. // Sprites
  16285. _this._pickedDownSprite = null;
  16286. if (_this.spriteManagers.length > 0) {
  16287. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16288. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16289. if (pickResult.pickedSprite.actionManager) {
  16290. _this._pickedDownSprite = pickResult.pickedSprite;
  16291. switch (evt.button) {
  16292. case 0:
  16293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16294. break;
  16295. case 1:
  16296. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16297. break;
  16298. case 2:
  16299. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16300. break;
  16301. }
  16302. if (pickResult.pickedSprite.actionManager) {
  16303. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16304. }
  16305. }
  16306. }
  16307. }
  16308. };
  16309. this._onPointerUp = function (evt) {
  16310. _this._isButtonPressed = false;
  16311. _this._pickedUpMesh = null;
  16312. _this._meshPickProceed = false;
  16313. _this._updatePointerPosition(evt);
  16314. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16315. // PreObservable support
  16316. if (this.onPrePointerObservable.hasObservers()) {
  16317. if (!clickInfo.ignore) {
  16318. if (!clickInfo.hasSwiped) {
  16319. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16320. var type = PointerEventTypes.POINTERTAP;
  16321. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16322. this.onPrePointerObservable.notifyObservers(pi, type);
  16323. if (pi.skipOnPointerObservable) {
  16324. return;
  16325. }
  16326. }
  16327. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16328. var type = PointerEventTypes.POINTERDOUBLETAP;
  16329. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16330. this.onPrePointerObservable.notifyObservers(pi, type);
  16331. if (pi.skipOnPointerObservable) {
  16332. return;
  16333. }
  16334. }
  16335. }
  16336. }
  16337. else {
  16338. var type = PointerEventTypes.POINTERUP;
  16339. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16340. this.onPrePointerObservable.notifyObservers(pi, type);
  16341. if (pi.skipOnPointerObservable) {
  16342. return;
  16343. }
  16344. }
  16345. }
  16346. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16347. return;
  16348. }
  16349. if (!this.pointerUpPredicate) {
  16350. this.pointerUpPredicate = function (mesh) {
  16351. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16352. };
  16353. }
  16354. // Meshes
  16355. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16356. this._initActionManager(null, clickInfo);
  16357. }
  16358. if (!pickResult) {
  16359. pickResult = this._currentPickResult;
  16360. }
  16361. if (pickResult && pickResult && pickResult.pickedMesh) {
  16362. this._pickedUpMesh = pickResult.pickedMesh;
  16363. if (this._pickedDownMesh === this._pickedUpMesh) {
  16364. if (this.onPointerPick) {
  16365. this.onPointerPick(evt, pickResult);
  16366. }
  16367. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16368. var type = PointerEventTypes.POINTERPICK;
  16369. var pi = new PointerInfo(type, evt, pickResult);
  16370. this.onPointerObservable.notifyObservers(pi, type);
  16371. }
  16372. }
  16373. if (pickResult.pickedMesh.actionManager) {
  16374. if (clickInfo.ignore) {
  16375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16376. }
  16377. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16379. }
  16380. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16382. }
  16383. }
  16384. }
  16385. if (this._pickedDownMesh &&
  16386. this._pickedDownMesh.actionManager &&
  16387. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16388. this._pickedDownMesh !== this._pickedUpMesh) {
  16389. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16390. }
  16391. if (this.onPointerUp) {
  16392. this.onPointerUp(evt, pickResult);
  16393. }
  16394. if (this.onPointerObservable.hasObservers()) {
  16395. if (!clickInfo.ignore) {
  16396. if (!clickInfo.hasSwiped) {
  16397. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16398. var type = PointerEventTypes.POINTERTAP;
  16399. var pi = new PointerInfo(type, evt, pickResult);
  16400. this.onPointerObservable.notifyObservers(pi, type);
  16401. }
  16402. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16403. var type = PointerEventTypes.POINTERDOUBLETAP;
  16404. var pi = new PointerInfo(type, evt, pickResult);
  16405. this.onPointerObservable.notifyObservers(pi, type);
  16406. }
  16407. }
  16408. }
  16409. else {
  16410. var type = PointerEventTypes.POINTERUP;
  16411. var pi = new PointerInfo(type, evt, pickResult);
  16412. this.onPointerObservable.notifyObservers(pi, type);
  16413. }
  16414. }
  16415. // Sprites
  16416. if (this.spriteManagers.length > 0) {
  16417. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16418. if (pickResult.hit && pickResult.pickedSprite) {
  16419. if (pickResult.pickedSprite.actionManager) {
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16421. if (pickResult.pickedSprite.actionManager) {
  16422. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16423. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16424. }
  16425. }
  16426. }
  16427. }
  16428. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16429. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16430. }
  16431. }
  16432. this._previousPickResult = this._currentPickResult;
  16433. }).bind(_this));
  16434. };
  16435. this._onKeyDown = function (evt) {
  16436. if (_this.actionManager) {
  16437. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16438. }
  16439. };
  16440. this._onKeyUp = function (evt) {
  16441. if (_this.actionManager) {
  16442. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16443. }
  16444. };
  16445. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16446. var canvas = this._engine.getRenderingCanvas();
  16447. if (attachMove) {
  16448. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16449. // Wheel
  16450. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16451. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16452. }
  16453. if (attachDown) {
  16454. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16455. }
  16456. if (attachUp) {
  16457. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16458. }
  16459. canvas.tabIndex = 1;
  16460. canvas.addEventListener("keydown", this._onKeyDown, false);
  16461. canvas.addEventListener("keyup", this._onKeyUp, false);
  16462. };
  16463. Scene.prototype.detachControl = function () {
  16464. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16465. var canvas = this._engine.getRenderingCanvas();
  16466. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16467. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16468. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16469. // Wheel
  16470. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16471. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16472. canvas.removeEventListener("keydown", this._onKeyDown);
  16473. canvas.removeEventListener("keyup", this._onKeyUp);
  16474. };
  16475. // Ready
  16476. Scene.prototype.isReady = function () {
  16477. if (this._pendingData.length > 0) {
  16478. return false;
  16479. }
  16480. var index;
  16481. // Geometries
  16482. for (index = 0; index < this._geometries.length; index++) {
  16483. var geometry = this._geometries[index];
  16484. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16485. return false;
  16486. }
  16487. }
  16488. // Meshes
  16489. for (index = 0; index < this.meshes.length; index++) {
  16490. var mesh = this.meshes[index];
  16491. if (!mesh.isEnabled()) {
  16492. continue;
  16493. }
  16494. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16495. continue;
  16496. }
  16497. if (!mesh.isReady()) {
  16498. return false;
  16499. }
  16500. var mat = mesh.material;
  16501. if (mat) {
  16502. if (!mat.isReady(mesh)) {
  16503. return false;
  16504. }
  16505. }
  16506. }
  16507. return true;
  16508. };
  16509. Scene.prototype.resetCachedMaterial = function () {
  16510. this._cachedMaterial = null;
  16511. this._cachedEffect = null;
  16512. this._cachedVisibility = null;
  16513. };
  16514. Scene.prototype.registerBeforeRender = function (func) {
  16515. this.onBeforeRenderObservable.add(func);
  16516. };
  16517. Scene.prototype.unregisterBeforeRender = function (func) {
  16518. this.onBeforeRenderObservable.removeCallback(func);
  16519. };
  16520. Scene.prototype.registerAfterRender = function (func) {
  16521. this.onAfterRenderObservable.add(func);
  16522. };
  16523. Scene.prototype.unregisterAfterRender = function (func) {
  16524. this.onAfterRenderObservable.removeCallback(func);
  16525. };
  16526. Scene.prototype._addPendingData = function (data) {
  16527. this._pendingData.push(data);
  16528. };
  16529. Scene.prototype._removePendingData = function (data) {
  16530. var index = this._pendingData.indexOf(data);
  16531. if (index !== -1) {
  16532. this._pendingData.splice(index, 1);
  16533. }
  16534. };
  16535. Scene.prototype.getWaitingItemsCount = function () {
  16536. return this._pendingData.length;
  16537. };
  16538. /**
  16539. * Registers a function to be executed when the scene is ready.
  16540. * @param {Function} func - the function to be executed.
  16541. */
  16542. Scene.prototype.executeWhenReady = function (func) {
  16543. var _this = this;
  16544. this.onReadyObservable.add(func);
  16545. if (this._executeWhenReadyTimeoutId !== -1) {
  16546. return;
  16547. }
  16548. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16549. _this._checkIsReady();
  16550. }, 150);
  16551. };
  16552. Scene.prototype._checkIsReady = function () {
  16553. var _this = this;
  16554. if (this.isReady()) {
  16555. this.onReadyObservable.notifyObservers(this);
  16556. this.onReadyObservable.clear();
  16557. this._executeWhenReadyTimeoutId = -1;
  16558. return;
  16559. }
  16560. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16561. _this._checkIsReady();
  16562. }, 150);
  16563. };
  16564. // Animations
  16565. /**
  16566. * Will start the animation sequence of a given target
  16567. * @param target - the target
  16568. * @param {number} from - from which frame should animation start
  16569. * @param {number} to - till which frame should animation run.
  16570. * @param {boolean} [loop] - should the animation loop
  16571. * @param {number} [speedRatio] - the speed in which to run the animation
  16572. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16573. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16574. * @return {BABYLON.Animatable} the animatable object created for this animation
  16575. * @see BABYLON.Animatable
  16576. * @see http://doc.babylonjs.com/page.php?p=22081
  16577. */
  16578. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16579. if (speedRatio === void 0) { speedRatio = 1.0; }
  16580. if (from > to && speedRatio > 0) {
  16581. speedRatio *= -1;
  16582. }
  16583. this.stopAnimation(target);
  16584. if (!animatable) {
  16585. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16586. }
  16587. // Local animations
  16588. if (target.animations) {
  16589. animatable.appendAnimations(target, target.animations);
  16590. }
  16591. // Children animations
  16592. if (target.getAnimatables) {
  16593. var animatables = target.getAnimatables();
  16594. for (var index = 0; index < animatables.length; index++) {
  16595. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16596. }
  16597. }
  16598. animatable.reset();
  16599. return animatable;
  16600. };
  16601. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16602. if (speedRatio === undefined) {
  16603. speedRatio = 1.0;
  16604. }
  16605. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16606. return animatable;
  16607. };
  16608. Scene.prototype.getAnimatableByTarget = function (target) {
  16609. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16610. if (this._activeAnimatables[index].target === target) {
  16611. return this._activeAnimatables[index];
  16612. }
  16613. }
  16614. return null;
  16615. };
  16616. Object.defineProperty(Scene.prototype, "Animatables", {
  16617. get: function () {
  16618. return this._activeAnimatables;
  16619. },
  16620. enumerable: true,
  16621. configurable: true
  16622. });
  16623. /**
  16624. * Will stop the animation of the given target
  16625. * @param target - the target
  16626. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16627. * @see beginAnimation
  16628. */
  16629. Scene.prototype.stopAnimation = function (target, animationName) {
  16630. var animatable = this.getAnimatableByTarget(target);
  16631. if (animatable) {
  16632. animatable.stop(animationName);
  16633. }
  16634. };
  16635. Scene.prototype._animate = function () {
  16636. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16637. return;
  16638. }
  16639. // Getting time
  16640. var now = BABYLON.Tools.Now;
  16641. if (!this._animationTimeLast) {
  16642. if (this._pendingData.length > 0) {
  16643. return;
  16644. }
  16645. this._animationTimeLast = now;
  16646. }
  16647. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16648. this._animationTime += deltaTime;
  16649. this._animationTimeLast = now;
  16650. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16651. this._activeAnimatables[index]._animate(this._animationTime);
  16652. }
  16653. };
  16654. // Matrix
  16655. Scene.prototype.getViewMatrix = function () {
  16656. return this._viewMatrix;
  16657. };
  16658. Scene.prototype.getProjectionMatrix = function () {
  16659. return this._projectionMatrix;
  16660. };
  16661. Scene.prototype.getTransformMatrix = function () {
  16662. return this._transformMatrix;
  16663. };
  16664. Scene.prototype.setTransformMatrix = function (view, projection) {
  16665. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16666. return;
  16667. }
  16668. this._viewUpdateFlag = view.updateFlag;
  16669. this._projectionUpdateFlag = projection.updateFlag;
  16670. this._viewMatrix = view;
  16671. this._projectionMatrix = projection;
  16672. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16673. // Update frustum
  16674. if (!this._frustumPlanes) {
  16675. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16676. }
  16677. else {
  16678. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16679. }
  16680. if (this._sceneUbo.useUbo) {
  16681. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16682. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16683. this._sceneUbo.update();
  16684. }
  16685. };
  16686. Scene.prototype.getSceneUniformBuffer = function () {
  16687. return this._sceneUbo;
  16688. };
  16689. // Methods
  16690. Scene.prototype.getUniqueId = function () {
  16691. var result = this._uniqueIdCounter;
  16692. this._uniqueIdCounter++;
  16693. return result;
  16694. };
  16695. Scene.prototype.addMesh = function (newMesh) {
  16696. newMesh.uniqueId = this.getUniqueId();
  16697. var position = this.meshes.push(newMesh);
  16698. //notify the collision coordinator
  16699. if (this.collisionCoordinator) {
  16700. this.collisionCoordinator.onMeshAdded(newMesh);
  16701. }
  16702. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16703. };
  16704. Scene.prototype.removeMesh = function (toRemove) {
  16705. var index = this.meshes.indexOf(toRemove);
  16706. if (index !== -1) {
  16707. // Remove from the scene if mesh found
  16708. this.meshes.splice(index, 1);
  16709. }
  16710. //notify the collision coordinator
  16711. if (this.collisionCoordinator) {
  16712. this.collisionCoordinator.onMeshRemoved(toRemove);
  16713. }
  16714. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16715. return index;
  16716. };
  16717. Scene.prototype.removeSkeleton = function (toRemove) {
  16718. var index = this.skeletons.indexOf(toRemove);
  16719. if (index !== -1) {
  16720. // Remove from the scene if found
  16721. this.skeletons.splice(index, 1);
  16722. }
  16723. return index;
  16724. };
  16725. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16726. var index = this.morphTargetManagers.indexOf(toRemove);
  16727. if (index !== -1) {
  16728. // Remove from the scene if found
  16729. this.morphTargetManagers.splice(index, 1);
  16730. }
  16731. return index;
  16732. };
  16733. Scene.prototype.removeLight = function (toRemove) {
  16734. var index = this.lights.indexOf(toRemove);
  16735. if (index !== -1) {
  16736. // Remove from the scene if mesh found
  16737. this.lights.splice(index, 1);
  16738. this.sortLightsByPriority();
  16739. }
  16740. this.onLightRemovedObservable.notifyObservers(toRemove);
  16741. return index;
  16742. };
  16743. Scene.prototype.removeCamera = function (toRemove) {
  16744. var index = this.cameras.indexOf(toRemove);
  16745. if (index !== -1) {
  16746. // Remove from the scene if mesh found
  16747. this.cameras.splice(index, 1);
  16748. }
  16749. // Remove from activeCameras
  16750. var index2 = this.activeCameras.indexOf(toRemove);
  16751. if (index2 !== -1) {
  16752. // Remove from the scene if mesh found
  16753. this.activeCameras.splice(index2, 1);
  16754. }
  16755. // Reset the activeCamera
  16756. if (this.activeCamera === toRemove) {
  16757. if (this.cameras.length > 0) {
  16758. this.activeCamera = this.cameras[0];
  16759. }
  16760. else {
  16761. this.activeCamera = null;
  16762. }
  16763. }
  16764. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16765. return index;
  16766. };
  16767. Scene.prototype.addLight = function (newLight) {
  16768. newLight.uniqueId = this.getUniqueId();
  16769. this.lights.push(newLight);
  16770. this.sortLightsByPriority();
  16771. this.onNewLightAddedObservable.notifyObservers(newLight);
  16772. };
  16773. Scene.prototype.sortLightsByPriority = function () {
  16774. if (this.requireLightSorting) {
  16775. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16776. }
  16777. };
  16778. Scene.prototype.addCamera = function (newCamera) {
  16779. newCamera.uniqueId = this.getUniqueId();
  16780. var position = this.cameras.push(newCamera);
  16781. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16782. };
  16783. /**
  16784. * Switch active camera
  16785. * @param {Camera} newCamera - new active camera
  16786. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16787. */
  16788. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16789. if (attachControl === void 0) { attachControl = true; }
  16790. var canvas = this._engine.getRenderingCanvas();
  16791. this.activeCamera.detachControl(canvas);
  16792. this.activeCamera = newCamera;
  16793. if (attachControl) {
  16794. newCamera.attachControl(canvas);
  16795. }
  16796. };
  16797. /**
  16798. * sets the active camera of the scene using its ID
  16799. * @param {string} id - the camera's ID
  16800. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16801. * @see activeCamera
  16802. */
  16803. Scene.prototype.setActiveCameraByID = function (id) {
  16804. var camera = this.getCameraByID(id);
  16805. if (camera) {
  16806. this.activeCamera = camera;
  16807. return camera;
  16808. }
  16809. return null;
  16810. };
  16811. /**
  16812. * sets the active camera of the scene using its name
  16813. * @param {string} name - the camera's name
  16814. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16815. * @see activeCamera
  16816. */
  16817. Scene.prototype.setActiveCameraByName = function (name) {
  16818. var camera = this.getCameraByName(name);
  16819. if (camera) {
  16820. this.activeCamera = camera;
  16821. return camera;
  16822. }
  16823. return null;
  16824. };
  16825. /**
  16826. * get a material using its id
  16827. * @param {string} the material's ID
  16828. * @return {BABYLON.Material|null} the material or null if none found.
  16829. */
  16830. Scene.prototype.getMaterialByID = function (id) {
  16831. for (var index = 0; index < this.materials.length; index++) {
  16832. if (this.materials[index].id === id) {
  16833. return this.materials[index];
  16834. }
  16835. }
  16836. return null;
  16837. };
  16838. /**
  16839. * get a material using its name
  16840. * @param {string} the material's name
  16841. * @return {BABYLON.Material|null} the material or null if none found.
  16842. */
  16843. Scene.prototype.getMaterialByName = function (name) {
  16844. for (var index = 0; index < this.materials.length; index++) {
  16845. if (this.materials[index].name === name) {
  16846. return this.materials[index];
  16847. }
  16848. }
  16849. return null;
  16850. };
  16851. Scene.prototype.getLensFlareSystemByName = function (name) {
  16852. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16853. if (this.lensFlareSystems[index].name === name) {
  16854. return this.lensFlareSystems[index];
  16855. }
  16856. }
  16857. return null;
  16858. };
  16859. Scene.prototype.getLensFlareSystemByID = function (id) {
  16860. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16861. if (this.lensFlareSystems[index].id === id) {
  16862. return this.lensFlareSystems[index];
  16863. }
  16864. }
  16865. return null;
  16866. };
  16867. Scene.prototype.getCameraByID = function (id) {
  16868. for (var index = 0; index < this.cameras.length; index++) {
  16869. if (this.cameras[index].id === id) {
  16870. return this.cameras[index];
  16871. }
  16872. }
  16873. return null;
  16874. };
  16875. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16876. for (var index = 0; index < this.cameras.length; index++) {
  16877. if (this.cameras[index].uniqueId === uniqueId) {
  16878. return this.cameras[index];
  16879. }
  16880. }
  16881. return null;
  16882. };
  16883. /**
  16884. * get a camera using its name
  16885. * @param {string} the camera's name
  16886. * @return {BABYLON.Camera|null} the camera or null if none found.
  16887. */
  16888. Scene.prototype.getCameraByName = function (name) {
  16889. for (var index = 0; index < this.cameras.length; index++) {
  16890. if (this.cameras[index].name === name) {
  16891. return this.cameras[index];
  16892. }
  16893. }
  16894. return null;
  16895. };
  16896. /**
  16897. * get a bone using its id
  16898. * @param {string} the bone's id
  16899. * @return {BABYLON.Bone|null} the bone or null if not found
  16900. */
  16901. Scene.prototype.getBoneByID = function (id) {
  16902. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16903. var skeleton = this.skeletons[skeletonIndex];
  16904. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16905. if (skeleton.bones[boneIndex].id === id) {
  16906. return skeleton.bones[boneIndex];
  16907. }
  16908. }
  16909. }
  16910. return null;
  16911. };
  16912. /**
  16913. * get a bone using its id
  16914. * @param {string} the bone's name
  16915. * @return {BABYLON.Bone|null} the bone or null if not found
  16916. */
  16917. Scene.prototype.getBoneByName = function (name) {
  16918. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16919. var skeleton = this.skeletons[skeletonIndex];
  16920. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16921. if (skeleton.bones[boneIndex].name === name) {
  16922. return skeleton.bones[boneIndex];
  16923. }
  16924. }
  16925. }
  16926. return null;
  16927. };
  16928. /**
  16929. * get a light node using its name
  16930. * @param {string} the light's name
  16931. * @return {BABYLON.Light|null} the light or null if none found.
  16932. */
  16933. Scene.prototype.getLightByName = function (name) {
  16934. for (var index = 0; index < this.lights.length; index++) {
  16935. if (this.lights[index].name === name) {
  16936. return this.lights[index];
  16937. }
  16938. }
  16939. return null;
  16940. };
  16941. /**
  16942. * get a light node using its ID
  16943. * @param {string} the light's id
  16944. * @return {BABYLON.Light|null} the light or null if none found.
  16945. */
  16946. Scene.prototype.getLightByID = function (id) {
  16947. for (var index = 0; index < this.lights.length; index++) {
  16948. if (this.lights[index].id === id) {
  16949. return this.lights[index];
  16950. }
  16951. }
  16952. return null;
  16953. };
  16954. /**
  16955. * get a light node using its scene-generated unique ID
  16956. * @param {number} the light's unique id
  16957. * @return {BABYLON.Light|null} the light or null if none found.
  16958. */
  16959. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16960. for (var index = 0; index < this.lights.length; index++) {
  16961. if (this.lights[index].uniqueId === uniqueId) {
  16962. return this.lights[index];
  16963. }
  16964. }
  16965. return null;
  16966. };
  16967. /**
  16968. * get a particle system by id
  16969. * @param id {number} the particle system id
  16970. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16971. */
  16972. Scene.prototype.getParticleSystemByID = function (id) {
  16973. for (var index = 0; index < this.particleSystems.length; index++) {
  16974. if (this.particleSystems[index].id === id) {
  16975. return this.particleSystems[index];
  16976. }
  16977. }
  16978. return null;
  16979. };
  16980. /**
  16981. * get a geometry using its ID
  16982. * @param {string} the geometry's id
  16983. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16984. */
  16985. Scene.prototype.getGeometryByID = function (id) {
  16986. for (var index = 0; index < this._geometries.length; index++) {
  16987. if (this._geometries[index].id === id) {
  16988. return this._geometries[index];
  16989. }
  16990. }
  16991. return null;
  16992. };
  16993. /**
  16994. * add a new geometry to this scene.
  16995. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16996. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16997. * @return {boolean} was the geometry added or not
  16998. */
  16999. Scene.prototype.pushGeometry = function (geometry, force) {
  17000. if (!force && this.getGeometryByID(geometry.id)) {
  17001. return false;
  17002. }
  17003. this._geometries.push(geometry);
  17004. //notify the collision coordinator
  17005. if (this.collisionCoordinator) {
  17006. this.collisionCoordinator.onGeometryAdded(geometry);
  17007. }
  17008. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17009. return true;
  17010. };
  17011. /**
  17012. * Removes an existing geometry
  17013. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17014. * @return {boolean} was the geometry removed or not
  17015. */
  17016. Scene.prototype.removeGeometry = function (geometry) {
  17017. var index = this._geometries.indexOf(geometry);
  17018. if (index > -1) {
  17019. this._geometries.splice(index, 1);
  17020. //notify the collision coordinator
  17021. if (this.collisionCoordinator) {
  17022. this.collisionCoordinator.onGeometryDeleted(geometry);
  17023. }
  17024. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17025. return true;
  17026. }
  17027. return false;
  17028. };
  17029. Scene.prototype.getGeometries = function () {
  17030. return this._geometries;
  17031. };
  17032. /**
  17033. * Get the first added mesh found of a given ID
  17034. * @param {string} id - the id to search for
  17035. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17036. */
  17037. Scene.prototype.getMeshByID = function (id) {
  17038. for (var index = 0; index < this.meshes.length; index++) {
  17039. if (this.meshes[index].id === id) {
  17040. return this.meshes[index];
  17041. }
  17042. }
  17043. return null;
  17044. };
  17045. Scene.prototype.getMeshesByID = function (id) {
  17046. return this.meshes.filter(function (m) {
  17047. return m.id === id;
  17048. });
  17049. };
  17050. /**
  17051. * Get a mesh with its auto-generated unique id
  17052. * @param {number} uniqueId - the unique id to search for
  17053. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17054. */
  17055. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17056. for (var index = 0; index < this.meshes.length; index++) {
  17057. if (this.meshes[index].uniqueId === uniqueId) {
  17058. return this.meshes[index];
  17059. }
  17060. }
  17061. return null;
  17062. };
  17063. /**
  17064. * Get a the last added mesh found of a given ID
  17065. * @param {string} id - the id to search for
  17066. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17067. */
  17068. Scene.prototype.getLastMeshByID = function (id) {
  17069. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17070. if (this.meshes[index].id === id) {
  17071. return this.meshes[index];
  17072. }
  17073. }
  17074. return null;
  17075. };
  17076. /**
  17077. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17078. * @param {string} id - the id to search for
  17079. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17080. */
  17081. Scene.prototype.getLastEntryByID = function (id) {
  17082. var index;
  17083. for (index = this.meshes.length - 1; index >= 0; index--) {
  17084. if (this.meshes[index].id === id) {
  17085. return this.meshes[index];
  17086. }
  17087. }
  17088. for (index = this.cameras.length - 1; index >= 0; index--) {
  17089. if (this.cameras[index].id === id) {
  17090. return this.cameras[index];
  17091. }
  17092. }
  17093. for (index = this.lights.length - 1; index >= 0; index--) {
  17094. if (this.lights[index].id === id) {
  17095. return this.lights[index];
  17096. }
  17097. }
  17098. return null;
  17099. };
  17100. Scene.prototype.getNodeByID = function (id) {
  17101. var mesh = this.getMeshByID(id);
  17102. if (mesh) {
  17103. return mesh;
  17104. }
  17105. var light = this.getLightByID(id);
  17106. if (light) {
  17107. return light;
  17108. }
  17109. var camera = this.getCameraByID(id);
  17110. if (camera) {
  17111. return camera;
  17112. }
  17113. var bone = this.getBoneByID(id);
  17114. return bone;
  17115. };
  17116. Scene.prototype.getNodeByName = function (name) {
  17117. var mesh = this.getMeshByName(name);
  17118. if (mesh) {
  17119. return mesh;
  17120. }
  17121. var light = this.getLightByName(name);
  17122. if (light) {
  17123. return light;
  17124. }
  17125. var camera = this.getCameraByName(name);
  17126. if (camera) {
  17127. return camera;
  17128. }
  17129. var bone = this.getBoneByName(name);
  17130. return bone;
  17131. };
  17132. Scene.prototype.getMeshByName = function (name) {
  17133. for (var index = 0; index < this.meshes.length; index++) {
  17134. if (this.meshes[index].name === name) {
  17135. return this.meshes[index];
  17136. }
  17137. }
  17138. return null;
  17139. };
  17140. Scene.prototype.getSoundByName = function (name) {
  17141. var index;
  17142. if (BABYLON.AudioEngine) {
  17143. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17144. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17145. return this.mainSoundTrack.soundCollection[index];
  17146. }
  17147. }
  17148. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17149. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17150. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17151. return this.soundTracks[sdIndex].soundCollection[index];
  17152. }
  17153. }
  17154. }
  17155. }
  17156. return null;
  17157. };
  17158. Scene.prototype.getLastSkeletonByID = function (id) {
  17159. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17160. if (this.skeletons[index].id === id) {
  17161. return this.skeletons[index];
  17162. }
  17163. }
  17164. return null;
  17165. };
  17166. Scene.prototype.getSkeletonById = function (id) {
  17167. for (var index = 0; index < this.skeletons.length; index++) {
  17168. if (this.skeletons[index].id === id) {
  17169. return this.skeletons[index];
  17170. }
  17171. }
  17172. return null;
  17173. };
  17174. Scene.prototype.getSkeletonByName = function (name) {
  17175. for (var index = 0; index < this.skeletons.length; index++) {
  17176. if (this.skeletons[index].name === name) {
  17177. return this.skeletons[index];
  17178. }
  17179. }
  17180. return null;
  17181. };
  17182. Scene.prototype.getMorphTargetManagerById = function (id) {
  17183. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17184. if (this.morphTargetManagers[index].uniqueId === id) {
  17185. return this.morphTargetManagers[index];
  17186. }
  17187. }
  17188. return null;
  17189. };
  17190. Scene.prototype.isActiveMesh = function (mesh) {
  17191. return (this._activeMeshes.indexOf(mesh) !== -1);
  17192. };
  17193. /**
  17194. * Return a the first highlight layer of the scene with a given name.
  17195. * @param name The name of the highlight layer to look for.
  17196. * @return The highlight layer if found otherwise null.
  17197. */
  17198. Scene.prototype.getHighlightLayerByName = function (name) {
  17199. for (var index = 0; index < this.highlightLayers.length; index++) {
  17200. if (this.highlightLayers[index].name === name) {
  17201. return this.highlightLayers[index];
  17202. }
  17203. }
  17204. return null;
  17205. };
  17206. Object.defineProperty(Scene.prototype, "uid", {
  17207. /**
  17208. * Return a unique id as a string which can serve as an identifier for the scene
  17209. */
  17210. get: function () {
  17211. if (!this._uid) {
  17212. this._uid = BABYLON.Tools.RandomId();
  17213. }
  17214. return this._uid;
  17215. },
  17216. enumerable: true,
  17217. configurable: true
  17218. });
  17219. /**
  17220. * Add an externaly attached data from its key.
  17221. * This method call will fail and return false, if such key already exists.
  17222. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17223. * @param key the unique key that identifies the data
  17224. * @param data the data object to associate to the key for this Engine instance
  17225. * @return true if no such key were already present and the data was added successfully, false otherwise
  17226. */
  17227. Scene.prototype.addExternalData = function (key, data) {
  17228. if (!this._externalData) {
  17229. this._externalData = new BABYLON.StringDictionary();
  17230. }
  17231. return this._externalData.add(key, data);
  17232. };
  17233. /**
  17234. * Get an externaly attached data from its key
  17235. * @param key the unique key that identifies the data
  17236. * @return the associated data, if present (can be null), or undefined if not present
  17237. */
  17238. Scene.prototype.getExternalData = function (key) {
  17239. if (!this._externalData) {
  17240. return null;
  17241. }
  17242. return this._externalData.get(key);
  17243. };
  17244. /**
  17245. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17246. * @param key the unique key that identifies the data
  17247. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17248. * @return the associated data, can be null if the factory returned null.
  17249. */
  17250. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17251. if (!this._externalData) {
  17252. this._externalData = new BABYLON.StringDictionary();
  17253. }
  17254. return this._externalData.getOrAddWithFactory(key, factory);
  17255. };
  17256. /**
  17257. * Remove an externaly attached data from the Engine instance
  17258. * @param key the unique key that identifies the data
  17259. * @return true if the data was successfully removed, false if it doesn't exist
  17260. */
  17261. Scene.prototype.removeExternalData = function (key) {
  17262. return this._externalData.remove(key);
  17263. };
  17264. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17265. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17266. var material = subMesh.getMaterial();
  17267. if (mesh.showSubMeshesBoundingBox) {
  17268. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17269. }
  17270. if (material) {
  17271. // Render targets
  17272. if (material.getRenderTargetTextures) {
  17273. if (this._processedMaterials.indexOf(material) === -1) {
  17274. this._processedMaterials.push(material);
  17275. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17276. }
  17277. }
  17278. // Dispatch
  17279. this._activeIndices.addCount(subMesh.indexCount, false);
  17280. this._renderingManager.dispatch(subMesh);
  17281. }
  17282. }
  17283. };
  17284. Scene.prototype._isInIntermediateRendering = function () {
  17285. return this._intermediateRendering;
  17286. };
  17287. Scene.prototype._evaluateActiveMeshes = function () {
  17288. this.activeCamera._activeMeshes.reset();
  17289. this._activeMeshes.reset();
  17290. this._renderingManager.reset();
  17291. this._processedMaterials.reset();
  17292. this._activeParticleSystems.reset();
  17293. this._activeSkeletons.reset();
  17294. this._softwareSkinnedMeshes.reset();
  17295. if (this._boundingBoxRenderer) {
  17296. this._boundingBoxRenderer.reset();
  17297. }
  17298. // Meshes
  17299. var meshes;
  17300. var len;
  17301. if (this._selectionOctree) {
  17302. var selection = this._selectionOctree.select(this._frustumPlanes);
  17303. meshes = selection.data;
  17304. len = selection.length;
  17305. }
  17306. else {
  17307. len = this.meshes.length;
  17308. meshes = this.meshes;
  17309. }
  17310. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17311. var mesh = meshes[meshIndex];
  17312. if (mesh.isBlocked) {
  17313. continue;
  17314. }
  17315. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17316. if (!mesh.isReady() || !mesh.isEnabled()) {
  17317. continue;
  17318. }
  17319. mesh.computeWorldMatrix();
  17320. // Intersections
  17321. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17322. this._meshesForIntersections.pushNoDuplicate(mesh);
  17323. }
  17324. // Switch to current LOD
  17325. var meshLOD = mesh.getLOD(this.activeCamera);
  17326. if (!meshLOD) {
  17327. continue;
  17328. }
  17329. mesh._preActivate();
  17330. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17331. this._activeMeshes.push(mesh);
  17332. this.activeCamera._activeMeshes.push(mesh);
  17333. mesh._activate(this._renderId);
  17334. this._activeMesh(mesh, meshLOD);
  17335. }
  17336. }
  17337. // Particle systems
  17338. this._particlesDuration.beginMonitoring();
  17339. var beforeParticlesDate = BABYLON.Tools.Now;
  17340. if (this.particlesEnabled) {
  17341. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17342. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17343. var particleSystem = this.particleSystems[particleIndex];
  17344. if (!particleSystem.isStarted()) {
  17345. continue;
  17346. }
  17347. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17348. this._activeParticleSystems.push(particleSystem);
  17349. particleSystem.animate();
  17350. this._renderingManager.dispatchParticles(particleSystem);
  17351. }
  17352. }
  17353. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17354. }
  17355. this._particlesDuration.endMonitoring(false);
  17356. };
  17357. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17358. if (mesh.skeleton && this.skeletonsEnabled) {
  17359. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17360. mesh.skeleton.prepare();
  17361. }
  17362. if (!mesh.computeBonesUsingShaders) {
  17363. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17364. }
  17365. }
  17366. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17367. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17368. }
  17369. if (mesh && mesh.subMeshes) {
  17370. // Submeshes Octrees
  17371. var len;
  17372. var subMeshes;
  17373. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17374. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17375. len = intersections.length;
  17376. subMeshes = intersections.data;
  17377. }
  17378. else {
  17379. subMeshes = mesh.subMeshes;
  17380. len = subMeshes.length;
  17381. }
  17382. for (var subIndex = 0; subIndex < len; subIndex++) {
  17383. var subMesh = subMeshes[subIndex];
  17384. this._evaluateSubMesh(subMesh, mesh);
  17385. }
  17386. }
  17387. };
  17388. Scene.prototype.updateTransformMatrix = function (force) {
  17389. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17390. };
  17391. Scene.prototype._renderForCamera = function (camera) {
  17392. var engine = this._engine;
  17393. var startTime = BABYLON.Tools.Now;
  17394. this.activeCamera = camera;
  17395. if (!this.activeCamera)
  17396. throw new Error("Active camera not set");
  17397. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17398. // Viewport
  17399. engine.setViewport(this.activeCamera.viewport);
  17400. // Camera
  17401. this.resetCachedMaterial();
  17402. this._renderId++;
  17403. this.updateTransformMatrix();
  17404. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17405. // Meshes
  17406. this._evaluateActiveMeshesDuration.beginMonitoring();
  17407. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17408. this._evaluateActiveMeshes();
  17409. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17410. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17411. // Software skinning
  17412. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17413. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17414. mesh.applySkeleton(mesh.skeleton);
  17415. }
  17416. // Render targets
  17417. this._renderTargetsDuration.beginMonitoring();
  17418. var needsRestoreFrameBuffer = false;
  17419. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17420. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17421. this._intermediateRendering = true;
  17422. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17423. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17424. var renderTarget = this._renderTargets.data[renderIndex];
  17425. if (renderTarget._shouldRender()) {
  17426. this._renderId++;
  17427. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17428. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17429. }
  17430. }
  17431. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17432. this._intermediateRendering = false;
  17433. this._renderId++;
  17434. needsRestoreFrameBuffer = true; // Restore back buffer
  17435. }
  17436. // Render HighlightLayer Texture
  17437. var stencilState = this._engine.getStencilBuffer();
  17438. var renderhighlights = false;
  17439. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17440. this._intermediateRendering = true;
  17441. for (var i = 0; i < this.highlightLayers.length; i++) {
  17442. var highlightLayer = this.highlightLayers[i];
  17443. if (highlightLayer.shouldRender() &&
  17444. (!highlightLayer.camera ||
  17445. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17446. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17447. renderhighlights = true;
  17448. var renderTarget = highlightLayer._mainTexture;
  17449. if (renderTarget._shouldRender()) {
  17450. this._renderId++;
  17451. renderTarget.render(false, false);
  17452. needsRestoreFrameBuffer = true;
  17453. }
  17454. }
  17455. }
  17456. this._intermediateRendering = false;
  17457. this._renderId++;
  17458. }
  17459. if (needsRestoreFrameBuffer) {
  17460. if (this.offscreenRenderTarget) {
  17461. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17462. }
  17463. else {
  17464. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17465. }
  17466. }
  17467. this._renderTargetsDuration.endMonitoring(false);
  17468. // Prepare Frame
  17469. this.postProcessManager._prepareFrame();
  17470. this._renderDuration.beginMonitoring();
  17471. // Backgrounds
  17472. var layerIndex;
  17473. var layer;
  17474. if (this.layers.length) {
  17475. engine.setDepthBuffer(false);
  17476. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17477. layer = this.layers[layerIndex];
  17478. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17479. layer.render();
  17480. }
  17481. }
  17482. engine.setDepthBuffer(true);
  17483. }
  17484. // Render
  17485. BABYLON.Tools.StartPerformanceCounter("Main render");
  17486. // Activate HighlightLayer stencil
  17487. if (renderhighlights) {
  17488. this._engine.setStencilBuffer(true);
  17489. }
  17490. this._renderingManager.render(null, null, true, true);
  17491. // Restore HighlightLayer stencil
  17492. if (renderhighlights) {
  17493. this._engine.setStencilBuffer(stencilState);
  17494. }
  17495. BABYLON.Tools.EndPerformanceCounter("Main render");
  17496. // Bounding boxes
  17497. if (this._boundingBoxRenderer) {
  17498. this._boundingBoxRenderer.render();
  17499. }
  17500. // Lens flares
  17501. if (this.lensFlaresEnabled) {
  17502. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17503. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17504. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17505. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17506. lensFlareSystem.render();
  17507. }
  17508. }
  17509. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17510. }
  17511. // Foregrounds
  17512. if (this.layers.length) {
  17513. engine.setDepthBuffer(false);
  17514. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17515. layer = this.layers[layerIndex];
  17516. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17517. layer.render();
  17518. }
  17519. }
  17520. engine.setDepthBuffer(true);
  17521. }
  17522. // Highlight Layer
  17523. if (renderhighlights) {
  17524. engine.setDepthBuffer(false);
  17525. for (var i = 0; i < this.highlightLayers.length; i++) {
  17526. if (this.highlightLayers[i].shouldRender()) {
  17527. this.highlightLayers[i].render();
  17528. }
  17529. }
  17530. engine.setDepthBuffer(true);
  17531. }
  17532. this._renderDuration.endMonitoring(false);
  17533. // Finalize frame
  17534. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17535. // Update camera
  17536. this.activeCamera._updateFromScene();
  17537. // Reset some special arrays
  17538. this._renderTargets.reset();
  17539. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17540. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17541. };
  17542. Scene.prototype._processSubCameras = function (camera) {
  17543. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17544. this._renderForCamera(camera);
  17545. return;
  17546. }
  17547. // rig cameras
  17548. for (var index = 0; index < camera._rigCameras.length; index++) {
  17549. this._renderForCamera(camera._rigCameras[index]);
  17550. }
  17551. this.activeCamera = camera;
  17552. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17553. // Update camera
  17554. this.activeCamera._updateFromScene();
  17555. };
  17556. Scene.prototype._checkIntersections = function () {
  17557. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17558. var sourceMesh = this._meshesForIntersections.data[index];
  17559. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17560. var action = sourceMesh.actionManager.actions[actionIndex];
  17561. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17562. var parameters = action.getTriggerParameter();
  17563. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17564. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17565. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17566. if (areIntersecting && currentIntersectionInProgress === -1) {
  17567. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17568. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17569. sourceMesh._intersectionsInProgress.push(otherMesh);
  17570. }
  17571. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17572. sourceMesh._intersectionsInProgress.push(otherMesh);
  17573. }
  17574. }
  17575. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17576. //They intersected, and now they don't.
  17577. //is this trigger an exit trigger? execute an event.
  17578. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17579. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17580. }
  17581. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17582. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17583. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17584. }
  17585. }
  17586. }
  17587. }
  17588. }
  17589. };
  17590. Scene.prototype.render = function () {
  17591. if (this.isDisposed) {
  17592. return;
  17593. }
  17594. this._lastFrameDuration.beginMonitoring();
  17595. this._particlesDuration.fetchNewFrame();
  17596. this._spritesDuration.fetchNewFrame();
  17597. this._activeParticles.fetchNewFrame();
  17598. this._renderDuration.fetchNewFrame();
  17599. this._renderTargetsDuration.fetchNewFrame();
  17600. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17601. this._totalVertices.fetchNewFrame();
  17602. this._activeIndices.fetchNewFrame();
  17603. this._activeBones.fetchNewFrame();
  17604. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17605. this._meshesForIntersections.reset();
  17606. this.resetCachedMaterial();
  17607. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17608. // Actions
  17609. if (this.actionManager) {
  17610. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17611. }
  17612. //Simplification Queue
  17613. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17614. this.simplificationQueue.executeNext();
  17615. }
  17616. // Animations
  17617. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17618. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17619. this._animate();
  17620. // Physics
  17621. if (this._physicsEngine) {
  17622. BABYLON.Tools.StartPerformanceCounter("Physics");
  17623. this._physicsEngine._step(deltaTime / 1000.0);
  17624. BABYLON.Tools.EndPerformanceCounter("Physics");
  17625. }
  17626. // Before render
  17627. this.onBeforeRenderObservable.notifyObservers(this);
  17628. // Customs render targets
  17629. this._renderTargetsDuration.beginMonitoring();
  17630. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17631. var engine = this.getEngine();
  17632. var currentActiveCamera = this.activeCamera;
  17633. if (this.renderTargetsEnabled) {
  17634. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17635. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17636. var renderTarget = this.customRenderTargets[customIndex];
  17637. if (renderTarget._shouldRender()) {
  17638. this._renderId++;
  17639. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17640. if (!this.activeCamera)
  17641. throw new Error("Active camera not set");
  17642. // Viewport
  17643. engine.setViewport(this.activeCamera.viewport);
  17644. // Camera
  17645. this.updateTransformMatrix();
  17646. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17647. }
  17648. }
  17649. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17650. this._renderId++;
  17651. }
  17652. if (this.offscreenRenderTarget) {
  17653. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17654. }
  17655. else {
  17656. // Restore back buffer
  17657. if (this.customRenderTargets.length > 0) {
  17658. engine.restoreDefaultFramebuffer();
  17659. }
  17660. }
  17661. this._renderTargetsDuration.endMonitoring();
  17662. this.activeCamera = currentActiveCamera;
  17663. // Procedural textures
  17664. if (this.proceduralTexturesEnabled) {
  17665. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17666. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17667. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17668. if (proceduralTexture._shouldRender()) {
  17669. proceduralTexture.render();
  17670. }
  17671. }
  17672. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17673. }
  17674. // Clear
  17675. if (this.autoClearDepthAndStencil || this.autoClear) {
  17676. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17677. }
  17678. // Shadows
  17679. if (this.shadowsEnabled) {
  17680. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17681. var light = this.lights[lightIndex];
  17682. var shadowGenerator = light.getShadowGenerator();
  17683. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17684. var shadowMap = shadowGenerator.getShadowMap();
  17685. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17686. this._renderTargets.push(shadowMap);
  17687. }
  17688. }
  17689. }
  17690. }
  17691. // Depth renderer
  17692. if (this._depthRenderer) {
  17693. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17694. }
  17695. // Geometry renderer
  17696. if (this._geometryBufferRenderer) {
  17697. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17698. }
  17699. // RenderPipeline
  17700. if (this._postProcessRenderPipelineManager) {
  17701. this._postProcessRenderPipelineManager.update();
  17702. }
  17703. // Multi-cameras?
  17704. if (this.activeCameras.length > 0) {
  17705. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17706. if (cameraIndex > 0) {
  17707. this._engine.clear(null, false, true, true);
  17708. }
  17709. this._processSubCameras(this.activeCameras[cameraIndex]);
  17710. }
  17711. }
  17712. else {
  17713. if (!this.activeCamera) {
  17714. throw new Error("No camera defined");
  17715. }
  17716. this._processSubCameras(this.activeCamera);
  17717. }
  17718. // Intersection checks
  17719. this._checkIntersections();
  17720. // Update the audio listener attached to the camera
  17721. if (BABYLON.AudioEngine) {
  17722. this._updateAudioParameters();
  17723. }
  17724. // After render
  17725. if (this.afterRender) {
  17726. this.afterRender();
  17727. }
  17728. this.onAfterRenderObservable.notifyObservers(this);
  17729. // Cleaning
  17730. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17731. this._toBeDisposed.data[index].dispose();
  17732. this._toBeDisposed[index] = null;
  17733. }
  17734. this._toBeDisposed.reset();
  17735. if (this.dumpNextRenderTargets) {
  17736. this.dumpNextRenderTargets = false;
  17737. }
  17738. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17739. this._lastFrameDuration.endMonitoring();
  17740. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17741. this._totalLightsCounter.addCount(this.lights.length, true);
  17742. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17743. this._totalTexturesCounter.addCount(this.textures.length, true);
  17744. this._activeBones.addCount(0, true);
  17745. this._activeIndices.addCount(0, true);
  17746. this._activeParticles.addCount(0, true);
  17747. };
  17748. Scene.prototype._updateAudioParameters = function () {
  17749. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17750. return;
  17751. }
  17752. var listeningCamera;
  17753. var audioEngine = BABYLON.Engine.audioEngine;
  17754. if (this.activeCameras.length > 0) {
  17755. listeningCamera = this.activeCameras[0];
  17756. }
  17757. else {
  17758. listeningCamera = this.activeCamera;
  17759. }
  17760. if (listeningCamera && audioEngine.canUseWebAudio) {
  17761. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17762. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17763. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17764. cameraDirection.normalize();
  17765. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17766. var i;
  17767. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17768. var sound = this.mainSoundTrack.soundCollection[i];
  17769. if (sound.useCustomAttenuation) {
  17770. sound.updateDistanceFromListener();
  17771. }
  17772. }
  17773. for (i = 0; i < this.soundTracks.length; i++) {
  17774. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17775. sound = this.soundTracks[i].soundCollection[j];
  17776. if (sound.useCustomAttenuation) {
  17777. sound.updateDistanceFromListener();
  17778. }
  17779. }
  17780. }
  17781. }
  17782. };
  17783. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17784. // Audio
  17785. get: function () {
  17786. return this._audioEnabled;
  17787. },
  17788. set: function (value) {
  17789. this._audioEnabled = value;
  17790. if (BABYLON.AudioEngine) {
  17791. if (this._audioEnabled) {
  17792. this._enableAudio();
  17793. }
  17794. else {
  17795. this._disableAudio();
  17796. }
  17797. }
  17798. },
  17799. enumerable: true,
  17800. configurable: true
  17801. });
  17802. Scene.prototype._disableAudio = function () {
  17803. var i;
  17804. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17805. this.mainSoundTrack.soundCollection[i].pause();
  17806. }
  17807. for (i = 0; i < this.soundTracks.length; i++) {
  17808. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17809. this.soundTracks[i].soundCollection[j].pause();
  17810. }
  17811. }
  17812. };
  17813. Scene.prototype._enableAudio = function () {
  17814. var i;
  17815. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17816. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17817. this.mainSoundTrack.soundCollection[i].play();
  17818. }
  17819. }
  17820. for (i = 0; i < this.soundTracks.length; i++) {
  17821. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17822. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17823. this.soundTracks[i].soundCollection[j].play();
  17824. }
  17825. }
  17826. }
  17827. };
  17828. Object.defineProperty(Scene.prototype, "headphone", {
  17829. get: function () {
  17830. return this._headphone;
  17831. },
  17832. set: function (value) {
  17833. this._headphone = value;
  17834. if (BABYLON.AudioEngine) {
  17835. if (this._headphone) {
  17836. this._switchAudioModeForHeadphones();
  17837. }
  17838. else {
  17839. this._switchAudioModeForNormalSpeakers();
  17840. }
  17841. }
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Scene.prototype._switchAudioModeForHeadphones = function () {
  17847. this.mainSoundTrack.switchPanningModelToHRTF();
  17848. for (var i = 0; i < this.soundTracks.length; i++) {
  17849. this.soundTracks[i].switchPanningModelToHRTF();
  17850. }
  17851. };
  17852. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17853. this.mainSoundTrack.switchPanningModelToEqualPower();
  17854. for (var i = 0; i < this.soundTracks.length; i++) {
  17855. this.soundTracks[i].switchPanningModelToEqualPower();
  17856. }
  17857. };
  17858. Scene.prototype.enableDepthRenderer = function () {
  17859. if (this._depthRenderer) {
  17860. return this._depthRenderer;
  17861. }
  17862. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17863. return this._depthRenderer;
  17864. };
  17865. Scene.prototype.disableDepthRenderer = function () {
  17866. if (!this._depthRenderer) {
  17867. return;
  17868. }
  17869. this._depthRenderer.dispose();
  17870. this._depthRenderer = null;
  17871. };
  17872. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17873. if (ratio === void 0) { ratio = 1; }
  17874. if (this._geometryBufferRenderer) {
  17875. return this._geometryBufferRenderer;
  17876. }
  17877. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17878. if (!this._geometryBufferRenderer.isSupported) {
  17879. this._geometryBufferRenderer = null;
  17880. }
  17881. return this._geometryBufferRenderer;
  17882. };
  17883. Scene.prototype.disableGeometryBufferRenderer = function () {
  17884. if (!this._geometryBufferRenderer) {
  17885. return;
  17886. }
  17887. this._geometryBufferRenderer.dispose();
  17888. this._geometryBufferRenderer = null;
  17889. };
  17890. Scene.prototype.freezeMaterials = function () {
  17891. for (var i = 0; i < this.materials.length; i++) {
  17892. this.materials[i].freeze();
  17893. }
  17894. };
  17895. Scene.prototype.unfreezeMaterials = function () {
  17896. for (var i = 0; i < this.materials.length; i++) {
  17897. this.materials[i].unfreeze();
  17898. }
  17899. };
  17900. Scene.prototype.dispose = function () {
  17901. this.beforeRender = null;
  17902. this.afterRender = null;
  17903. this.skeletons = [];
  17904. this.morphTargetManagers = [];
  17905. this.importedMeshesFiles = new Array();
  17906. if (this._depthRenderer) {
  17907. this._depthRenderer.dispose();
  17908. }
  17909. // Smart arrays
  17910. if (this.activeCamera) {
  17911. this.activeCamera._activeMeshes.dispose();
  17912. this.activeCamera = null;
  17913. }
  17914. this._activeMeshes.dispose();
  17915. this._renderingManager.dispose();
  17916. this._processedMaterials.dispose();
  17917. this._activeParticleSystems.dispose();
  17918. this._activeSkeletons.dispose();
  17919. this._softwareSkinnedMeshes.dispose();
  17920. if (this._boundingBoxRenderer) {
  17921. this._boundingBoxRenderer.dispose();
  17922. }
  17923. this._meshesForIntersections.dispose();
  17924. this._toBeDisposed.dispose();
  17925. // Debug layer
  17926. if (this._debugLayer) {
  17927. this._debugLayer.hide();
  17928. }
  17929. // Events
  17930. this.onDisposeObservable.notifyObservers(this);
  17931. this.onDisposeObservable.clear();
  17932. this.onBeforeRenderObservable.clear();
  17933. this.onAfterRenderObservable.clear();
  17934. this.detachControl();
  17935. // Release sounds & sounds tracks
  17936. if (BABYLON.AudioEngine) {
  17937. this.disposeSounds();
  17938. }
  17939. // Detach cameras
  17940. var canvas = this._engine.getRenderingCanvas();
  17941. var index;
  17942. for (index = 0; index < this.cameras.length; index++) {
  17943. this.cameras[index].detachControl(canvas);
  17944. }
  17945. // Release lights
  17946. while (this.lights.length) {
  17947. this.lights[0].dispose();
  17948. }
  17949. // Release meshes
  17950. while (this.meshes.length) {
  17951. this.meshes[0].dispose(true);
  17952. }
  17953. // Release cameras
  17954. while (this.cameras.length) {
  17955. this.cameras[0].dispose();
  17956. }
  17957. // Release materials
  17958. while (this.materials.length) {
  17959. this.materials[0].dispose();
  17960. }
  17961. // Release particles
  17962. while (this.particleSystems.length) {
  17963. this.particleSystems[0].dispose();
  17964. }
  17965. // Release sprites
  17966. while (this.spriteManagers.length) {
  17967. this.spriteManagers[0].dispose();
  17968. }
  17969. // Release layers
  17970. while (this.layers.length) {
  17971. this.layers[0].dispose();
  17972. }
  17973. while (this.highlightLayers.length) {
  17974. this.highlightLayers[0].dispose();
  17975. }
  17976. // Release textures
  17977. while (this.textures.length) {
  17978. this.textures[0].dispose();
  17979. }
  17980. // Release UBO
  17981. this._sceneUbo.dispose();
  17982. // Post-processes
  17983. this.postProcessManager.dispose();
  17984. // Physics
  17985. if (this._physicsEngine) {
  17986. this.disablePhysicsEngine();
  17987. }
  17988. // Remove from engine
  17989. index = this._engine.scenes.indexOf(this);
  17990. if (index > -1) {
  17991. this._engine.scenes.splice(index, 1);
  17992. }
  17993. this._engine.wipeCaches();
  17994. this._engine = null;
  17995. };
  17996. Object.defineProperty(Scene.prototype, "isDisposed", {
  17997. get: function () {
  17998. return !this._engine;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. // Release sounds & sounds tracks
  18004. Scene.prototype.disposeSounds = function () {
  18005. this.mainSoundTrack.dispose();
  18006. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18007. this.soundTracks[scIndex].dispose();
  18008. }
  18009. };
  18010. // Octrees
  18011. Scene.prototype.getWorldExtends = function () {
  18012. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18013. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18014. for (var index = 0; index < this.meshes.length; index++) {
  18015. var mesh = this.meshes[index];
  18016. mesh.computeWorldMatrix(true);
  18017. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18018. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18019. BABYLON.Tools.CheckExtends(minBox, min, max);
  18020. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18021. }
  18022. return {
  18023. min: min,
  18024. max: max
  18025. };
  18026. };
  18027. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18028. if (maxCapacity === void 0) { maxCapacity = 64; }
  18029. if (maxDepth === void 0) { maxDepth = 2; }
  18030. if (!this._selectionOctree) {
  18031. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18032. }
  18033. var worldExtends = this.getWorldExtends();
  18034. // Update octree
  18035. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18036. return this._selectionOctree;
  18037. };
  18038. // Picking
  18039. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18040. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18041. var engine = this._engine;
  18042. if (!camera) {
  18043. if (!this.activeCamera)
  18044. throw new Error("Active camera not set");
  18045. camera = this.activeCamera;
  18046. }
  18047. var cameraViewport = camera.viewport;
  18048. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18049. // Moving coordinates to local viewport world
  18050. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18051. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18052. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18053. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18054. };
  18055. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18056. if (!BABYLON.PickingInfo) {
  18057. return null;
  18058. }
  18059. var engine = this._engine;
  18060. if (!camera) {
  18061. if (!this.activeCamera)
  18062. throw new Error("Active camera not set");
  18063. camera = this.activeCamera;
  18064. }
  18065. var cameraViewport = camera.viewport;
  18066. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18067. var identity = BABYLON.Matrix.Identity();
  18068. // Moving coordinates to local viewport world
  18069. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18070. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18071. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18072. };
  18073. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18074. if (!BABYLON.PickingInfo) {
  18075. return null;
  18076. }
  18077. var pickingInfo = null;
  18078. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18079. var mesh = this.meshes[meshIndex];
  18080. if (predicate) {
  18081. if (!predicate(mesh)) {
  18082. continue;
  18083. }
  18084. }
  18085. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18086. continue;
  18087. }
  18088. var world = mesh.getWorldMatrix();
  18089. var ray = rayFunction(world);
  18090. var result = mesh.intersects(ray, fastCheck);
  18091. if (!result || !result.hit)
  18092. continue;
  18093. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18094. continue;
  18095. pickingInfo = result;
  18096. if (fastCheck) {
  18097. break;
  18098. }
  18099. }
  18100. return pickingInfo || new BABYLON.PickingInfo();
  18101. };
  18102. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18103. if (!BABYLON.PickingInfo) {
  18104. return null;
  18105. }
  18106. var pickingInfos = new Array();
  18107. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18108. var mesh = this.meshes[meshIndex];
  18109. if (predicate) {
  18110. if (!predicate(mesh)) {
  18111. continue;
  18112. }
  18113. }
  18114. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18115. continue;
  18116. }
  18117. var world = mesh.getWorldMatrix();
  18118. var ray = rayFunction(world);
  18119. var result = mesh.intersects(ray, false);
  18120. if (!result || !result.hit)
  18121. continue;
  18122. pickingInfos.push(result);
  18123. }
  18124. return pickingInfos;
  18125. };
  18126. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18127. if (!BABYLON.PickingInfo) {
  18128. return null;
  18129. }
  18130. var pickingInfo = null;
  18131. camera = camera || this.activeCamera;
  18132. if (this.spriteManagers.length > 0) {
  18133. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18134. var spriteManager = this.spriteManagers[spriteIndex];
  18135. if (!spriteManager.isPickable) {
  18136. continue;
  18137. }
  18138. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18139. if (!result || !result.hit)
  18140. continue;
  18141. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18142. continue;
  18143. pickingInfo = result;
  18144. if (fastCheck) {
  18145. break;
  18146. }
  18147. }
  18148. }
  18149. return pickingInfo || new BABYLON.PickingInfo();
  18150. };
  18151. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18152. /// <param name="x">X position on screen</param>
  18153. /// <param name="y">Y position on screen</param>
  18154. /// <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>
  18155. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18156. /// <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>
  18157. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18158. var _this = this;
  18159. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18160. };
  18161. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18162. /// <param name="x">X position on screen</param>
  18163. /// <param name="y">Y position on screen</param>
  18164. /// <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>
  18165. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18166. /// <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>
  18167. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18168. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18169. };
  18170. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18171. var _this = this;
  18172. return this._internalPick(function (world) {
  18173. if (!_this._pickWithRayInverseMatrix) {
  18174. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18175. }
  18176. world.invertToRef(_this._pickWithRayInverseMatrix);
  18177. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18178. }, predicate, fastCheck);
  18179. };
  18180. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18181. /// <param name="x">X position on screen</param>
  18182. /// <param name="y">Y position on screen</param>
  18183. /// <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>
  18184. /// <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>
  18185. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18186. var _this = this;
  18187. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18188. };
  18189. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18190. /// <param name="ray">Ray to use</param>
  18191. /// <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>
  18192. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18193. var _this = this;
  18194. return this._internalMultiPick(function (world) {
  18195. if (!_this._pickWithRayInverseMatrix) {
  18196. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18197. }
  18198. world.invertToRef(_this._pickWithRayInverseMatrix);
  18199. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18200. }, predicate);
  18201. };
  18202. Scene.prototype.setPointerOverMesh = function (mesh) {
  18203. if (this._pointerOverMesh === mesh) {
  18204. return;
  18205. }
  18206. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18207. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18208. }
  18209. this._pointerOverMesh = mesh;
  18210. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18211. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18212. }
  18213. };
  18214. Scene.prototype.getPointerOverMesh = function () {
  18215. return this._pointerOverMesh;
  18216. };
  18217. Scene.prototype.setPointerOverSprite = function (sprite) {
  18218. if (this._pointerOverSprite === sprite) {
  18219. return;
  18220. }
  18221. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18222. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18223. }
  18224. this._pointerOverSprite = sprite;
  18225. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18226. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18227. }
  18228. };
  18229. Scene.prototype.getPointerOverSprite = function () {
  18230. return this._pointerOverSprite;
  18231. };
  18232. // Physics
  18233. Scene.prototype.getPhysicsEngine = function () {
  18234. return this._physicsEngine;
  18235. };
  18236. /**
  18237. * Enables physics to the current scene
  18238. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18239. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18240. * @return {boolean} was the physics engine initialized
  18241. */
  18242. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18243. if (this._physicsEngine) {
  18244. return true;
  18245. }
  18246. try {
  18247. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18248. return true;
  18249. }
  18250. catch (e) {
  18251. BABYLON.Tools.Error(e.message);
  18252. return false;
  18253. }
  18254. };
  18255. Scene.prototype.disablePhysicsEngine = function () {
  18256. if (!this._physicsEngine) {
  18257. return;
  18258. }
  18259. this._physicsEngine.dispose();
  18260. this._physicsEngine = undefined;
  18261. };
  18262. Scene.prototype.isPhysicsEnabled = function () {
  18263. return this._physicsEngine !== undefined;
  18264. };
  18265. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18266. var mesh = compound.parts[0].mesh;
  18267. mesh.physicsImpostor.dispose();
  18268. mesh.physicsImpostor = null;
  18269. };
  18270. // Misc.
  18271. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18272. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18273. // Light
  18274. if (this.lights.length === 0) {
  18275. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18276. }
  18277. // Camera
  18278. if (!this.activeCamera) {
  18279. var worldExtends = this.getWorldExtends();
  18280. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18281. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18282. var camera;
  18283. var radius = worldSize.length() * 1.5;
  18284. if (createArcRotateCamera) {
  18285. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18286. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18287. arcRotateCamera.wheelPrecision = 100 / radius;
  18288. camera = arcRotateCamera;
  18289. }
  18290. else {
  18291. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18292. freeCamera.setTarget(worldCenter);
  18293. camera = freeCamera;
  18294. }
  18295. camera.minZ = radius * 0.01;
  18296. camera.maxZ = radius * 100;
  18297. camera.speed = radius * 0.2;
  18298. this.activeCamera = camera;
  18299. }
  18300. };
  18301. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18302. if (pbr === void 0) { pbr = false; }
  18303. if (environmentTexture) {
  18304. this.environmentTexture = environmentTexture;
  18305. }
  18306. if (!this.environmentTexture) {
  18307. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18308. return;
  18309. }
  18310. if (!this.environmentTexture) {
  18311. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18312. return;
  18313. }
  18314. // Skybox
  18315. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18316. if (pbr) {
  18317. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18318. hdrSkyboxMaterial.backFaceCulling = false;
  18319. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18320. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18321. hdrSkyboxMaterial.microSurface = 1.0;
  18322. hdrSkyboxMaterial.disableLighting = true;
  18323. hdrSkybox.infiniteDistance = true;
  18324. hdrSkybox.material = hdrSkyboxMaterial;
  18325. }
  18326. else {
  18327. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18328. skyboxMaterial.backFaceCulling = false;
  18329. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18330. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18331. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18332. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18333. skyboxMaterial.disableLighting = true;
  18334. hdrSkybox.infiniteDistance = true;
  18335. hdrSkybox.material = skyboxMaterial;
  18336. }
  18337. return hdrSkybox;
  18338. };
  18339. // Tags
  18340. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18341. if (tagsQuery === undefined) {
  18342. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18343. return list;
  18344. }
  18345. var listByTags = [];
  18346. forEach = forEach || (function (item) { return; });
  18347. for (var i in list) {
  18348. var item = list[i];
  18349. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18350. listByTags.push(item);
  18351. forEach(item);
  18352. }
  18353. }
  18354. return listByTags;
  18355. };
  18356. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18357. return this._getByTags(this.meshes, tagsQuery, forEach);
  18358. };
  18359. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18360. return this._getByTags(this.cameras, tagsQuery, forEach);
  18361. };
  18362. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18363. return this._getByTags(this.lights, tagsQuery, forEach);
  18364. };
  18365. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18366. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18367. };
  18368. /**
  18369. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18370. * This allowed control for front to back rendering or reversly depending of the special needs.
  18371. *
  18372. * @param renderingGroupId The rendering group id corresponding to its index
  18373. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18374. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18375. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18376. */
  18377. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18378. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18379. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18380. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18381. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18382. };
  18383. /**
  18384. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18385. *
  18386. * @param renderingGroupId The rendering group id corresponding to its index
  18387. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18388. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18389. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18390. */
  18391. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18392. if (depth === void 0) { depth = true; }
  18393. if (stencil === void 0) { stencil = true; }
  18394. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18395. };
  18396. /**
  18397. * Will flag all materials as dirty to trigger new shader compilation
  18398. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18399. */
  18400. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18401. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18402. var material = _a[_i];
  18403. if (predicate && !predicate(material)) {
  18404. continue;
  18405. }
  18406. material.markAsDirty(flag);
  18407. }
  18408. };
  18409. return Scene;
  18410. }());
  18411. // Statics
  18412. Scene._FOGMODE_NONE = 0;
  18413. Scene._FOGMODE_EXP = 1;
  18414. Scene._FOGMODE_EXP2 = 2;
  18415. Scene._FOGMODE_LINEAR = 3;
  18416. Scene.MinDeltaTime = 1.0;
  18417. Scene.MaxDeltaTime = 1000.0;
  18418. Scene.DragMovementThreshold = 10; // in pixels
  18419. Scene.LongPressDelay = 500; // in milliseconds
  18420. Scene.DoubleClickDelay = 300; // in milliseconds
  18421. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18422. BABYLON.Scene = Scene;
  18423. })(BABYLON || (BABYLON = {}));
  18424. //# sourceMappingURL=babylon.scene.js.map
  18425. var BABYLON;
  18426. (function (BABYLON) {
  18427. var Buffer = (function () {
  18428. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18429. if (engine instanceof BABYLON.Mesh) {
  18430. this._engine = engine.getScene().getEngine();
  18431. }
  18432. else {
  18433. this._engine = engine;
  18434. }
  18435. this._updatable = updatable;
  18436. this._data = data;
  18437. this._strideSize = stride;
  18438. if (!postponeInternalCreation) {
  18439. this.create();
  18440. }
  18441. this._instanced = instanced;
  18442. }
  18443. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18444. // a lot of these parameters are ignored as they are overriden by the buffer
  18445. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18446. };
  18447. // Properties
  18448. Buffer.prototype.isUpdatable = function () {
  18449. return this._updatable;
  18450. };
  18451. Buffer.prototype.getData = function () {
  18452. return this._data;
  18453. };
  18454. Buffer.prototype.getBuffer = function () {
  18455. return this._buffer;
  18456. };
  18457. Buffer.prototype.getStrideSize = function () {
  18458. return this._strideSize;
  18459. };
  18460. Buffer.prototype.getIsInstanced = function () {
  18461. return this._instanced;
  18462. };
  18463. // Methods
  18464. Buffer.prototype.create = function (data) {
  18465. if (!data && this._buffer) {
  18466. return; // nothing to do
  18467. }
  18468. data = data || this._data;
  18469. if (!this._buffer) {
  18470. if (this._updatable) {
  18471. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18472. this._data = data;
  18473. }
  18474. else {
  18475. this._buffer = this._engine.createVertexBuffer(data);
  18476. }
  18477. }
  18478. else if (this._updatable) {
  18479. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18480. this._data = data;
  18481. }
  18482. };
  18483. Buffer.prototype.update = function (data) {
  18484. this.create(data);
  18485. };
  18486. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18487. if (!this._buffer) {
  18488. return;
  18489. }
  18490. if (this._updatable) {
  18491. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18492. this._data = null;
  18493. }
  18494. };
  18495. Buffer.prototype.dispose = function () {
  18496. if (!this._buffer) {
  18497. return;
  18498. }
  18499. if (this._engine._releaseBuffer(this._buffer)) {
  18500. this._buffer = null;
  18501. }
  18502. };
  18503. return Buffer;
  18504. }());
  18505. BABYLON.Buffer = Buffer;
  18506. })(BABYLON || (BABYLON = {}));
  18507. //# sourceMappingURL=babylon.buffer.js.map
  18508. var BABYLON;
  18509. (function (BABYLON) {
  18510. var VertexBuffer = (function () {
  18511. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18512. if (!stride) {
  18513. // Deduce stride from kind
  18514. switch (kind) {
  18515. case VertexBuffer.PositionKind:
  18516. stride = 3;
  18517. break;
  18518. case VertexBuffer.NormalKind:
  18519. stride = 3;
  18520. break;
  18521. case VertexBuffer.UVKind:
  18522. case VertexBuffer.UV2Kind:
  18523. case VertexBuffer.UV3Kind:
  18524. case VertexBuffer.UV4Kind:
  18525. case VertexBuffer.UV5Kind:
  18526. case VertexBuffer.UV6Kind:
  18527. stride = 2;
  18528. break;
  18529. case VertexBuffer.TangentKind:
  18530. case VertexBuffer.ColorKind:
  18531. stride = 4;
  18532. break;
  18533. case VertexBuffer.MatricesIndicesKind:
  18534. case VertexBuffer.MatricesIndicesExtraKind:
  18535. stride = 4;
  18536. break;
  18537. case VertexBuffer.MatricesWeightsKind:
  18538. case VertexBuffer.MatricesWeightsExtraKind:
  18539. stride = 4;
  18540. break;
  18541. }
  18542. }
  18543. if (data instanceof BABYLON.Buffer) {
  18544. if (!stride) {
  18545. stride = data.getStrideSize();
  18546. }
  18547. this._buffer = data;
  18548. this._ownsBuffer = false;
  18549. }
  18550. else {
  18551. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18552. this._ownsBuffer = true;
  18553. }
  18554. this._stride = stride;
  18555. this._offset = offset ? offset : 0;
  18556. this._size = size ? size : stride;
  18557. this._kind = kind;
  18558. }
  18559. /**
  18560. * Returns the kind of the VertexBuffer (string).
  18561. */
  18562. VertexBuffer.prototype.getKind = function () {
  18563. return this._kind;
  18564. };
  18565. // Properties
  18566. /**
  18567. * Boolean : is the VertexBuffer updatable ?
  18568. */
  18569. VertexBuffer.prototype.isUpdatable = function () {
  18570. return this._buffer.isUpdatable();
  18571. };
  18572. /**
  18573. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18574. */
  18575. VertexBuffer.prototype.getData = function () {
  18576. return this._buffer.getData();
  18577. };
  18578. /**
  18579. * Returns the WebGLBuffer associated to the VertexBuffer.
  18580. */
  18581. VertexBuffer.prototype.getBuffer = function () {
  18582. return this._buffer.getBuffer();
  18583. };
  18584. /**
  18585. * Returns the stride of the VertexBuffer (integer).
  18586. */
  18587. VertexBuffer.prototype.getStrideSize = function () {
  18588. return this._stride;
  18589. };
  18590. /**
  18591. * Returns the offset (integer).
  18592. */
  18593. VertexBuffer.prototype.getOffset = function () {
  18594. return this._offset;
  18595. };
  18596. /**
  18597. * Returns the VertexBuffer total size (integer).
  18598. */
  18599. VertexBuffer.prototype.getSize = function () {
  18600. return this._size;
  18601. };
  18602. /**
  18603. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18604. */
  18605. VertexBuffer.prototype.getIsInstanced = function () {
  18606. return this._buffer.getIsInstanced();
  18607. };
  18608. // Methods
  18609. /**
  18610. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18611. * Returns the created WebGLBuffer.
  18612. */
  18613. VertexBuffer.prototype.create = function (data) {
  18614. return this._buffer.create(data);
  18615. };
  18616. /**
  18617. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18618. * Returns the updated WebGLBuffer.
  18619. */
  18620. VertexBuffer.prototype.update = function (data) {
  18621. return this._buffer.update(data);
  18622. };
  18623. /**
  18624. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18625. * Returns the directly updated WebGLBuffer.
  18626. */
  18627. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18628. return this._buffer.updateDirectly(data, offset);
  18629. };
  18630. /**
  18631. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18632. */
  18633. VertexBuffer.prototype.dispose = function () {
  18634. if (this._ownsBuffer) {
  18635. this._buffer.dispose();
  18636. }
  18637. };
  18638. Object.defineProperty(VertexBuffer, "PositionKind", {
  18639. get: function () {
  18640. return VertexBuffer._PositionKind;
  18641. },
  18642. enumerable: true,
  18643. configurable: true
  18644. });
  18645. Object.defineProperty(VertexBuffer, "NormalKind", {
  18646. get: function () {
  18647. return VertexBuffer._NormalKind;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(VertexBuffer, "TangentKind", {
  18653. get: function () {
  18654. return VertexBuffer._TangentKind;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Object.defineProperty(VertexBuffer, "UVKind", {
  18660. get: function () {
  18661. return VertexBuffer._UVKind;
  18662. },
  18663. enumerable: true,
  18664. configurable: true
  18665. });
  18666. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18667. get: function () {
  18668. return VertexBuffer._UV2Kind;
  18669. },
  18670. enumerable: true,
  18671. configurable: true
  18672. });
  18673. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18674. get: function () {
  18675. return VertexBuffer._UV3Kind;
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18681. get: function () {
  18682. return VertexBuffer._UV4Kind;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18688. get: function () {
  18689. return VertexBuffer._UV5Kind;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18695. get: function () {
  18696. return VertexBuffer._UV6Kind;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(VertexBuffer, "ColorKind", {
  18702. get: function () {
  18703. return VertexBuffer._ColorKind;
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18709. get: function () {
  18710. return VertexBuffer._MatricesIndicesKind;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18716. get: function () {
  18717. return VertexBuffer._MatricesWeightsKind;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18723. get: function () {
  18724. return VertexBuffer._MatricesIndicesExtraKind;
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18730. get: function () {
  18731. return VertexBuffer._MatricesWeightsExtraKind;
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. return VertexBuffer;
  18737. }());
  18738. // Enums
  18739. VertexBuffer._PositionKind = "position";
  18740. VertexBuffer._NormalKind = "normal";
  18741. VertexBuffer._TangentKind = "tangent";
  18742. VertexBuffer._UVKind = "uv";
  18743. VertexBuffer._UV2Kind = "uv2";
  18744. VertexBuffer._UV3Kind = "uv3";
  18745. VertexBuffer._UV4Kind = "uv4";
  18746. VertexBuffer._UV5Kind = "uv5";
  18747. VertexBuffer._UV6Kind = "uv6";
  18748. VertexBuffer._ColorKind = "color";
  18749. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18750. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18751. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18752. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18753. BABYLON.VertexBuffer = VertexBuffer;
  18754. })(BABYLON || (BABYLON = {}));
  18755. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18756. var BABYLON;
  18757. (function (BABYLON) {
  18758. var BaseTexture = (function () {
  18759. function BaseTexture(scene) {
  18760. this._hasAlpha = false;
  18761. this.getAlphaFromRGB = false;
  18762. this.level = 1;
  18763. this.coordinatesIndex = 0;
  18764. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18765. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18766. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18767. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18768. this.isCube = false;
  18769. this.isRenderTarget = false;
  18770. this.animations = new Array();
  18771. /**
  18772. * An event triggered when the texture is disposed.
  18773. * @type {BABYLON.Observable}
  18774. */
  18775. this.onDisposeObservable = new BABYLON.Observable();
  18776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18777. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18778. this._scene.textures.push(this);
  18779. this._uid = null;
  18780. }
  18781. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18782. get: function () {
  18783. return this._hasAlpha;
  18784. },
  18785. set: function (value) {
  18786. if (this._hasAlpha === value) {
  18787. return;
  18788. }
  18789. this._hasAlpha = value;
  18790. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18791. },
  18792. enumerable: true,
  18793. configurable: true
  18794. });
  18795. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18796. get: function () {
  18797. return this._coordinatesMode;
  18798. },
  18799. set: function (value) {
  18800. if (this._coordinatesMode === value) {
  18801. return;
  18802. }
  18803. this._coordinatesMode = value;
  18804. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18805. },
  18806. enumerable: true,
  18807. configurable: true
  18808. });
  18809. Object.defineProperty(BaseTexture.prototype, "uid", {
  18810. get: function () {
  18811. if (!this._uid) {
  18812. this._uid = BABYLON.Tools.RandomId();
  18813. }
  18814. return this._uid;
  18815. },
  18816. enumerable: true,
  18817. configurable: true
  18818. });
  18819. BaseTexture.prototype.toString = function () {
  18820. return this.name;
  18821. };
  18822. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18823. set: function (callback) {
  18824. if (this._onDisposeObserver) {
  18825. this.onDisposeObservable.remove(this._onDisposeObserver);
  18826. }
  18827. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18828. },
  18829. enumerable: true,
  18830. configurable: true
  18831. });
  18832. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18833. get: function () {
  18834. return true;
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. BaseTexture.prototype.getScene = function () {
  18840. return this._scene;
  18841. };
  18842. BaseTexture.prototype.getTextureMatrix = function () {
  18843. return null;
  18844. };
  18845. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18846. return null;
  18847. };
  18848. BaseTexture.prototype.getInternalTexture = function () {
  18849. return this._texture;
  18850. };
  18851. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18852. return !this.isBlocking || this.isReady();
  18853. };
  18854. BaseTexture.prototype.isReady = function () {
  18855. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18856. this.delayLoad();
  18857. return false;
  18858. }
  18859. if (this._texture) {
  18860. return this._texture.isReady;
  18861. }
  18862. return false;
  18863. };
  18864. BaseTexture.prototype.getSize = function () {
  18865. if (this._texture._width) {
  18866. return new BABYLON.Size(this._texture._width, this._texture._height);
  18867. }
  18868. if (this._texture._size) {
  18869. return new BABYLON.Size(this._texture._size, this._texture._size);
  18870. }
  18871. return BABYLON.Size.Zero();
  18872. };
  18873. BaseTexture.prototype.getBaseSize = function () {
  18874. if (!this.isReady() || !this._texture)
  18875. return BABYLON.Size.Zero();
  18876. if (this._texture._size) {
  18877. return new BABYLON.Size(this._texture._size, this._texture._size);
  18878. }
  18879. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18880. };
  18881. BaseTexture.prototype.scale = function (ratio) {
  18882. };
  18883. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18884. get: function () {
  18885. return false;
  18886. },
  18887. enumerable: true,
  18888. configurable: true
  18889. });
  18890. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18891. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18892. for (var index = 0; index < texturesCache.length; index++) {
  18893. var texturesCacheEntry = texturesCache[index];
  18894. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18895. texturesCache.splice(index, 1);
  18896. return;
  18897. }
  18898. }
  18899. };
  18900. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18901. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18902. for (var index = 0; index < texturesCache.length; index++) {
  18903. var texturesCacheEntry = texturesCache[index];
  18904. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18905. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18906. texturesCacheEntry.references++;
  18907. return texturesCacheEntry;
  18908. }
  18909. }
  18910. }
  18911. return null;
  18912. };
  18913. BaseTexture.prototype.delayLoad = function () {
  18914. };
  18915. BaseTexture.prototype.clone = function () {
  18916. return null;
  18917. };
  18918. BaseTexture.prototype.releaseInternalTexture = function () {
  18919. if (this._texture) {
  18920. this._scene.getEngine().releaseInternalTexture(this._texture);
  18921. delete this._texture;
  18922. }
  18923. };
  18924. BaseTexture.prototype.dispose = function () {
  18925. // Animations
  18926. this.getScene().stopAnimation(this);
  18927. // Remove from scene
  18928. this._scene._removePendingData(this);
  18929. var index = this._scene.textures.indexOf(this);
  18930. if (index >= 0) {
  18931. this._scene.textures.splice(index, 1);
  18932. }
  18933. if (this._texture === undefined) {
  18934. return;
  18935. }
  18936. // Release
  18937. this.releaseInternalTexture();
  18938. // Callback
  18939. this.onDisposeObservable.notifyObservers(this);
  18940. this.onDisposeObservable.clear();
  18941. };
  18942. BaseTexture.prototype.serialize = function () {
  18943. if (!this.name) {
  18944. return null;
  18945. }
  18946. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18947. // Animations
  18948. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18949. return serializationObject;
  18950. };
  18951. return BaseTexture;
  18952. }());
  18953. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18954. __decorate([
  18955. BABYLON.serialize()
  18956. ], BaseTexture.prototype, "name", void 0);
  18957. __decorate([
  18958. BABYLON.serialize("hasAlpha")
  18959. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18960. __decorate([
  18961. BABYLON.serialize()
  18962. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18963. __decorate([
  18964. BABYLON.serialize()
  18965. ], BaseTexture.prototype, "level", void 0);
  18966. __decorate([
  18967. BABYLON.serialize()
  18968. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18969. __decorate([
  18970. BABYLON.serialize("coordinatesMode")
  18971. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18972. __decorate([
  18973. BABYLON.serialize()
  18974. ], BaseTexture.prototype, "wrapU", void 0);
  18975. __decorate([
  18976. BABYLON.serialize()
  18977. ], BaseTexture.prototype, "wrapV", void 0);
  18978. __decorate([
  18979. BABYLON.serialize()
  18980. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18981. __decorate([
  18982. BABYLON.serialize()
  18983. ], BaseTexture.prototype, "isCube", void 0);
  18984. __decorate([
  18985. BABYLON.serialize()
  18986. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18987. BABYLON.BaseTexture = BaseTexture;
  18988. })(BABYLON || (BABYLON = {}));
  18989. //# sourceMappingURL=babylon.baseTexture.js.map
  18990. var BABYLON;
  18991. (function (BABYLON) {
  18992. var Texture = (function (_super) {
  18993. __extends(Texture, _super);
  18994. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18995. if (noMipmap === void 0) { noMipmap = false; }
  18996. if (invertY === void 0) { invertY = true; }
  18997. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18998. if (onLoad === void 0) { onLoad = null; }
  18999. if (onError === void 0) { onError = null; }
  19000. if (buffer === void 0) { buffer = null; }
  19001. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19002. var _this = _super.call(this, scene) || this;
  19003. _this.uOffset = 0;
  19004. _this.vOffset = 0;
  19005. _this.uScale = 1.0;
  19006. _this.vScale = 1.0;
  19007. _this.uAng = 0;
  19008. _this.vAng = 0;
  19009. _this.wAng = 0;
  19010. _this._isBlocking = true;
  19011. _this.name = url;
  19012. _this.url = url;
  19013. _this._noMipmap = noMipmap;
  19014. _this._invertY = invertY;
  19015. _this._samplingMode = samplingMode;
  19016. _this._buffer = buffer;
  19017. _this._deleteBuffer = deleteBuffer;
  19018. _this._format = format;
  19019. scene = _this.getScene();
  19020. if (!url) {
  19021. return _this;
  19022. }
  19023. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19024. var load = function () {
  19025. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19026. _this.onLoadObservable.notifyObservers(true);
  19027. }
  19028. if (onLoad) {
  19029. onLoad();
  19030. }
  19031. if (!_this.isBlocking) {
  19032. scene.resetCachedMaterial();
  19033. }
  19034. };
  19035. if (!_this._texture) {
  19036. if (!scene.useDelayedTextureLoading) {
  19037. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19038. if (deleteBuffer) {
  19039. delete _this._buffer;
  19040. }
  19041. }
  19042. else {
  19043. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19044. _this._delayedOnLoad = load;
  19045. _this._delayedOnError = onError;
  19046. }
  19047. }
  19048. else {
  19049. if (_this._texture.isReady) {
  19050. BABYLON.Tools.SetImmediate(function () { return load(); });
  19051. }
  19052. else {
  19053. _this._texture.onLoadedCallbacks.push(load);
  19054. }
  19055. }
  19056. return _this;
  19057. }
  19058. Object.defineProperty(Texture.prototype, "noMipmap", {
  19059. get: function () {
  19060. return this._noMipmap;
  19061. },
  19062. enumerable: true,
  19063. configurable: true
  19064. });
  19065. Object.defineProperty(Texture.prototype, "isBlocking", {
  19066. get: function () {
  19067. return this._isBlocking;
  19068. },
  19069. set: function (value) {
  19070. this._isBlocking = value;
  19071. },
  19072. enumerable: true,
  19073. configurable: true
  19074. });
  19075. Texture.prototype.delayLoad = function () {
  19076. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19077. return;
  19078. }
  19079. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19080. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19081. if (!this._texture) {
  19082. 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);
  19083. if (this._deleteBuffer) {
  19084. delete this._buffer;
  19085. }
  19086. }
  19087. };
  19088. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19089. if (!this._texture) {
  19090. return;
  19091. }
  19092. this._samplingMode = samplingMode;
  19093. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19094. };
  19095. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19096. x *= this.uScale;
  19097. y *= this.vScale;
  19098. x -= 0.5 * this.uScale;
  19099. y -= 0.5 * this.vScale;
  19100. z -= 0.5;
  19101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19102. t.x += 0.5 * this.uScale + this.uOffset;
  19103. t.y += 0.5 * this.vScale + this.vOffset;
  19104. t.z += 0.5;
  19105. };
  19106. Texture.prototype.getTextureMatrix = function () {
  19107. if (this.uOffset === this._cachedUOffset &&
  19108. this.vOffset === this._cachedVOffset &&
  19109. this.uScale === this._cachedUScale &&
  19110. this.vScale === this._cachedVScale &&
  19111. this.uAng === this._cachedUAng &&
  19112. this.vAng === this._cachedVAng &&
  19113. this.wAng === this._cachedWAng) {
  19114. return this._cachedTextureMatrix;
  19115. }
  19116. this._cachedUOffset = this.uOffset;
  19117. this._cachedVOffset = this.vOffset;
  19118. this._cachedUScale = this.uScale;
  19119. this._cachedVScale = this.vScale;
  19120. this._cachedUAng = this.uAng;
  19121. this._cachedVAng = this.vAng;
  19122. this._cachedWAng = this.wAng;
  19123. if (!this._cachedTextureMatrix) {
  19124. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19125. this._rowGenerationMatrix = new BABYLON.Matrix();
  19126. this._t0 = BABYLON.Vector3.Zero();
  19127. this._t1 = BABYLON.Vector3.Zero();
  19128. this._t2 = BABYLON.Vector3.Zero();
  19129. }
  19130. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19131. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19132. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19133. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19134. this._t1.subtractInPlace(this._t0);
  19135. this._t2.subtractInPlace(this._t0);
  19136. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19137. this._cachedTextureMatrix.m[0] = this._t1.x;
  19138. this._cachedTextureMatrix.m[1] = this._t1.y;
  19139. this._cachedTextureMatrix.m[2] = this._t1.z;
  19140. this._cachedTextureMatrix.m[4] = this._t2.x;
  19141. this._cachedTextureMatrix.m[5] = this._t2.y;
  19142. this._cachedTextureMatrix.m[6] = this._t2.z;
  19143. this._cachedTextureMatrix.m[8] = this._t0.x;
  19144. this._cachedTextureMatrix.m[9] = this._t0.y;
  19145. this._cachedTextureMatrix.m[10] = this._t0.z;
  19146. return this._cachedTextureMatrix;
  19147. };
  19148. Texture.prototype.getReflectionTextureMatrix = function () {
  19149. if (this.uOffset === this._cachedUOffset &&
  19150. this.vOffset === this._cachedVOffset &&
  19151. this.uScale === this._cachedUScale &&
  19152. this.vScale === this._cachedVScale &&
  19153. this.coordinatesMode === this._cachedCoordinatesMode) {
  19154. return this._cachedTextureMatrix;
  19155. }
  19156. if (!this._cachedTextureMatrix) {
  19157. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19158. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19159. }
  19160. this._cachedCoordinatesMode = this.coordinatesMode;
  19161. switch (this.coordinatesMode) {
  19162. case Texture.PLANAR_MODE:
  19163. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19164. this._cachedTextureMatrix[0] = this.uScale;
  19165. this._cachedTextureMatrix[5] = this.vScale;
  19166. this._cachedTextureMatrix[12] = this.uOffset;
  19167. this._cachedTextureMatrix[13] = this.vOffset;
  19168. break;
  19169. case Texture.PROJECTION_MODE:
  19170. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19171. this._projectionModeMatrix.m[0] = 0.5;
  19172. this._projectionModeMatrix.m[5] = -0.5;
  19173. this._projectionModeMatrix.m[10] = 0.0;
  19174. this._projectionModeMatrix.m[12] = 0.5;
  19175. this._projectionModeMatrix.m[13] = 0.5;
  19176. this._projectionModeMatrix.m[14] = 1.0;
  19177. this._projectionModeMatrix.m[15] = 1.0;
  19178. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19179. break;
  19180. default:
  19181. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19182. break;
  19183. }
  19184. return this._cachedTextureMatrix;
  19185. };
  19186. Texture.prototype.clone = function () {
  19187. var _this = this;
  19188. return BABYLON.SerializationHelper.Clone(function () {
  19189. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19190. }, this);
  19191. };
  19192. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19193. get: function () {
  19194. if (!this._onLoadObservarble) {
  19195. this._onLoadObservarble = new BABYLON.Observable();
  19196. }
  19197. return this._onLoadObservarble;
  19198. },
  19199. enumerable: true,
  19200. configurable: true
  19201. });
  19202. // Statics
  19203. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19204. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19205. if (onLoad === void 0) { onLoad = null; }
  19206. if (onError === void 0) { onError = null; }
  19207. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19208. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19209. };
  19210. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19211. if (parsedTexture.customType) {
  19212. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19213. // Update Sampling Mode
  19214. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19215. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19216. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19217. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19218. }
  19219. }
  19220. return parsedCustomTexture;
  19221. }
  19222. if (parsedTexture.isCube) {
  19223. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19224. }
  19225. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19226. return null;
  19227. }
  19228. var texture = BABYLON.SerializationHelper.Parse(function () {
  19229. if (parsedTexture.mirrorPlane) {
  19230. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19231. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19232. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19233. return mirrorTexture;
  19234. }
  19235. else if (parsedTexture.isRenderTarget) {
  19236. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19237. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19238. return renderTargetTexture;
  19239. }
  19240. else {
  19241. var texture;
  19242. if (parsedTexture.base64String) {
  19243. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19244. }
  19245. else {
  19246. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19247. }
  19248. return texture;
  19249. }
  19250. }, parsedTexture, scene);
  19251. // Update Sampling Mode
  19252. if (parsedTexture.samplingMode) {
  19253. var sampling = parsedTexture.samplingMode;
  19254. if (texture._samplingMode !== sampling) {
  19255. texture.updateSamplingMode(sampling);
  19256. }
  19257. }
  19258. // Animations
  19259. if (parsedTexture.animations) {
  19260. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19261. var parsedAnimation = parsedTexture.animations[animationIndex];
  19262. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19263. }
  19264. }
  19265. return texture;
  19266. };
  19267. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19268. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19269. if (noMipmap === void 0) { noMipmap = false; }
  19270. if (invertY === void 0) { invertY = true; }
  19271. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19272. if (onLoad === void 0) { onLoad = null; }
  19273. if (onError === void 0) { onError = null; }
  19274. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19275. if (name.substr(0, 5) !== "data:") {
  19276. name = "data:" + name;
  19277. }
  19278. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19279. };
  19280. return Texture;
  19281. }(BABYLON.BaseTexture));
  19282. // Constants
  19283. Texture.NEAREST_SAMPLINGMODE = 1;
  19284. Texture.BILINEAR_SAMPLINGMODE = 2;
  19285. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19286. Texture.EXPLICIT_MODE = 0;
  19287. Texture.SPHERICAL_MODE = 1;
  19288. Texture.PLANAR_MODE = 2;
  19289. Texture.CUBIC_MODE = 3;
  19290. Texture.PROJECTION_MODE = 4;
  19291. Texture.SKYBOX_MODE = 5;
  19292. Texture.INVCUBIC_MODE = 6;
  19293. Texture.EQUIRECTANGULAR_MODE = 7;
  19294. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19295. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19296. Texture.CLAMP_ADDRESSMODE = 0;
  19297. Texture.WRAP_ADDRESSMODE = 1;
  19298. Texture.MIRROR_ADDRESSMODE = 2;
  19299. __decorate([
  19300. BABYLON.serialize()
  19301. ], Texture.prototype, "url", void 0);
  19302. __decorate([
  19303. BABYLON.serialize()
  19304. ], Texture.prototype, "uOffset", void 0);
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], Texture.prototype, "vOffset", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], Texture.prototype, "uScale", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Texture.prototype, "vScale", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Texture.prototype, "uAng", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Texture.prototype, "vAng", void 0);
  19320. __decorate([
  19321. BABYLON.serialize()
  19322. ], Texture.prototype, "wAng", void 0);
  19323. __decorate([
  19324. BABYLON.serialize()
  19325. ], Texture.prototype, "isBlocking", null);
  19326. BABYLON.Texture = Texture;
  19327. })(BABYLON || (BABYLON = {}));
  19328. //# sourceMappingURL=babylon.texture.js.map
  19329. var BABYLON;
  19330. (function (BABYLON) {
  19331. var _InstancesBatch = (function () {
  19332. function _InstancesBatch() {
  19333. this.mustReturn = false;
  19334. this.visibleInstances = new Array();
  19335. this.renderSelf = new Array();
  19336. }
  19337. return _InstancesBatch;
  19338. }());
  19339. BABYLON._InstancesBatch = _InstancesBatch;
  19340. var Mesh = (function (_super) {
  19341. __extends(Mesh, _super);
  19342. /**
  19343. * @constructor
  19344. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19345. * @param {Scene} scene The scene to add this mesh to.
  19346. * @param {Node} parent The parent of this mesh, if it has one
  19347. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19348. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19349. * When false, achieved by calling a clone(), also passing False.
  19350. * This will make creation of children, recursive.
  19351. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19352. */
  19353. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19354. if (parent === void 0) { parent = null; }
  19355. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19356. var _this = _super.call(this, name, scene) || this;
  19357. // Events
  19358. /**
  19359. * An event triggered before rendering the mesh
  19360. * @type {BABYLON.Observable}
  19361. */
  19362. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19363. /**
  19364. * An event triggered after rendering the mesh
  19365. * @type {BABYLON.Observable}
  19366. */
  19367. _this.onAfterRenderObservable = new BABYLON.Observable();
  19368. /**
  19369. * An event triggered before drawing the mesh
  19370. * @type {BABYLON.Observable}
  19371. */
  19372. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19373. // Members
  19374. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19375. _this.instances = new Array();
  19376. _this._LODLevels = new Array();
  19377. _this._visibleInstances = {};
  19378. _this._renderIdForInstances = new Array();
  19379. _this._batchCache = new _InstancesBatch();
  19380. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19381. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19382. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19383. // Will be used to save a source mesh reference, If any
  19384. _this._source = null;
  19385. if (source) {
  19386. // Source mesh
  19387. _this._source = source;
  19388. // Geometry
  19389. if (source._geometry) {
  19390. source._geometry.applyToMesh(_this);
  19391. }
  19392. // Deep copy
  19393. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19394. // Parent
  19395. _this.parent = source.parent;
  19396. // Pivot
  19397. _this.setPivotMatrix(source.getPivotMatrix());
  19398. _this.id = name + "." + source.id;
  19399. // Material
  19400. _this.material = source.material;
  19401. var index;
  19402. if (!doNotCloneChildren) {
  19403. // Children
  19404. for (index = 0; index < scene.meshes.length; index++) {
  19405. var mesh = scene.meshes[index];
  19406. if (mesh.parent === source) {
  19407. // doNotCloneChildren is always going to be False
  19408. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19409. }
  19410. }
  19411. }
  19412. // Physics clone
  19413. var physicsEngine = _this.getScene().getPhysicsEngine();
  19414. if (clonePhysicsImpostor && physicsEngine) {
  19415. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19416. if (impostor) {
  19417. _this.physicsImpostor = impostor.clone(_this);
  19418. }
  19419. }
  19420. // Particles
  19421. for (index = 0; index < scene.particleSystems.length; index++) {
  19422. var system = scene.particleSystems[index];
  19423. if (system.emitter === source) {
  19424. system.clone(system.name, _this);
  19425. }
  19426. }
  19427. _this.computeWorldMatrix(true);
  19428. }
  19429. // Parent
  19430. if (parent !== null) {
  19431. _this.parent = parent;
  19432. }
  19433. return _this;
  19434. }
  19435. Object.defineProperty(Mesh, "FRONTSIDE", {
  19436. /**
  19437. * Mesh side orientation : usually the external or front surface
  19438. */
  19439. get: function () {
  19440. return Mesh._FRONTSIDE;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(Mesh, "BACKSIDE", {
  19446. /**
  19447. * Mesh side orientation : usually the internal or back surface
  19448. */
  19449. get: function () {
  19450. return Mesh._BACKSIDE;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19456. /**
  19457. * Mesh side orientation : both internal and external or front and back surfaces
  19458. */
  19459. get: function () {
  19460. return Mesh._DOUBLESIDE;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19466. /**
  19467. * Mesh side orientation : by default, `FRONTSIDE`
  19468. */
  19469. get: function () {
  19470. return Mesh._DEFAULTSIDE;
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. Object.defineProperty(Mesh, "NO_CAP", {
  19476. /**
  19477. * Mesh cap setting : no cap
  19478. */
  19479. get: function () {
  19480. return Mesh._NO_CAP;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(Mesh, "CAP_START", {
  19486. /**
  19487. * Mesh cap setting : one cap at the beginning of the mesh
  19488. */
  19489. get: function () {
  19490. return Mesh._CAP_START;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(Mesh, "CAP_END", {
  19496. /**
  19497. * Mesh cap setting : one cap at the end of the mesh
  19498. */
  19499. get: function () {
  19500. return Mesh._CAP_END;
  19501. },
  19502. enumerable: true,
  19503. configurable: true
  19504. });
  19505. Object.defineProperty(Mesh, "CAP_ALL", {
  19506. /**
  19507. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19508. */
  19509. get: function () {
  19510. return Mesh._CAP_ALL;
  19511. },
  19512. enumerable: true,
  19513. configurable: true
  19514. });
  19515. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19516. set: function (callback) {
  19517. if (this._onBeforeDrawObserver) {
  19518. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19519. }
  19520. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19521. },
  19522. enumerable: true,
  19523. configurable: true
  19524. });
  19525. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19526. get: function () {
  19527. return this._morphTargetManager;
  19528. },
  19529. set: function (value) {
  19530. if (this._morphTargetManager === value) {
  19531. return;
  19532. }
  19533. this._morphTargetManager = value;
  19534. this._syncGeometryWithMorphTargetManager();
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. Object.defineProperty(Mesh.prototype, "source", {
  19540. get: function () {
  19541. return this._source;
  19542. },
  19543. enumerable: true,
  19544. configurable: true
  19545. });
  19546. // Methods
  19547. /**
  19548. * Returns the string "Mesh".
  19549. */
  19550. Mesh.prototype.getClassName = function () {
  19551. return "Mesh";
  19552. };
  19553. /**
  19554. * Returns a string.
  19555. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19556. */
  19557. Mesh.prototype.toString = function (fullDetails) {
  19558. var ret = _super.prototype.toString.call(this, fullDetails);
  19559. ret += ", n vertices: " + this.getTotalVertices();
  19560. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19561. if (this.animations) {
  19562. for (var i = 0; i < this.animations.length; i++) {
  19563. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19564. }
  19565. }
  19566. if (fullDetails) {
  19567. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19568. }
  19569. return ret;
  19570. };
  19571. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19572. /**
  19573. * True if the mesh has some Levels Of Details (LOD).
  19574. * Returns a boolean.
  19575. */
  19576. get: function () {
  19577. return this._LODLevels.length > 0;
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Mesh.prototype._sortLODLevels = function () {
  19583. this._LODLevels.sort(function (a, b) {
  19584. if (a.distance < b.distance) {
  19585. return 1;
  19586. }
  19587. if (a.distance > b.distance) {
  19588. return -1;
  19589. }
  19590. return 0;
  19591. });
  19592. };
  19593. /**
  19594. * Add a mesh as LOD level triggered at the given distance.
  19595. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19596. * @param {number} distance The distance from the center of the object to show this level
  19597. * @param {Mesh} mesh The mesh to be added as LOD level
  19598. * @return {Mesh} This mesh (for chaining)
  19599. */
  19600. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19601. if (mesh && mesh._masterMesh) {
  19602. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19603. return this;
  19604. }
  19605. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19606. this._LODLevels.push(level);
  19607. if (mesh) {
  19608. mesh._masterMesh = this;
  19609. }
  19610. this._sortLODLevels();
  19611. return this;
  19612. };
  19613. /**
  19614. * Returns the LOD level mesh at the passed distance or null if not found.
  19615. * It is related to the method `addLODLevel(distance, mesh)`.
  19616. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19617. * Returns an object Mesh or `null`.
  19618. */
  19619. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19620. for (var index = 0; index < this._LODLevels.length; index++) {
  19621. var level = this._LODLevels[index];
  19622. if (level.distance === distance) {
  19623. return level.mesh;
  19624. }
  19625. }
  19626. return null;
  19627. };
  19628. /**
  19629. * Remove a mesh from the LOD array
  19630. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19631. * @param {Mesh} mesh The mesh to be removed.
  19632. * @return {Mesh} This mesh (for chaining)
  19633. */
  19634. Mesh.prototype.removeLODLevel = function (mesh) {
  19635. for (var index = 0; index < this._LODLevels.length; index++) {
  19636. if (this._LODLevels[index].mesh === mesh) {
  19637. this._LODLevels.splice(index, 1);
  19638. if (mesh) {
  19639. mesh._masterMesh = null;
  19640. }
  19641. }
  19642. }
  19643. this._sortLODLevels();
  19644. return this;
  19645. };
  19646. /**
  19647. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19648. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19649. */
  19650. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19651. if (!this._LODLevels || this._LODLevels.length === 0) {
  19652. return this;
  19653. }
  19654. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19655. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19656. if (this.onLODLevelSelection) {
  19657. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19658. }
  19659. return this;
  19660. }
  19661. for (var index = 0; index < this._LODLevels.length; index++) {
  19662. var level = this._LODLevels[index];
  19663. if (level.distance < distanceToCamera) {
  19664. if (level.mesh) {
  19665. level.mesh._preActivate();
  19666. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19667. }
  19668. if (this.onLODLevelSelection) {
  19669. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19670. }
  19671. return level.mesh;
  19672. }
  19673. }
  19674. if (this.onLODLevelSelection) {
  19675. this.onLODLevelSelection(distanceToCamera, this, this);
  19676. }
  19677. return this;
  19678. };
  19679. Object.defineProperty(Mesh.prototype, "geometry", {
  19680. /**
  19681. * Returns the mesh internal Geometry object.
  19682. */
  19683. get: function () {
  19684. return this._geometry;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. /**
  19690. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19691. */
  19692. Mesh.prototype.getTotalVertices = function () {
  19693. if (!this._geometry) {
  19694. return 0;
  19695. }
  19696. return this._geometry.getTotalVertices();
  19697. };
  19698. /**
  19699. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19700. * 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.
  19701. * You can force the copy with forceCopy === true
  19702. * Returns null if the mesh has no geometry or no vertex buffer.
  19703. * Possible `kind` values :
  19704. * - BABYLON.VertexBuffer.PositionKind
  19705. * - BABYLON.VertexBuffer.UVKind
  19706. * - BABYLON.VertexBuffer.UV2Kind
  19707. * - BABYLON.VertexBuffer.UV3Kind
  19708. * - BABYLON.VertexBuffer.UV4Kind
  19709. * - BABYLON.VertexBuffer.UV5Kind
  19710. * - BABYLON.VertexBuffer.UV6Kind
  19711. * - BABYLON.VertexBuffer.ColorKind
  19712. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19713. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19714. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19715. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19716. */
  19717. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19718. if (!this._geometry) {
  19719. return null;
  19720. }
  19721. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19722. };
  19723. /**
  19724. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19725. * Returns `undefined` if the mesh has no geometry.
  19726. * Possible `kind` values :
  19727. * - BABYLON.VertexBuffer.PositionKind
  19728. * - BABYLON.VertexBuffer.UVKind
  19729. * - BABYLON.VertexBuffer.UV2Kind
  19730. * - BABYLON.VertexBuffer.UV3Kind
  19731. * - BABYLON.VertexBuffer.UV4Kind
  19732. * - BABYLON.VertexBuffer.UV5Kind
  19733. * - BABYLON.VertexBuffer.UV6Kind
  19734. * - BABYLON.VertexBuffer.ColorKind
  19735. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19736. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19737. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19738. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19739. */
  19740. Mesh.prototype.getVertexBuffer = function (kind) {
  19741. if (!this._geometry) {
  19742. return undefined;
  19743. }
  19744. return this._geometry.getVertexBuffer(kind);
  19745. };
  19746. /**
  19747. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19748. * Possible `kind` values :
  19749. * - BABYLON.VertexBuffer.PositionKind
  19750. * - BABYLON.VertexBuffer.UVKind
  19751. * - BABYLON.VertexBuffer.UV2Kind
  19752. * - BABYLON.VertexBuffer.UV3Kind
  19753. * - BABYLON.VertexBuffer.UV4Kind
  19754. * - BABYLON.VertexBuffer.UV5Kind
  19755. * - BABYLON.VertexBuffer.UV6Kind
  19756. * - BABYLON.VertexBuffer.ColorKind
  19757. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19758. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19759. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19760. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19761. */
  19762. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19763. if (!this._geometry) {
  19764. if (this._delayInfo) {
  19765. return this._delayInfo.indexOf(kind) !== -1;
  19766. }
  19767. return false;
  19768. }
  19769. return this._geometry.isVerticesDataPresent(kind);
  19770. };
  19771. /**
  19772. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19773. * Possible `kind` values :
  19774. * - BABYLON.VertexBuffer.PositionKind
  19775. * - BABYLON.VertexBuffer.UVKind
  19776. * - BABYLON.VertexBuffer.UV2Kind
  19777. * - BABYLON.VertexBuffer.UV3Kind
  19778. * - BABYLON.VertexBuffer.UV4Kind
  19779. * - BABYLON.VertexBuffer.UV5Kind
  19780. * - BABYLON.VertexBuffer.UV6Kind
  19781. * - BABYLON.VertexBuffer.ColorKind
  19782. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19783. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19784. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19785. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19786. */
  19787. Mesh.prototype.getVerticesDataKinds = function () {
  19788. if (!this._geometry) {
  19789. var result = [];
  19790. if (this._delayInfo) {
  19791. this._delayInfo.forEach(function (kind, index, array) {
  19792. result.push(kind);
  19793. });
  19794. }
  19795. return result;
  19796. }
  19797. return this._geometry.getVerticesDataKinds();
  19798. };
  19799. /**
  19800. * Returns a positive integer : the total number of indices in this mesh geometry.
  19801. * Returns zero if the mesh has no geometry.
  19802. */
  19803. Mesh.prototype.getTotalIndices = function () {
  19804. if (!this._geometry) {
  19805. return 0;
  19806. }
  19807. return this._geometry.getTotalIndices();
  19808. };
  19809. /**
  19810. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19811. * 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.
  19812. * Returns an empty array if the mesh has no geometry.
  19813. */
  19814. Mesh.prototype.getIndices = function (copyWhenShared) {
  19815. if (!this._geometry) {
  19816. return [];
  19817. }
  19818. return this._geometry.getIndices(copyWhenShared);
  19819. };
  19820. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19821. get: function () {
  19822. return this._masterMesh !== null && this._masterMesh !== undefined;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. /**
  19828. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19829. */
  19830. Mesh.prototype.isReady = function () {
  19831. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19832. return false;
  19833. }
  19834. return _super.prototype.isReady.call(this);
  19835. };
  19836. /**
  19837. * Boolean : true if the mesh has been disposed.
  19838. */
  19839. Mesh.prototype.isDisposed = function () {
  19840. return this._isDisposed;
  19841. };
  19842. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19843. get: function () {
  19844. return this._sideOrientation;
  19845. },
  19846. /**
  19847. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19848. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19849. */
  19850. set: function (sideO) {
  19851. this._sideOrientation = sideO;
  19852. },
  19853. enumerable: true,
  19854. configurable: true
  19855. });
  19856. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19857. /**
  19858. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19859. * This property is pertinent only for updatable parametric shapes.
  19860. */
  19861. get: function () {
  19862. return this._areNormalsFrozen;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. /**
  19868. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19869. * It has no effect at all on other shapes.
  19870. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19871. * Returns the Mesh.
  19872. */
  19873. Mesh.prototype.freezeNormals = function () {
  19874. this._areNormalsFrozen = true;
  19875. return this;
  19876. };
  19877. /**
  19878. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19879. * It has no effect at all on other shapes.
  19880. * It reactivates the mesh normals computation if it was previously frozen.
  19881. * Returns the Mesh.
  19882. */
  19883. Mesh.prototype.unfreezeNormals = function () {
  19884. this._areNormalsFrozen = false;
  19885. return this;
  19886. };
  19887. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19888. /**
  19889. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19890. */
  19891. set: function (count) {
  19892. this._overridenInstanceCount = count;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. // Methods
  19898. Mesh.prototype._preActivate = function () {
  19899. var sceneRenderId = this.getScene().getRenderId();
  19900. if (this._preActivateId === sceneRenderId) {
  19901. return this;
  19902. }
  19903. this._preActivateId = sceneRenderId;
  19904. this._visibleInstances = null;
  19905. return this;
  19906. };
  19907. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19908. if (this._visibleInstances) {
  19909. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19910. }
  19911. return this;
  19912. };
  19913. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19914. if (!this._visibleInstances) {
  19915. this._visibleInstances = {};
  19916. this._visibleInstances.defaultRenderId = renderId;
  19917. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19918. }
  19919. if (!this._visibleInstances[renderId]) {
  19920. this._visibleInstances[renderId] = new Array();
  19921. }
  19922. this._visibleInstances[renderId].push(instance);
  19923. return this;
  19924. };
  19925. /**
  19926. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19927. * This means the mesh underlying bounding box and sphere are recomputed.
  19928. * Returns the Mesh.
  19929. */
  19930. Mesh.prototype.refreshBoundingInfo = function () {
  19931. if (this._boundingInfo.isLocked) {
  19932. return;
  19933. }
  19934. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19935. if (data) {
  19936. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19937. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19938. }
  19939. if (this.subMeshes) {
  19940. for (var index = 0; index < this.subMeshes.length; index++) {
  19941. this.subMeshes[index].refreshBoundingInfo();
  19942. }
  19943. }
  19944. this._updateBoundingInfo();
  19945. return this;
  19946. };
  19947. Mesh.prototype._createGlobalSubMesh = function () {
  19948. var totalVertices = this.getTotalVertices();
  19949. if (!totalVertices || !this.getIndices()) {
  19950. return null;
  19951. }
  19952. this.releaseSubMeshes();
  19953. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19954. };
  19955. Mesh.prototype.subdivide = function (count) {
  19956. if (count < 1) {
  19957. return;
  19958. }
  19959. var totalIndices = this.getTotalIndices();
  19960. var subdivisionSize = (totalIndices / count) | 0;
  19961. var offset = 0;
  19962. // Ensure that subdivisionSize is a multiple of 3
  19963. while (subdivisionSize % 3 !== 0) {
  19964. subdivisionSize++;
  19965. }
  19966. this.releaseSubMeshes();
  19967. for (var index = 0; index < count; index++) {
  19968. if (offset >= totalIndices) {
  19969. break;
  19970. }
  19971. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19972. offset += subdivisionSize;
  19973. }
  19974. this.synchronizeInstances();
  19975. };
  19976. /**
  19977. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19978. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19979. * The `data` are either a numeric array either a Float32Array.
  19980. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19981. * 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).
  19982. * Note that a new underlying VertexBuffer object is created each call.
  19983. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19984. *
  19985. * Possible `kind` values :
  19986. * - BABYLON.VertexBuffer.PositionKind
  19987. * - BABYLON.VertexBuffer.UVKind
  19988. * - BABYLON.VertexBuffer.UV2Kind
  19989. * - BABYLON.VertexBuffer.UV3Kind
  19990. * - BABYLON.VertexBuffer.UV4Kind
  19991. * - BABYLON.VertexBuffer.UV5Kind
  19992. * - BABYLON.VertexBuffer.UV6Kind
  19993. * - BABYLON.VertexBuffer.ColorKind
  19994. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19995. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19996. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19997. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19998. *
  19999. * Returns the Mesh.
  20000. */
  20001. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20002. if (!this._geometry) {
  20003. var vertexData = new BABYLON.VertexData();
  20004. vertexData.set(data, kind);
  20005. var scene = this.getScene();
  20006. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20007. }
  20008. else {
  20009. this._geometry.setVerticesData(kind, data, updatable, stride);
  20010. }
  20011. return this;
  20012. };
  20013. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20014. if (updatable === void 0) { updatable = true; }
  20015. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20016. return;
  20017. }
  20018. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20019. };
  20020. /**
  20021. * Sets the mesh VertexBuffer.
  20022. * Returns the Mesh.
  20023. */
  20024. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20025. if (!this._geometry) {
  20026. var scene = this.getScene();
  20027. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20028. }
  20029. this._geometry.setVerticesBuffer(buffer);
  20030. return this;
  20031. };
  20032. /**
  20033. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20034. * If the mesh has no geometry, it is simply returned as it is.
  20035. * The `data` are either a numeric array either a Float32Array.
  20036. * No new underlying VertexBuffer object is created.
  20037. * 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.
  20038. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20039. *
  20040. * Possible `kind` values :
  20041. * - BABYLON.VertexBuffer.PositionKind
  20042. * - BABYLON.VertexBuffer.UVKind
  20043. * - BABYLON.VertexBuffer.UV2Kind
  20044. * - BABYLON.VertexBuffer.UV3Kind
  20045. * - BABYLON.VertexBuffer.UV4Kind
  20046. * - BABYLON.VertexBuffer.UV5Kind
  20047. * - BABYLON.VertexBuffer.UV6Kind
  20048. * - BABYLON.VertexBuffer.ColorKind
  20049. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20050. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20051. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20052. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20053. *
  20054. * Returns the Mesh.
  20055. */
  20056. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20057. if (!this._geometry) {
  20058. return;
  20059. }
  20060. if (!makeItUnique) {
  20061. this._geometry.updateVerticesData(kind, data, updateExtends);
  20062. }
  20063. else {
  20064. this.makeGeometryUnique();
  20065. this.updateVerticesData(kind, data, updateExtends, false);
  20066. }
  20067. return this;
  20068. };
  20069. /**
  20070. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20071. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20072. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20073. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20074. * Returns the Mesh.
  20075. */
  20076. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20077. if (computeNormals === void 0) { computeNormals = true; }
  20078. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20079. positionFunction(positions);
  20080. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20081. if (computeNormals) {
  20082. var indices = this.getIndices();
  20083. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20084. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20085. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20086. }
  20087. return this;
  20088. };
  20089. /**
  20090. * This method will force the computation of normals for the mesh.
  20091. * Please note that the mesh must have normals vertex data already.
  20092. * Returns the Mesh.
  20093. */
  20094. Mesh.prototype.recomputeNormals = function () {
  20095. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20096. var indices = this.getIndices();
  20097. var normals;
  20098. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20099. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20100. }
  20101. else {
  20102. normals = [];
  20103. }
  20104. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20105. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20106. return this;
  20107. };
  20108. /**
  20109. * Creates a un-shared specific occurence of the geometry for the mesh.
  20110. * Returns the Mesh.
  20111. */
  20112. Mesh.prototype.makeGeometryUnique = function () {
  20113. if (!this._geometry) {
  20114. return;
  20115. }
  20116. var oldGeometry = this._geometry;
  20117. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20118. oldGeometry.releaseForMesh(this, true);
  20119. geometry.applyToMesh(this);
  20120. return this;
  20121. };
  20122. /**
  20123. * Sets the mesh indices.
  20124. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20125. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20126. * This method creates a new index buffer each call.
  20127. * Returns the Mesh.
  20128. */
  20129. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20130. if (!this._geometry) {
  20131. var vertexData = new BABYLON.VertexData();
  20132. vertexData.indices = indices;
  20133. var scene = this.getScene();
  20134. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20135. }
  20136. else {
  20137. this._geometry.setIndices(indices, totalVertices);
  20138. }
  20139. return this;
  20140. };
  20141. /**
  20142. * Invert the geometry to move from a right handed system to a left handed one.
  20143. * Returns the Mesh.
  20144. */
  20145. Mesh.prototype.toLeftHanded = function () {
  20146. if (!this._geometry) {
  20147. return;
  20148. }
  20149. this._geometry.toLeftHanded();
  20150. return this;
  20151. };
  20152. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20153. var engine = this.getScene().getEngine();
  20154. // Wireframe
  20155. var indexToBind;
  20156. if (this._unIndexed) {
  20157. indexToBind = null;
  20158. }
  20159. else {
  20160. switch (fillMode) {
  20161. case BABYLON.Material.PointFillMode:
  20162. indexToBind = null;
  20163. break;
  20164. case BABYLON.Material.WireFrameFillMode:
  20165. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20166. break;
  20167. default:
  20168. case BABYLON.Material.TriangleFillMode:
  20169. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20170. break;
  20171. }
  20172. }
  20173. // VBOs
  20174. this._geometry._bind(effect, indexToBind);
  20175. return this;
  20176. };
  20177. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20178. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20179. return this;
  20180. }
  20181. this.onBeforeDrawObservable.notifyObservers(this);
  20182. var engine = this.getScene().getEngine();
  20183. // Draw order
  20184. switch (fillMode) {
  20185. case BABYLON.Material.PointFillMode:
  20186. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20187. break;
  20188. case BABYLON.Material.WireFrameFillMode:
  20189. if (this._unIndexed) {
  20190. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20191. }
  20192. else {
  20193. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20194. }
  20195. break;
  20196. default:
  20197. if (this._unIndexed) {
  20198. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20199. }
  20200. else {
  20201. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20202. }
  20203. }
  20204. return this;
  20205. };
  20206. /**
  20207. * Registers for this mesh a javascript function called just before the rendering process.
  20208. * This function is passed the current mesh.
  20209. * Return the Mesh.
  20210. */
  20211. Mesh.prototype.registerBeforeRender = function (func) {
  20212. this.onBeforeRenderObservable.add(func);
  20213. return this;
  20214. };
  20215. /**
  20216. * Disposes a previously registered javascript function called before the rendering.
  20217. * This function is passed the current mesh.
  20218. * Returns the Mesh.
  20219. */
  20220. Mesh.prototype.unregisterBeforeRender = function (func) {
  20221. this.onBeforeRenderObservable.removeCallback(func);
  20222. return this;
  20223. };
  20224. /**
  20225. * Registers for this mesh a javascript function called just after the rendering is complete.
  20226. * This function is passed the current mesh.
  20227. * Returns the Mesh.
  20228. */
  20229. Mesh.prototype.registerAfterRender = function (func) {
  20230. this.onAfterRenderObservable.add(func);
  20231. return this;
  20232. };
  20233. /**
  20234. * Disposes a previously registered javascript function called after the rendering.
  20235. * This function is passed the current mesh.
  20236. * Return the Mesh.
  20237. */
  20238. Mesh.prototype.unregisterAfterRender = function (func) {
  20239. this.onAfterRenderObservable.removeCallback(func);
  20240. return this;
  20241. };
  20242. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20243. var scene = this.getScene();
  20244. this._batchCache.mustReturn = false;
  20245. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20246. this._batchCache.visibleInstances[subMeshId] = null;
  20247. if (this._visibleInstances) {
  20248. var currentRenderId = scene.getRenderId();
  20249. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20250. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20251. var selfRenderId = this._renderId;
  20252. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20253. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20254. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20255. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20256. }
  20257. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20258. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20259. this._batchCache.mustReturn = true;
  20260. return this._batchCache;
  20261. }
  20262. if (currentRenderId !== selfRenderId) {
  20263. this._batchCache.renderSelf[subMeshId] = false;
  20264. }
  20265. }
  20266. this._renderIdForInstances[subMeshId] = currentRenderId;
  20267. }
  20268. return this._batchCache;
  20269. };
  20270. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20271. var visibleInstances = batch.visibleInstances[subMesh._id];
  20272. var matricesCount = visibleInstances.length + 1;
  20273. var bufferSize = matricesCount * 16 * 4;
  20274. var currentInstancesBufferSize = this._instancesBufferSize;
  20275. var instancesBuffer = this._instancesBuffer;
  20276. while (this._instancesBufferSize < bufferSize) {
  20277. this._instancesBufferSize *= 2;
  20278. }
  20279. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20280. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20281. }
  20282. var offset = 0;
  20283. var instancesCount = 0;
  20284. var world = this.getWorldMatrix();
  20285. if (batch.renderSelf[subMesh._id]) {
  20286. world.copyToArray(this._instancesData, offset);
  20287. offset += 16;
  20288. instancesCount++;
  20289. }
  20290. if (visibleInstances) {
  20291. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20292. var instance = visibleInstances[instanceIndex];
  20293. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20294. offset += 16;
  20295. instancesCount++;
  20296. }
  20297. }
  20298. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20299. if (instancesBuffer) {
  20300. instancesBuffer.dispose();
  20301. }
  20302. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20303. this._instancesBuffer = instancesBuffer;
  20304. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20305. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20306. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20307. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20308. }
  20309. else {
  20310. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20311. }
  20312. this.geometry._bind(effect);
  20313. this._draw(subMesh, fillMode, instancesCount);
  20314. engine.unbindInstanceAttributes();
  20315. return this;
  20316. };
  20317. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20318. var scene = this.getScene();
  20319. var engine = scene.getEngine();
  20320. if (hardwareInstancedRendering) {
  20321. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20322. }
  20323. else {
  20324. if (batch.renderSelf[subMesh._id]) {
  20325. // Draw
  20326. if (onBeforeDraw) {
  20327. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20328. }
  20329. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20330. }
  20331. if (batch.visibleInstances[subMesh._id]) {
  20332. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20333. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20334. // World
  20335. var world = instance.getWorldMatrix();
  20336. if (onBeforeDraw) {
  20337. onBeforeDraw(true, world, effectiveMaterial);
  20338. }
  20339. // Draw
  20340. this._draw(subMesh, fillMode);
  20341. }
  20342. }
  20343. }
  20344. return this;
  20345. };
  20346. /**
  20347. * Triggers the draw call for the mesh.
  20348. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20349. * Returns the Mesh.
  20350. */
  20351. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20352. var scene = this.getScene();
  20353. // Managing instances
  20354. var batch = this._getInstancesRenderList(subMesh._id);
  20355. if (batch.mustReturn) {
  20356. return this;
  20357. }
  20358. // Checking geometry state
  20359. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20360. return this;
  20361. }
  20362. var callbackIndex;
  20363. this.onBeforeRenderObservable.notifyObservers(this);
  20364. var engine = scene.getEngine();
  20365. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20366. // Material
  20367. var effectiveMaterial = subMesh.getMaterial();
  20368. if (!effectiveMaterial) {
  20369. return this;
  20370. }
  20371. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20372. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20373. return this;
  20374. }
  20375. }
  20376. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20377. return this;
  20378. }
  20379. // Alpha mode
  20380. if (enableAlphaMode) {
  20381. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20382. }
  20383. // Outline - step 1
  20384. var savedDepthWrite = engine.getDepthWrite();
  20385. if (this.renderOutline) {
  20386. engine.setDepthWrite(false);
  20387. scene.getOutlineRenderer().render(subMesh, batch);
  20388. engine.setDepthWrite(savedDepthWrite);
  20389. }
  20390. var effect;
  20391. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20392. effect = subMesh.effect;
  20393. }
  20394. else {
  20395. effect = effectiveMaterial.getEffect();
  20396. }
  20397. effectiveMaterial._preBind(effect);
  20398. // Bind
  20399. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20400. this._bind(subMesh, effect, fillMode);
  20401. var world = this.getWorldMatrix();
  20402. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20403. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20404. }
  20405. else {
  20406. effectiveMaterial.bind(world, this);
  20407. }
  20408. // Draw
  20409. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20410. // Unbind
  20411. effectiveMaterial.unbind();
  20412. // Outline - step 2
  20413. if (this.renderOutline && savedDepthWrite) {
  20414. engine.setDepthWrite(true);
  20415. engine.setColorWrite(false);
  20416. scene.getOutlineRenderer().render(subMesh, batch);
  20417. engine.setColorWrite(true);
  20418. }
  20419. // Overlay
  20420. if (this.renderOverlay) {
  20421. var currentMode = engine.getAlphaMode();
  20422. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20423. scene.getOutlineRenderer().render(subMesh, batch, true);
  20424. engine.setAlphaMode(currentMode);
  20425. }
  20426. this.onAfterRenderObservable.notifyObservers(this);
  20427. return this;
  20428. };
  20429. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20430. if (isInstance) {
  20431. effectiveMaterial.bindOnlyWorldMatrix(world);
  20432. }
  20433. return this;
  20434. };
  20435. /**
  20436. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20437. */
  20438. Mesh.prototype.getEmittedParticleSystems = function () {
  20439. var results = new Array();
  20440. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20441. var particleSystem = this.getScene().particleSystems[index];
  20442. if (particleSystem.emitter === this) {
  20443. results.push(particleSystem);
  20444. }
  20445. }
  20446. return results;
  20447. };
  20448. /**
  20449. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20450. */
  20451. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20452. var results = new Array();
  20453. var descendants = this.getDescendants();
  20454. descendants.push(this);
  20455. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20456. var particleSystem = this.getScene().particleSystems[index];
  20457. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20458. results.push(particleSystem);
  20459. }
  20460. }
  20461. return results;
  20462. };
  20463. Mesh.prototype._checkDelayState = function () {
  20464. var scene = this.getScene();
  20465. if (this._geometry) {
  20466. this._geometry.load(scene);
  20467. }
  20468. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20470. this._queueLoad(this, scene);
  20471. }
  20472. return this;
  20473. };
  20474. Mesh.prototype._queueLoad = function (mesh, scene) {
  20475. var _this = this;
  20476. scene._addPendingData(mesh);
  20477. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20478. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20479. if (data instanceof ArrayBuffer) {
  20480. _this._delayLoadingFunction(data, _this);
  20481. }
  20482. else {
  20483. _this._delayLoadingFunction(JSON.parse(data), _this);
  20484. }
  20485. _this.instances.forEach(function (instance) {
  20486. instance._syncSubMeshes();
  20487. });
  20488. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20489. scene._removePendingData(_this);
  20490. }, function () { }, scene.database, getBinaryData);
  20491. return this;
  20492. };
  20493. /**
  20494. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20495. */
  20496. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20497. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20498. return false;
  20499. }
  20500. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20501. return false;
  20502. }
  20503. this._checkDelayState();
  20504. return true;
  20505. };
  20506. /**
  20507. * Sets the mesh material by the material or multiMaterial `id` property.
  20508. * The material `id` is a string identifying the material or the multiMaterial.
  20509. * This method returns the Mesh.
  20510. */
  20511. Mesh.prototype.setMaterialByID = function (id) {
  20512. var materials = this.getScene().materials;
  20513. var index;
  20514. for (index = materials.length - 1; index > -1; index--) {
  20515. if (materials[index].id === id) {
  20516. this.material = materials[index];
  20517. return this;
  20518. }
  20519. }
  20520. // Multi
  20521. var multiMaterials = this.getScene().multiMaterials;
  20522. for (index = multiMaterials.length - 1; index > -1; index--) {
  20523. if (multiMaterials[index].id === id) {
  20524. this.material = multiMaterials[index];
  20525. return this;
  20526. }
  20527. }
  20528. return this;
  20529. };
  20530. /**
  20531. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20532. */
  20533. Mesh.prototype.getAnimatables = function () {
  20534. var results = [];
  20535. if (this.material) {
  20536. results.push(this.material);
  20537. }
  20538. if (this.skeleton) {
  20539. results.push(this.skeleton);
  20540. }
  20541. return results;
  20542. };
  20543. /**
  20544. * Modifies the mesh geometry according to the passed transformation matrix.
  20545. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20546. * The mesh normals are modified accordingly the same transformation.
  20547. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20548. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20549. * Returns the Mesh.
  20550. */
  20551. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20552. // Position
  20553. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20554. return this;
  20555. }
  20556. var submeshes = this.subMeshes.splice(0);
  20557. this._resetPointsArrayCache();
  20558. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20559. var temp = [];
  20560. var index;
  20561. for (index = 0; index < data.length; index += 3) {
  20562. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20563. }
  20564. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20565. // Normals
  20566. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20567. return this;
  20568. }
  20569. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20570. temp = [];
  20571. for (index = 0; index < data.length; index += 3) {
  20572. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20573. }
  20574. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20575. // flip faces?
  20576. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20577. this.flipFaces();
  20578. }
  20579. // Restore submeshes
  20580. this.releaseSubMeshes();
  20581. this.subMeshes = submeshes;
  20582. return this;
  20583. };
  20584. /**
  20585. * Modifies the mesh geometry according to its own current World Matrix.
  20586. * The mesh World Matrix is then reset.
  20587. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20588. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20589. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20590. * Returns the Mesh.
  20591. */
  20592. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20593. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20594. this.scaling.copyFromFloats(1, 1, 1);
  20595. this.position.copyFromFloats(0, 0, 0);
  20596. this.rotation.copyFromFloats(0, 0, 0);
  20597. //only if quaternion is already set
  20598. if (this.rotationQuaternion) {
  20599. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20600. }
  20601. this._worldMatrix = BABYLON.Matrix.Identity();
  20602. return this;
  20603. };
  20604. Object.defineProperty(Mesh.prototype, "_positions", {
  20605. // Cache
  20606. get: function () {
  20607. if (this._geometry) {
  20608. return this._geometry._positions;
  20609. }
  20610. return null;
  20611. },
  20612. enumerable: true,
  20613. configurable: true
  20614. });
  20615. Mesh.prototype._resetPointsArrayCache = function () {
  20616. if (this._geometry) {
  20617. this._geometry._resetPointsArrayCache();
  20618. }
  20619. return this;
  20620. };
  20621. Mesh.prototype._generatePointsArray = function () {
  20622. if (this._geometry) {
  20623. return this._geometry._generatePointsArray();
  20624. }
  20625. return false;
  20626. };
  20627. /**
  20628. * Returns a new Mesh object generated from the current mesh properties.
  20629. * This method must not get confused with createInstance().
  20630. * The parameter `name` is a string, the name given to the new mesh.
  20631. * The optional parameter `newParent` can be any Node object (default `null`).
  20632. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20633. * 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.
  20634. */
  20635. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20636. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20637. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20638. };
  20639. /**
  20640. * Disposes the mesh.
  20641. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20642. */
  20643. Mesh.prototype.dispose = function (doNotRecurse) {
  20644. var _this = this;
  20645. this.morphTargetManager = undefined;
  20646. if (this._geometry) {
  20647. this._geometry.releaseForMesh(this, true);
  20648. }
  20649. // Sources
  20650. var meshes = this.getScene().meshes;
  20651. meshes.forEach(function (mesh) {
  20652. if (mesh._source && mesh._source === _this) {
  20653. mesh._source = null;
  20654. }
  20655. });
  20656. this._source = null;
  20657. // Instances
  20658. if (this._instancesBuffer) {
  20659. this._instancesBuffer.dispose();
  20660. this._instancesBuffer = null;
  20661. }
  20662. while (this.instances.length) {
  20663. this.instances[0].dispose();
  20664. }
  20665. // Highlight layers.
  20666. var highlightLayers = this.getScene().highlightLayers;
  20667. for (var i = 0; i < highlightLayers.length; i++) {
  20668. var highlightLayer = highlightLayers[i];
  20669. if (highlightLayer) {
  20670. highlightLayer.removeMesh(this);
  20671. highlightLayer.removeExcludedMesh(this);
  20672. }
  20673. }
  20674. _super.prototype.dispose.call(this, doNotRecurse);
  20675. };
  20676. /**
  20677. * Modifies the mesh geometry according to a displacement map.
  20678. * 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.
  20679. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20680. * This method returns nothing.
  20681. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20682. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20683. * 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.
  20684. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20685. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20686. *
  20687. * Returns the Mesh.
  20688. */
  20689. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20690. var _this = this;
  20691. var scene = this.getScene();
  20692. var onload = function (img) {
  20693. // Getting height map data
  20694. var canvas = document.createElement("canvas");
  20695. var context = canvas.getContext("2d");
  20696. var heightMapWidth = img.width;
  20697. var heightMapHeight = img.height;
  20698. canvas.width = heightMapWidth;
  20699. canvas.height = heightMapHeight;
  20700. context.drawImage(img, 0, 0);
  20701. // Create VertexData from map data
  20702. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20703. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20704. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20705. //execute success callback, if set
  20706. if (onSuccess) {
  20707. onSuccess(_this);
  20708. }
  20709. };
  20710. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20711. return this;
  20712. };
  20713. /**
  20714. * Modifies the mesh geometry according to a displacementMap buffer.
  20715. * 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.
  20716. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20717. * This method returns nothing.
  20718. * 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.
  20719. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20720. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20721. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20722. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20723. *
  20724. * Returns the Mesh.
  20725. */
  20726. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20727. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20728. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20729. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20730. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20731. return this;
  20732. }
  20733. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20734. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20735. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20736. var position = BABYLON.Vector3.Zero();
  20737. var normal = BABYLON.Vector3.Zero();
  20738. var uv = BABYLON.Vector2.Zero();
  20739. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20740. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20741. for (var index = 0; index < positions.length; index += 3) {
  20742. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20743. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20744. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20745. // Compute height
  20746. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20747. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20748. var pos = (u + v * heightMapWidth) * 4;
  20749. var r = buffer[pos] / 255.0;
  20750. var g = buffer[pos + 1] / 255.0;
  20751. var b = buffer[pos + 2] / 255.0;
  20752. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20753. normal.normalize();
  20754. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20755. position = position.add(normal);
  20756. position.toArray(positions, index);
  20757. }
  20758. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20759. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20760. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20761. return this;
  20762. };
  20763. /**
  20764. * Modify the mesh to get a flat shading rendering.
  20765. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20766. * This method returns the Mesh.
  20767. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20768. */
  20769. Mesh.prototype.convertToFlatShadedMesh = function () {
  20770. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20771. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20772. var kinds = this.getVerticesDataKinds();
  20773. var vbs = [];
  20774. var data = [];
  20775. var newdata = [];
  20776. var updatableNormals = false;
  20777. var kindIndex;
  20778. var kind;
  20779. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20780. kind = kinds[kindIndex];
  20781. var vertexBuffer = this.getVertexBuffer(kind);
  20782. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20783. updatableNormals = vertexBuffer.isUpdatable();
  20784. kinds.splice(kindIndex, 1);
  20785. kindIndex--;
  20786. continue;
  20787. }
  20788. vbs[kind] = vertexBuffer;
  20789. data[kind] = vbs[kind].getData();
  20790. newdata[kind] = [];
  20791. }
  20792. // Save previous submeshes
  20793. var previousSubmeshes = this.subMeshes.slice(0);
  20794. var indices = this.getIndices();
  20795. var totalIndices = this.getTotalIndices();
  20796. // Generating unique vertices per face
  20797. var index;
  20798. for (index = 0; index < totalIndices; index++) {
  20799. var vertexIndex = indices[index];
  20800. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20801. kind = kinds[kindIndex];
  20802. var stride = vbs[kind].getStrideSize();
  20803. for (var offset = 0; offset < stride; offset++) {
  20804. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20805. }
  20806. }
  20807. }
  20808. // Updating faces & normal
  20809. var normals = [];
  20810. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20811. for (index = 0; index < totalIndices; index += 3) {
  20812. indices[index] = index;
  20813. indices[index + 1] = index + 1;
  20814. indices[index + 2] = index + 2;
  20815. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20816. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20817. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20818. var p1p2 = p1.subtract(p2);
  20819. var p3p2 = p3.subtract(p2);
  20820. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20821. // Store same normals for every vertex
  20822. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20823. normals.push(normal.x);
  20824. normals.push(normal.y);
  20825. normals.push(normal.z);
  20826. }
  20827. }
  20828. this.setIndices(indices);
  20829. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20830. // Updating vertex buffers
  20831. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20832. kind = kinds[kindIndex];
  20833. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20834. }
  20835. // Updating submeshes
  20836. this.releaseSubMeshes();
  20837. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20838. var previousOne = previousSubmeshes[submeshIndex];
  20839. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20840. }
  20841. this.synchronizeInstances();
  20842. return this;
  20843. };
  20844. /**
  20845. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20846. * In other words, more vertices, no more indices and a single bigger VBO.
  20847. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20848. * Returns the Mesh.
  20849. */
  20850. Mesh.prototype.convertToUnIndexedMesh = function () {
  20851. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20852. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20853. var kinds = this.getVerticesDataKinds();
  20854. var vbs = [];
  20855. var data = [];
  20856. var newdata = [];
  20857. var updatableNormals = false;
  20858. var kindIndex;
  20859. var kind;
  20860. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20861. kind = kinds[kindIndex];
  20862. var vertexBuffer = this.getVertexBuffer(kind);
  20863. vbs[kind] = vertexBuffer;
  20864. data[kind] = vbs[kind].getData();
  20865. newdata[kind] = [];
  20866. }
  20867. // Save previous submeshes
  20868. var previousSubmeshes = this.subMeshes.slice(0);
  20869. var indices = this.getIndices();
  20870. var totalIndices = this.getTotalIndices();
  20871. // Generating unique vertices per face
  20872. var index;
  20873. for (index = 0; index < totalIndices; index++) {
  20874. var vertexIndex = indices[index];
  20875. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20876. kind = kinds[kindIndex];
  20877. var stride = vbs[kind].getStrideSize();
  20878. for (var offset = 0; offset < stride; offset++) {
  20879. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20880. }
  20881. }
  20882. }
  20883. // Updating indices
  20884. for (index = 0; index < totalIndices; index += 3) {
  20885. indices[index] = index;
  20886. indices[index + 1] = index + 1;
  20887. indices[index + 2] = index + 2;
  20888. }
  20889. this.setIndices(indices);
  20890. // Updating vertex buffers
  20891. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20892. kind = kinds[kindIndex];
  20893. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20894. }
  20895. // Updating submeshes
  20896. this.releaseSubMeshes();
  20897. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20898. var previousOne = previousSubmeshes[submeshIndex];
  20899. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20900. }
  20901. this._unIndexed = true;
  20902. this.synchronizeInstances();
  20903. return this;
  20904. };
  20905. /**
  20906. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20907. * This method returns the Mesh.
  20908. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20909. */
  20910. Mesh.prototype.flipFaces = function (flipNormals) {
  20911. if (flipNormals === void 0) { flipNormals = false; }
  20912. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20913. var i;
  20914. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20915. for (i = 0; i < vertex_data.normals.length; i++) {
  20916. vertex_data.normals[i] *= -1;
  20917. }
  20918. }
  20919. var temp;
  20920. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20921. // reassign indices
  20922. temp = vertex_data.indices[i + 1];
  20923. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20924. vertex_data.indices[i + 2] = temp;
  20925. }
  20926. vertex_data.applyToMesh(this);
  20927. return this;
  20928. };
  20929. // Instances
  20930. /**
  20931. * Creates a new InstancedMesh object from the mesh model.
  20932. * An instance shares the same properties and the same material than its model.
  20933. * Only these properties of each instance can then be set individually :
  20934. * - position
  20935. * - rotation
  20936. * - rotationQuaternion
  20937. * - setPivotMatrix
  20938. * - scaling
  20939. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20940. * Warning : this method is not supported for Line mesh and LineSystem
  20941. */
  20942. Mesh.prototype.createInstance = function (name) {
  20943. return new BABYLON.InstancedMesh(name, this);
  20944. };
  20945. /**
  20946. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20947. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20948. * This method returns the Mesh.
  20949. */
  20950. Mesh.prototype.synchronizeInstances = function () {
  20951. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20952. var instance = this.instances[instanceIndex];
  20953. instance._syncSubMeshes();
  20954. }
  20955. return this;
  20956. };
  20957. /**
  20958. * Simplify the mesh according to the given array of settings.
  20959. * Function will return immediately and will simplify async. It returns the Mesh.
  20960. * @param settings a collection of simplification settings.
  20961. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20962. * @param type the type of simplification to run.
  20963. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20964. */
  20965. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20966. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20967. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20968. this.getScene().simplificationQueue.addTask({
  20969. settings: settings,
  20970. parallelProcessing: parallelProcessing,
  20971. mesh: this,
  20972. simplificationType: simplificationType,
  20973. successCallback: successCallback
  20974. });
  20975. return this;
  20976. };
  20977. /**
  20978. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20979. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20980. * This should be used together with the simplification to avoid disappearing triangles.
  20981. * Returns the Mesh.
  20982. * @param successCallback an optional success callback to be called after the optimization finished.
  20983. */
  20984. Mesh.prototype.optimizeIndices = function (successCallback) {
  20985. var _this = this;
  20986. var indices = this.getIndices();
  20987. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20988. var vectorPositions = [];
  20989. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20990. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20991. }
  20992. var dupes = [];
  20993. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20994. var realPos = vectorPositions.length - 1 - iteration;
  20995. var testedPosition = vectorPositions[realPos];
  20996. for (var j = 0; j < realPos; ++j) {
  20997. var againstPosition = vectorPositions[j];
  20998. if (testedPosition.equals(againstPosition)) {
  20999. dupes[realPos] = j;
  21000. break;
  21001. }
  21002. }
  21003. }, function () {
  21004. for (var i = 0; i < indices.length; ++i) {
  21005. indices[i] = dupes[indices[i]] || indices[i];
  21006. }
  21007. //indices are now reordered
  21008. var originalSubMeshes = _this.subMeshes.slice(0);
  21009. _this.setIndices(indices);
  21010. _this.subMeshes = originalSubMeshes;
  21011. if (successCallback) {
  21012. successCallback(_this);
  21013. }
  21014. });
  21015. return this;
  21016. };
  21017. Mesh.prototype.serialize = function (serializationObject) {
  21018. serializationObject.name = this.name;
  21019. serializationObject.id = this.id;
  21020. serializationObject.type = this.getClassName();
  21021. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21022. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21023. }
  21024. serializationObject.position = this.position.asArray();
  21025. if (this.rotationQuaternion) {
  21026. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21027. }
  21028. else if (this.rotation) {
  21029. serializationObject.rotation = this.rotation.asArray();
  21030. }
  21031. serializationObject.scaling = this.scaling.asArray();
  21032. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21033. serializationObject.isEnabled = this.isEnabled();
  21034. serializationObject.isVisible = this.isVisible;
  21035. serializationObject.infiniteDistance = this.infiniteDistance;
  21036. serializationObject.pickable = this.isPickable;
  21037. serializationObject.receiveShadows = this.receiveShadows;
  21038. serializationObject.billboardMode = this.billboardMode;
  21039. serializationObject.visibility = this.visibility;
  21040. serializationObject.checkCollisions = this.checkCollisions;
  21041. serializationObject.isBlocker = this.isBlocker;
  21042. // Parent
  21043. if (this.parent) {
  21044. serializationObject.parentId = this.parent.id;
  21045. }
  21046. // Geometry
  21047. var geometry = this._geometry;
  21048. if (geometry) {
  21049. var geometryId = geometry.id;
  21050. serializationObject.geometryId = geometryId;
  21051. // SubMeshes
  21052. serializationObject.subMeshes = [];
  21053. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21054. var subMesh = this.subMeshes[subIndex];
  21055. serializationObject.subMeshes.push({
  21056. materialIndex: subMesh.materialIndex,
  21057. verticesStart: subMesh.verticesStart,
  21058. verticesCount: subMesh.verticesCount,
  21059. indexStart: subMesh.indexStart,
  21060. indexCount: subMesh.indexCount
  21061. });
  21062. }
  21063. }
  21064. // Material
  21065. if (this.material) {
  21066. serializationObject.materialId = this.material.id;
  21067. }
  21068. else {
  21069. this.material = null;
  21070. }
  21071. // Morph targets
  21072. if (this.morphTargetManager) {
  21073. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21074. }
  21075. // Skeleton
  21076. if (this.skeleton) {
  21077. serializationObject.skeletonId = this.skeleton.id;
  21078. }
  21079. // Physics
  21080. //TODO implement correct serialization for physics impostors.
  21081. if (this.getPhysicsImpostor()) {
  21082. var impostor = this.getPhysicsImpostor();
  21083. serializationObject.physicsMass = impostor.getParam("mass");
  21084. serializationObject.physicsFriction = impostor.getParam("friction");
  21085. serializationObject.physicsRestitution = impostor.getParam("mass");
  21086. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21087. }
  21088. // Metadata
  21089. if (this.metadata) {
  21090. serializationObject.metadata = this.metadata;
  21091. }
  21092. // Instances
  21093. serializationObject.instances = [];
  21094. for (var index = 0; index < this.instances.length; index++) {
  21095. var instance = this.instances[index];
  21096. var serializationInstance = {
  21097. name: instance.name,
  21098. position: instance.position.asArray(),
  21099. scaling: instance.scaling.asArray()
  21100. };
  21101. if (instance.rotationQuaternion) {
  21102. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21103. }
  21104. else if (instance.rotation) {
  21105. serializationInstance.rotation = instance.rotation.asArray();
  21106. }
  21107. serializationObject.instances.push(serializationInstance);
  21108. // Animations
  21109. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21110. serializationInstance.ranges = instance.serializeAnimationRanges();
  21111. }
  21112. //
  21113. // Animations
  21114. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21115. serializationObject.ranges = this.serializeAnimationRanges();
  21116. // Layer mask
  21117. serializationObject.layerMask = this.layerMask;
  21118. // Alpha
  21119. serializationObject.alphaIndex = this.alphaIndex;
  21120. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21121. // Overlay
  21122. serializationObject.overlayAlpha = this.overlayAlpha;
  21123. serializationObject.overlayColor = this.overlayColor.asArray();
  21124. serializationObject.renderOverlay = this.renderOverlay;
  21125. // Fog
  21126. serializationObject.applyFog = this.applyFog;
  21127. // Action Manager
  21128. if (this.actionManager) {
  21129. serializationObject.actions = this.actionManager.serialize(this.name);
  21130. }
  21131. };
  21132. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21133. if (!this.geometry) {
  21134. return;
  21135. }
  21136. this._markSubMeshesAsAttributesDirty();
  21137. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21138. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21139. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21140. this.morphTargetManager = undefined;
  21141. return;
  21142. }
  21143. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21144. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21145. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21146. if (morphTarget.hasNormals) {
  21147. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21148. }
  21149. if (morphTarget.hasTangents) {
  21150. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21151. }
  21152. }
  21153. }
  21154. else {
  21155. var index = 0;
  21156. // Positions
  21157. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21158. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21159. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21160. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21161. }
  21162. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21163. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21164. }
  21165. index++;
  21166. }
  21167. }
  21168. };
  21169. // Statics
  21170. /**
  21171. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21172. * The parameter `parsedMesh` is the mesh to be copied.
  21173. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21174. */
  21175. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21176. var mesh;
  21177. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21178. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21179. }
  21180. else {
  21181. mesh = new Mesh(parsedMesh.name, scene);
  21182. }
  21183. mesh.id = parsedMesh.id;
  21184. if (BABYLON.Tags) {
  21185. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21186. }
  21187. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21188. if (parsedMesh.metadata !== undefined) {
  21189. mesh.metadata = parsedMesh.metadata;
  21190. }
  21191. if (parsedMesh.rotationQuaternion) {
  21192. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21193. }
  21194. else if (parsedMesh.rotation) {
  21195. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21196. }
  21197. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21198. if (parsedMesh.localMatrix) {
  21199. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21200. }
  21201. else if (parsedMesh.pivotMatrix) {
  21202. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21203. }
  21204. mesh.setEnabled(parsedMesh.isEnabled);
  21205. mesh.isVisible = parsedMesh.isVisible;
  21206. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21207. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21208. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21209. if (parsedMesh.applyFog !== undefined) {
  21210. mesh.applyFog = parsedMesh.applyFog;
  21211. }
  21212. if (parsedMesh.pickable !== undefined) {
  21213. mesh.isPickable = parsedMesh.pickable;
  21214. }
  21215. if (parsedMesh.alphaIndex !== undefined) {
  21216. mesh.alphaIndex = parsedMesh.alphaIndex;
  21217. }
  21218. mesh.receiveShadows = parsedMesh.receiveShadows;
  21219. mesh.billboardMode = parsedMesh.billboardMode;
  21220. if (parsedMesh.visibility !== undefined) {
  21221. mesh.visibility = parsedMesh.visibility;
  21222. }
  21223. mesh.checkCollisions = parsedMesh.checkCollisions;
  21224. if (parsedMesh.isBlocker !== undefined) {
  21225. mesh.isBlocker = parsedMesh.isBlocker;
  21226. }
  21227. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21228. // freezeWorldMatrix
  21229. if (parsedMesh.freezeWorldMatrix) {
  21230. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21231. }
  21232. // Parent
  21233. if (parsedMesh.parentId) {
  21234. mesh._waitingParentId = parsedMesh.parentId;
  21235. }
  21236. // Actions
  21237. if (parsedMesh.actions !== undefined) {
  21238. mesh._waitingActions = parsedMesh.actions;
  21239. }
  21240. // Overlay
  21241. if (parsedMesh.overlayAlpha !== undefined) {
  21242. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21243. }
  21244. if (parsedMesh.overlayColor !== undefined) {
  21245. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21246. }
  21247. if (parsedMesh.renderOverlay !== undefined) {
  21248. mesh.renderOverlay = parsedMesh.renderOverlay;
  21249. }
  21250. // Geometry
  21251. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21252. if (parsedMesh.delayLoadingFile) {
  21253. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21254. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21255. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21256. if (parsedMesh._binaryInfo) {
  21257. mesh._binaryInfo = parsedMesh._binaryInfo;
  21258. }
  21259. mesh._delayInfo = [];
  21260. if (parsedMesh.hasUVs) {
  21261. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21262. }
  21263. if (parsedMesh.hasUVs2) {
  21264. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21265. }
  21266. if (parsedMesh.hasUVs3) {
  21267. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21268. }
  21269. if (parsedMesh.hasUVs4) {
  21270. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21271. }
  21272. if (parsedMesh.hasUVs5) {
  21273. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21274. }
  21275. if (parsedMesh.hasUVs6) {
  21276. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21277. }
  21278. if (parsedMesh.hasColors) {
  21279. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21280. }
  21281. if (parsedMesh.hasMatricesIndices) {
  21282. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21283. }
  21284. if (parsedMesh.hasMatricesWeights) {
  21285. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21286. }
  21287. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21288. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21289. mesh._checkDelayState();
  21290. }
  21291. }
  21292. else {
  21293. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21294. }
  21295. // Material
  21296. if (parsedMesh.materialId) {
  21297. mesh.setMaterialByID(parsedMesh.materialId);
  21298. }
  21299. else {
  21300. mesh.material = null;
  21301. }
  21302. // Morph targets
  21303. if (parsedMesh.morphTargetManagerId > -1) {
  21304. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21305. }
  21306. // Skeleton
  21307. if (parsedMesh.skeletonId > -1) {
  21308. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21309. if (parsedMesh.numBoneInfluencers) {
  21310. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21311. }
  21312. }
  21313. // Animations
  21314. if (parsedMesh.animations) {
  21315. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21316. var parsedAnimation = parsedMesh.animations[animationIndex];
  21317. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21318. }
  21319. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21320. }
  21321. if (parsedMesh.autoAnimate) {
  21322. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21323. }
  21324. // Layer Mask
  21325. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21326. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21327. }
  21328. else {
  21329. mesh.layerMask = 0x0FFFFFFF;
  21330. }
  21331. // Physics
  21332. if (parsedMesh.physicsImpostor) {
  21333. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21334. mass: parsedMesh.physicsMass,
  21335. friction: parsedMesh.physicsFriction,
  21336. restitution: parsedMesh.physicsRestitution
  21337. }, scene);
  21338. }
  21339. // Instances
  21340. if (parsedMesh.instances) {
  21341. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21342. var parsedInstance = parsedMesh.instances[index];
  21343. var instance = mesh.createInstance(parsedInstance.name);
  21344. if (BABYLON.Tags) {
  21345. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21346. }
  21347. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21348. if (parsedInstance.parentId) {
  21349. instance._waitingParentId = parsedInstance.parentId;
  21350. }
  21351. if (parsedInstance.rotationQuaternion) {
  21352. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21353. }
  21354. else if (parsedInstance.rotation) {
  21355. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21356. }
  21357. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21358. instance.checkCollisions = mesh.checkCollisions;
  21359. if (parsedMesh.animations) {
  21360. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21361. parsedAnimation = parsedMesh.animations[animationIndex];
  21362. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21363. }
  21364. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21365. }
  21366. }
  21367. }
  21368. return mesh;
  21369. };
  21370. /**
  21371. * Creates a ribbon mesh.
  21372. * Please consider using the same method from the MeshBuilder class instead.
  21373. * 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.
  21374. *
  21375. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21376. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21377. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21378. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21379. * 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.
  21380. * 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.
  21381. * 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
  21382. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21383. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21385. */
  21386. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21387. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21388. pathArray: pathArray,
  21389. closeArray: closeArray,
  21390. closePath: closePath,
  21391. offset: offset,
  21392. updatable: updatable,
  21393. sideOrientation: sideOrientation,
  21394. instance: instance
  21395. }, scene);
  21396. };
  21397. /**
  21398. * Creates a plane polygonal mesh. By default, this is a disc.
  21399. * Please consider using the same method from the MeshBuilder class instead.
  21400. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21401. * 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.
  21402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21405. */
  21406. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21407. var options = {
  21408. radius: radius,
  21409. tessellation: tessellation,
  21410. sideOrientation: sideOrientation,
  21411. updatable: updatable
  21412. };
  21413. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21414. };
  21415. /**
  21416. * Creates a box mesh.
  21417. * Please consider using the same method from the MeshBuilder class instead.
  21418. * The parameter `size` sets the size (float) of each box side (default 1).
  21419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21422. */
  21423. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21424. var options = {
  21425. size: size,
  21426. sideOrientation: sideOrientation,
  21427. updatable: updatable
  21428. };
  21429. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21430. };
  21431. /**
  21432. * Creates a sphere mesh.
  21433. * Please consider using the same method from the MeshBuilder class instead.
  21434. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21435. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21436. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21437. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21438. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21439. */
  21440. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21441. var options = {
  21442. segments: segments,
  21443. diameterX: diameter,
  21444. diameterY: diameter,
  21445. diameterZ: diameter,
  21446. sideOrientation: sideOrientation,
  21447. updatable: updatable
  21448. };
  21449. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21450. };
  21451. /**
  21452. * Creates a cylinder or a cone mesh.
  21453. * Please consider using the same method from the MeshBuilder class instead.
  21454. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21455. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21456. * 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.
  21457. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21458. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21459. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21462. */
  21463. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21464. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21465. if (scene !== undefined) {
  21466. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21467. updatable = scene;
  21468. }
  21469. scene = subdivisions;
  21470. subdivisions = 1;
  21471. }
  21472. var options = {
  21473. height: height,
  21474. diameterTop: diameterTop,
  21475. diameterBottom: diameterBottom,
  21476. tessellation: tessellation,
  21477. subdivisions: subdivisions,
  21478. sideOrientation: sideOrientation,
  21479. updatable: updatable
  21480. };
  21481. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21482. };
  21483. // Torus (Code from SharpDX.org)
  21484. /**
  21485. * Creates a torus mesh.
  21486. * Please consider using the same method from the MeshBuilder class instead.
  21487. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21488. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21489. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21490. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21493. */
  21494. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21495. var options = {
  21496. diameter: diameter,
  21497. thickness: thickness,
  21498. tessellation: tessellation,
  21499. sideOrientation: sideOrientation,
  21500. updatable: updatable
  21501. };
  21502. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21503. };
  21504. /**
  21505. * Creates a torus knot mesh.
  21506. * Please consider using the same method from the MeshBuilder class instead.
  21507. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21508. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21509. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21510. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21511. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21514. */
  21515. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21516. var options = {
  21517. radius: radius,
  21518. tube: tube,
  21519. radialSegments: radialSegments,
  21520. tubularSegments: tubularSegments,
  21521. p: p,
  21522. q: q,
  21523. sideOrientation: sideOrientation,
  21524. updatable: updatable
  21525. };
  21526. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21527. };
  21528. /**
  21529. * Creates a line mesh.
  21530. * Please consider using the same method from the MeshBuilder class instead.
  21531. * 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.
  21532. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21533. * The parameter `points` is an array successive Vector3.
  21534. * 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
  21535. * When updating an instance, remember that only point positions can change, not the number of points.
  21536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21537. */
  21538. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21539. var options = {
  21540. points: points,
  21541. updatable: updatable,
  21542. instance: instance
  21543. };
  21544. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21545. };
  21546. /**
  21547. * Creates a dashed line mesh.
  21548. * Please consider using the same method from the MeshBuilder class instead.
  21549. * 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.
  21550. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21551. * The parameter `points` is an array successive Vector3.
  21552. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21553. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21554. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21555. * 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
  21556. * When updating an instance, remember that only point positions can change, not the number of points.
  21557. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21558. */
  21559. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21560. var options = {
  21561. points: points,
  21562. dashSize: dashSize,
  21563. gapSize: gapSize,
  21564. dashNb: dashNb,
  21565. updatable: updatable,
  21566. instance: instance
  21567. };
  21568. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21569. };
  21570. /**
  21571. * Creates a polygon mesh.
  21572. * Please consider using the same method from the MeshBuilder class instead.
  21573. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21574. * 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.
  21575. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21576. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21577. * Remember you can only change the shape positions, not their number when updating a polygon.
  21578. */
  21579. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21580. var options = {
  21581. shape: shape,
  21582. holes: holes,
  21583. updatable: updatable,
  21584. sideOrientation: sideOrientation
  21585. };
  21586. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21587. };
  21588. /**
  21589. * Creates an extruded polygon mesh, with depth in the Y direction.
  21590. * Please consider using the same method from the MeshBuilder class instead.
  21591. */
  21592. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21593. var options = {
  21594. shape: shape,
  21595. holes: holes,
  21596. depth: depth,
  21597. updatable: updatable,
  21598. sideOrientation: sideOrientation
  21599. };
  21600. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21601. };
  21602. /**
  21603. * Creates an extruded shape mesh.
  21604. * 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.
  21605. * Please consider using the same method from the MeshBuilder class instead.
  21606. *
  21607. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21608. * 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
  21609. * extruded along the Z axis.
  21610. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21611. * 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.
  21612. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21613. * 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
  21614. * 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
  21615. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21616. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21617. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21618. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21619. */
  21620. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21621. var options = {
  21622. shape: shape,
  21623. path: path,
  21624. scale: scale,
  21625. rotation: rotation,
  21626. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21627. sideOrientation: sideOrientation,
  21628. instance: instance,
  21629. updatable: updatable
  21630. };
  21631. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21632. };
  21633. /**
  21634. * Creates an custom extruded shape mesh.
  21635. * 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.
  21636. * Please consider using the same method from the MeshBuilder class instead.
  21637. *
  21638. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21639. * 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
  21640. * extruded along the Z axis.
  21641. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21642. * 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
  21643. * and the distance of this point from the begining of the path :
  21644. * ```javascript
  21645. * var rotationFunction = function(i, distance) {
  21646. * // do things
  21647. * return rotationValue; }
  21648. * ```
  21649. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21650. * 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
  21651. * and the distance of this point from the begining of the path :
  21652. * ```javascript
  21653. * var scaleFunction = function(i, distance) {
  21654. * // do things
  21655. * return scaleValue;}
  21656. * ```
  21657. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21658. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21659. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21660. * 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
  21661. * 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
  21662. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21663. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21666. */
  21667. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21668. var options = {
  21669. shape: shape,
  21670. path: path,
  21671. scaleFunction: scaleFunction,
  21672. rotationFunction: rotationFunction,
  21673. ribbonCloseArray: ribbonCloseArray,
  21674. ribbonClosePath: ribbonClosePath,
  21675. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21676. sideOrientation: sideOrientation,
  21677. instance: instance,
  21678. updatable: updatable
  21679. };
  21680. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21681. };
  21682. /**
  21683. * Creates lathe mesh.
  21684. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21685. * Please consider using the same method from the MeshBuilder class instead.
  21686. * 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
  21687. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21688. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21689. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21693. */
  21694. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21695. var options = {
  21696. shape: shape,
  21697. radius: radius,
  21698. tessellation: tessellation,
  21699. sideOrientation: sideOrientation,
  21700. updatable: updatable
  21701. };
  21702. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21703. };
  21704. /**
  21705. * Creates a plane mesh.
  21706. * Please consider using the same method from the MeshBuilder class instead.
  21707. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21709. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21711. */
  21712. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21713. var options = {
  21714. size: size,
  21715. width: size,
  21716. height: size,
  21717. sideOrientation: sideOrientation,
  21718. updatable: updatable
  21719. };
  21720. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21721. };
  21722. /**
  21723. * Creates a ground mesh.
  21724. * Please consider using the same method from the MeshBuilder class instead.
  21725. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21726. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21727. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21728. */
  21729. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21730. var options = {
  21731. width: width,
  21732. height: height,
  21733. subdivisions: subdivisions,
  21734. updatable: updatable
  21735. };
  21736. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21737. };
  21738. /**
  21739. * Creates a tiled ground mesh.
  21740. * Please consider using the same method from the MeshBuilder class instead.
  21741. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21742. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21743. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21744. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21745. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21746. * numbers of subdivisions on the ground width and height of each tile.
  21747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21748. */
  21749. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21750. var options = {
  21751. xmin: xmin,
  21752. zmin: zmin,
  21753. xmax: xmax,
  21754. zmax: zmax,
  21755. subdivisions: subdivisions,
  21756. precision: precision,
  21757. updatable: updatable
  21758. };
  21759. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21760. };
  21761. /**
  21762. * Creates a ground mesh from a height map.
  21763. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21764. * Please consider using the same method from the MeshBuilder class instead.
  21765. * The parameter `url` sets the URL of the height map image resource.
  21766. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21767. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21768. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21769. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21770. * 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).
  21771. * This function is passed the newly built mesh :
  21772. * ```javascript
  21773. * function(mesh) { // do things
  21774. * return; }
  21775. * ```
  21776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21777. */
  21778. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21779. var options = {
  21780. width: width,
  21781. height: height,
  21782. subdivisions: subdivisions,
  21783. minHeight: minHeight,
  21784. maxHeight: maxHeight,
  21785. updatable: updatable,
  21786. onReady: onReady
  21787. };
  21788. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21789. };
  21790. /**
  21791. * Creates a tube mesh.
  21792. * 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.
  21793. * Please consider using the same method from the MeshBuilder class instead.
  21794. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21795. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21796. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21797. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21798. * 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.
  21799. * It must return a radius value (positive float) :
  21800. * ```javascript
  21801. * var radiusFunction = function(i, distance) {
  21802. * // do things
  21803. * return radius; }
  21804. * ```
  21805. * 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
  21806. * 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
  21807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21810. */
  21811. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21812. var options = {
  21813. path: path,
  21814. radius: radius,
  21815. tessellation: tessellation,
  21816. radiusFunction: radiusFunction,
  21817. arc: 1,
  21818. cap: cap,
  21819. updatable: updatable,
  21820. sideOrientation: sideOrientation,
  21821. instance: instance
  21822. };
  21823. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21824. };
  21825. /**
  21826. * Creates a polyhedron mesh.
  21827. * Please consider using the same method from the MeshBuilder class instead.
  21828. * 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
  21829. * to choose the wanted type.
  21830. * The parameter `size` (positive float, default 1) sets the polygon size.
  21831. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21832. * 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`.
  21833. * 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
  21834. * 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)`).
  21835. * 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
  21836. * 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.
  21837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21840. */
  21841. Mesh.CreatePolyhedron = function (name, options, scene) {
  21842. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21843. };
  21844. /**
  21845. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21846. * Please consider using the same method from the MeshBuilder class instead.
  21847. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21848. * 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`).
  21849. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21850. * 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.
  21851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21852. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21854. */
  21855. Mesh.CreateIcoSphere = function (name, options, scene) {
  21856. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21857. };
  21858. /**
  21859. * Creates a decal mesh.
  21860. * Please consider using the same method from the MeshBuilder class instead.
  21861. * 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.
  21862. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21863. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21864. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21865. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21866. */
  21867. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21868. var options = {
  21869. position: position,
  21870. normal: normal,
  21871. size: size,
  21872. angle: angle
  21873. };
  21874. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21875. };
  21876. // Skeletons
  21877. /**
  21878. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21879. */
  21880. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21881. var source;
  21882. if (!this._sourcePositions) {
  21883. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21884. this._sourcePositions = new Float32Array(source);
  21885. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21886. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21887. }
  21888. }
  21889. return this._sourcePositions;
  21890. };
  21891. /**
  21892. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21893. */
  21894. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21895. var source;
  21896. if (!this._sourceNormals) {
  21897. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21898. this._sourceNormals = new Float32Array(source);
  21899. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21900. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21901. }
  21902. }
  21903. return this._sourceNormals;
  21904. };
  21905. /**
  21906. * Updates the vertex buffer by applying transformation from the bones.
  21907. * Returns the Mesh.
  21908. *
  21909. * @param {skeleton} skeleton to apply
  21910. */
  21911. Mesh.prototype.applySkeleton = function (skeleton) {
  21912. if (!this.geometry) {
  21913. return this;
  21914. }
  21915. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21916. return this;
  21917. }
  21918. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21919. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21920. return this;
  21921. }
  21922. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21923. return this;
  21924. }
  21925. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21926. return this;
  21927. }
  21928. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21929. return this;
  21930. }
  21931. if (!this._sourcePositions) {
  21932. var submeshes = this.subMeshes.slice();
  21933. this.setPositionsForCPUSkinning();
  21934. this.subMeshes = submeshes;
  21935. }
  21936. if (!this._sourceNormals) {
  21937. this.setNormalsForCPUSkinning();
  21938. }
  21939. // positionsData checks for not being Float32Array will only pass at most once
  21940. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21941. if (!(positionsData instanceof Float32Array)) {
  21942. positionsData = new Float32Array(positionsData);
  21943. }
  21944. // normalsData checks for not being Float32Array will only pass at most once
  21945. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21946. if (!(normalsData instanceof Float32Array)) {
  21947. normalsData = new Float32Array(normalsData);
  21948. }
  21949. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21950. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21951. var needExtras = this.numBoneInfluencers > 4;
  21952. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21953. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21954. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21955. var tempVector3 = BABYLON.Vector3.Zero();
  21956. var finalMatrix = new BABYLON.Matrix();
  21957. var tempMatrix = new BABYLON.Matrix();
  21958. var matWeightIdx = 0;
  21959. var inf;
  21960. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21961. var weight;
  21962. for (inf = 0; inf < 4; inf++) {
  21963. weight = matricesWeightsData[matWeightIdx + inf];
  21964. if (weight > 0) {
  21965. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21966. finalMatrix.addToSelf(tempMatrix);
  21967. }
  21968. else
  21969. break;
  21970. }
  21971. if (needExtras) {
  21972. for (inf = 0; inf < 4; inf++) {
  21973. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21974. if (weight > 0) {
  21975. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21976. finalMatrix.addToSelf(tempMatrix);
  21977. }
  21978. else
  21979. break;
  21980. }
  21981. }
  21982. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21983. tempVector3.toArray(positionsData, index);
  21984. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21985. tempVector3.toArray(normalsData, index);
  21986. finalMatrix.reset();
  21987. }
  21988. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21989. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21990. return this;
  21991. };
  21992. // Tools
  21993. /**
  21994. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21995. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21996. */
  21997. Mesh.MinMax = function (meshes) {
  21998. var minVector = null;
  21999. var maxVector = null;
  22000. meshes.forEach(function (mesh, index, array) {
  22001. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22002. if (!minVector) {
  22003. minVector = boundingBox.minimumWorld;
  22004. maxVector = boundingBox.maximumWorld;
  22005. }
  22006. else {
  22007. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22008. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22009. }
  22010. });
  22011. return {
  22012. min: minVector,
  22013. max: maxVector
  22014. };
  22015. };
  22016. /**
  22017. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22018. */
  22019. Mesh.Center = function (meshesOrMinMaxVector) {
  22020. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22021. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22022. };
  22023. /**
  22024. * Merge the array of meshes into a single mesh for performance reasons.
  22025. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22026. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22027. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22028. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22029. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22030. */
  22031. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22032. if (disposeSource === void 0) { disposeSource = true; }
  22033. var index;
  22034. if (!allow32BitsIndices) {
  22035. var totalVertices = 0;
  22036. // Counting vertices
  22037. for (index = 0; index < meshes.length; index++) {
  22038. if (meshes[index]) {
  22039. totalVertices += meshes[index].getTotalVertices();
  22040. if (totalVertices > 65536) {
  22041. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22042. return null;
  22043. }
  22044. }
  22045. }
  22046. }
  22047. // Merge
  22048. var vertexData;
  22049. var otherVertexData;
  22050. var indiceArray = new Array();
  22051. var source;
  22052. for (index = 0; index < meshes.length; index++) {
  22053. if (meshes[index]) {
  22054. meshes[index].computeWorldMatrix(true);
  22055. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22056. otherVertexData.transform(meshes[index].getWorldMatrix());
  22057. if (vertexData) {
  22058. vertexData.merge(otherVertexData);
  22059. }
  22060. else {
  22061. vertexData = otherVertexData;
  22062. source = meshes[index];
  22063. }
  22064. if (subdivideWithSubMeshes) {
  22065. indiceArray.push(meshes[index].getTotalIndices());
  22066. }
  22067. }
  22068. }
  22069. if (!meshSubclass) {
  22070. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22071. }
  22072. vertexData.applyToMesh(meshSubclass);
  22073. // Setting properties
  22074. meshSubclass.material = source.material;
  22075. meshSubclass.checkCollisions = source.checkCollisions;
  22076. // Cleaning
  22077. if (disposeSource) {
  22078. for (index = 0; index < meshes.length; index++) {
  22079. if (meshes[index]) {
  22080. meshes[index].dispose();
  22081. }
  22082. }
  22083. }
  22084. // Subdivide
  22085. if (subdivideWithSubMeshes) {
  22086. //-- Suppresions du submesh global
  22087. meshSubclass.releaseSubMeshes();
  22088. index = 0;
  22089. var offset = 0;
  22090. //-- aplique la subdivision en fonction du tableau d'indices
  22091. while (index < indiceArray.length) {
  22092. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22093. offset += indiceArray[index];
  22094. index++;
  22095. }
  22096. }
  22097. return meshSubclass;
  22098. };
  22099. return Mesh;
  22100. }(BABYLON.AbstractMesh));
  22101. // Consts
  22102. Mesh._FRONTSIDE = 0;
  22103. Mesh._BACKSIDE = 1;
  22104. Mesh._DOUBLESIDE = 2;
  22105. Mesh._DEFAULTSIDE = 0;
  22106. Mesh._NO_CAP = 0;
  22107. Mesh._CAP_START = 1;
  22108. Mesh._CAP_END = 2;
  22109. Mesh._CAP_ALL = 3;
  22110. BABYLON.Mesh = Mesh;
  22111. })(BABYLON || (BABYLON = {}));
  22112. //# sourceMappingURL=babylon.mesh.js.map
  22113. var BABYLON;
  22114. (function (BABYLON) {
  22115. var SubMesh = (function () {
  22116. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22117. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22118. this.materialIndex = materialIndex;
  22119. this.verticesStart = verticesStart;
  22120. this.verticesCount = verticesCount;
  22121. this.indexStart = indexStart;
  22122. this.indexCount = indexCount;
  22123. this._renderId = 0;
  22124. this._mesh = mesh;
  22125. this._renderingMesh = renderingMesh || mesh;
  22126. mesh.subMeshes.push(this);
  22127. this._trianglePlanes = [];
  22128. this._id = mesh.subMeshes.length - 1;
  22129. if (createBoundingBox) {
  22130. this.refreshBoundingInfo();
  22131. mesh.computeWorldMatrix(true);
  22132. }
  22133. }
  22134. Object.defineProperty(SubMesh.prototype, "effect", {
  22135. get: function () {
  22136. return this._materialEffect;
  22137. },
  22138. enumerable: true,
  22139. configurable: true
  22140. });
  22141. SubMesh.prototype.setEffect = function (effect, defines) {
  22142. if (this._materialEffect === effect) {
  22143. return;
  22144. }
  22145. this._materialDefines = defines;
  22146. this._materialEffect = effect;
  22147. };
  22148. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22149. get: function () {
  22150. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22151. },
  22152. enumerable: true,
  22153. configurable: true
  22154. });
  22155. /**
  22156. * Returns the submesh BoudingInfo object.
  22157. */
  22158. SubMesh.prototype.getBoundingInfo = function () {
  22159. if (this.IsGlobal) {
  22160. return this._mesh.getBoundingInfo();
  22161. }
  22162. return this._boundingInfo;
  22163. };
  22164. /**
  22165. * Sets the submesh BoundingInfo.
  22166. * Return the SubMesh.
  22167. */
  22168. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22169. this._boundingInfo = boundingInfo;
  22170. return this;
  22171. };
  22172. /**
  22173. * Returns the mesh of the current submesh.
  22174. */
  22175. SubMesh.prototype.getMesh = function () {
  22176. return this._mesh;
  22177. };
  22178. /**
  22179. * Returns the rendering mesh of the submesh.
  22180. */
  22181. SubMesh.prototype.getRenderingMesh = function () {
  22182. return this._renderingMesh;
  22183. };
  22184. /**
  22185. * Returns the submesh material.
  22186. */
  22187. SubMesh.prototype.getMaterial = function () {
  22188. var rootMaterial = this._renderingMesh.material;
  22189. if (rootMaterial && rootMaterial.getSubMaterial) {
  22190. var multiMaterial = rootMaterial;
  22191. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22192. if (this._currentMaterial !== effectiveMaterial) {
  22193. this._currentMaterial = effectiveMaterial;
  22194. if (this._materialDefines) {
  22195. this._materialDefines.markAllAsDirty();
  22196. }
  22197. }
  22198. return effectiveMaterial;
  22199. }
  22200. if (!rootMaterial) {
  22201. return this._mesh.getScene().defaultMaterial;
  22202. }
  22203. return rootMaterial;
  22204. };
  22205. // Methods
  22206. /**
  22207. * Sets a new updated BoundingInfo object to the submesh.
  22208. * Returns the SubMesh.
  22209. */
  22210. SubMesh.prototype.refreshBoundingInfo = function () {
  22211. this._lastColliderWorldVertices = null;
  22212. if (this.IsGlobal) {
  22213. return;
  22214. }
  22215. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22216. if (!data) {
  22217. this._boundingInfo = this._mesh._boundingInfo;
  22218. return;
  22219. }
  22220. var indices = this._renderingMesh.getIndices();
  22221. var extend;
  22222. //is this the only submesh?
  22223. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22224. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22225. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22226. }
  22227. else {
  22228. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22229. }
  22230. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22231. return this;
  22232. };
  22233. SubMesh.prototype._checkCollision = function (collider) {
  22234. return this.getBoundingInfo()._checkCollision(collider);
  22235. };
  22236. /**
  22237. * Updates the submesh BoundingInfo.
  22238. * Returns the Submesh.
  22239. */
  22240. SubMesh.prototype.updateBoundingInfo = function (world) {
  22241. if (!this.getBoundingInfo()) {
  22242. this.refreshBoundingInfo();
  22243. }
  22244. this.getBoundingInfo().update(world);
  22245. return this;
  22246. };
  22247. /**
  22248. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22249. * Boolean returned.
  22250. */
  22251. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22252. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22253. };
  22254. /**
  22255. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22256. * Boolean returned.
  22257. */
  22258. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22259. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22260. };
  22261. /**
  22262. * Renders the submesh.
  22263. * Returns it.
  22264. */
  22265. SubMesh.prototype.render = function (enableAlphaMode) {
  22266. this._renderingMesh.render(this, enableAlphaMode);
  22267. return this;
  22268. };
  22269. /**
  22270. * Returns a new Index Buffer.
  22271. * Type returned : WebGLBuffer.
  22272. */
  22273. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22274. if (!this._linesIndexBuffer) {
  22275. var linesIndices = [];
  22276. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22277. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22278. }
  22279. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22280. this.linesIndexCount = linesIndices.length;
  22281. }
  22282. return this._linesIndexBuffer;
  22283. };
  22284. /**
  22285. * True is the passed Ray intersects the submesh bounding box.
  22286. * Boolean returned.
  22287. */
  22288. SubMesh.prototype.canIntersects = function (ray) {
  22289. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22290. };
  22291. /**
  22292. * Returns an object IntersectionInfo.
  22293. */
  22294. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22295. var intersectInfo = null;
  22296. // LineMesh first as it's also a Mesh...
  22297. if (this._mesh instanceof BABYLON.LinesMesh) {
  22298. var lineMesh = this._mesh;
  22299. // Line test
  22300. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22301. var p0 = positions[indices[index]];
  22302. var p1 = positions[indices[index + 1]];
  22303. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22304. if (length < 0) {
  22305. continue;
  22306. }
  22307. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22308. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22309. if (fastCheck) {
  22310. break;
  22311. }
  22312. }
  22313. }
  22314. }
  22315. else {
  22316. // Triangles test
  22317. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22318. var p0 = positions[indices[index]];
  22319. var p1 = positions[indices[index + 1]];
  22320. var p2 = positions[indices[index + 2]];
  22321. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22322. if (currentIntersectInfo) {
  22323. if (currentIntersectInfo.distance < 0) {
  22324. continue;
  22325. }
  22326. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22327. intersectInfo = currentIntersectInfo;
  22328. intersectInfo.faceId = index / 3;
  22329. if (fastCheck) {
  22330. break;
  22331. }
  22332. }
  22333. }
  22334. }
  22335. }
  22336. return intersectInfo;
  22337. };
  22338. // Clone
  22339. /**
  22340. * Creates a new Submesh from the passed Mesh.
  22341. */
  22342. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22343. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22344. if (!this.IsGlobal) {
  22345. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22346. }
  22347. return result;
  22348. };
  22349. // Dispose
  22350. /**
  22351. * Disposes the Submesh.
  22352. * Returns nothing.
  22353. */
  22354. SubMesh.prototype.dispose = function () {
  22355. if (this._linesIndexBuffer) {
  22356. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22357. this._linesIndexBuffer = null;
  22358. }
  22359. // Remove from mesh
  22360. var index = this._mesh.subMeshes.indexOf(this);
  22361. this._mesh.subMeshes.splice(index, 1);
  22362. };
  22363. // Statics
  22364. /**
  22365. * Creates a new Submesh from the passed parameters :
  22366. * - materialIndex (integer) : the index of the main mesh material.
  22367. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22368. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22369. * - mesh (Mesh) : the main mesh to create the submesh from.
  22370. * - renderingMesh (optional Mesh) : rendering mesh.
  22371. */
  22372. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22373. var minVertexIndex = Number.MAX_VALUE;
  22374. var maxVertexIndex = -Number.MAX_VALUE;
  22375. renderingMesh = renderingMesh || mesh;
  22376. var indices = renderingMesh.getIndices();
  22377. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22378. var vertexIndex = indices[index];
  22379. if (vertexIndex < minVertexIndex)
  22380. minVertexIndex = vertexIndex;
  22381. if (vertexIndex > maxVertexIndex)
  22382. maxVertexIndex = vertexIndex;
  22383. }
  22384. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22385. };
  22386. return SubMesh;
  22387. }());
  22388. BABYLON.SubMesh = SubMesh;
  22389. })(BABYLON || (BABYLON = {}));
  22390. //# sourceMappingURL=babylon.subMesh.js.map
  22391. var BABYLON;
  22392. (function (BABYLON) {
  22393. var EffectFallbacks = (function () {
  22394. function EffectFallbacks() {
  22395. this._defines = {};
  22396. this._currentRank = 32;
  22397. this._maxRank = -1;
  22398. }
  22399. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22400. if (!this._defines[rank]) {
  22401. if (rank < this._currentRank) {
  22402. this._currentRank = rank;
  22403. }
  22404. if (rank > this._maxRank) {
  22405. this._maxRank = rank;
  22406. }
  22407. this._defines[rank] = new Array();
  22408. }
  22409. this._defines[rank].push(define);
  22410. };
  22411. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22412. this._meshRank = rank;
  22413. this._mesh = mesh;
  22414. if (rank < this._currentRank) {
  22415. this._currentRank = rank;
  22416. }
  22417. if (rank > this._maxRank) {
  22418. this._maxRank = rank;
  22419. }
  22420. };
  22421. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22422. get: function () {
  22423. return this._currentRank <= this._maxRank;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22429. // First we try to switch to CPU skinning
  22430. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22431. this._mesh.computeBonesUsingShaders = false;
  22432. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22433. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22434. var scene = this._mesh.getScene();
  22435. for (var index = 0; index < scene.meshes.length; index++) {
  22436. var otherMesh = scene.meshes[index];
  22437. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22438. otherMesh.computeBonesUsingShaders = false;
  22439. }
  22440. }
  22441. }
  22442. else {
  22443. var currentFallbacks = this._defines[this._currentRank];
  22444. if (currentFallbacks) {
  22445. for (var index = 0; index < currentFallbacks.length; index++) {
  22446. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22447. }
  22448. }
  22449. this._currentRank++;
  22450. }
  22451. return currentDefines;
  22452. };
  22453. return EffectFallbacks;
  22454. }());
  22455. BABYLON.EffectFallbacks = EffectFallbacks;
  22456. var EffectCreationOptions = (function () {
  22457. function EffectCreationOptions() {
  22458. }
  22459. return EffectCreationOptions;
  22460. }());
  22461. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22462. var Effect = (function () {
  22463. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22464. var _this = this;
  22465. this.uniqueId = 0;
  22466. this._uniformBuffersNames = {};
  22467. this._isReady = false;
  22468. this._compilationError = "";
  22469. this._valueCache = {};
  22470. this.name = baseName;
  22471. if (attributesNamesOrOptions.attributes) {
  22472. var options = attributesNamesOrOptions;
  22473. this._engine = uniformsNamesOrEngine;
  22474. this._attributesNames = options.attributes;
  22475. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22476. this._samplers = options.samplers;
  22477. this.defines = options.defines;
  22478. this.onError = options.onError;
  22479. this.onCompiled = options.onCompiled;
  22480. this._fallbacks = options.fallbacks;
  22481. this._indexParameters = options.indexParameters;
  22482. if (options.uniformBuffersNames) {
  22483. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22484. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22485. }
  22486. }
  22487. }
  22488. else {
  22489. this._engine = engine;
  22490. this.defines = defines;
  22491. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22492. this._samplers = samplers;
  22493. this._attributesNames = attributesNamesOrOptions;
  22494. this.onError = onError;
  22495. this.onCompiled = onCompiled;
  22496. this._indexParameters = indexParameters;
  22497. this._fallbacks = fallbacks;
  22498. }
  22499. this.uniqueId = Effect._uniqueIdSeed++;
  22500. var vertexSource;
  22501. var fragmentSource;
  22502. if (baseName.vertexElement) {
  22503. vertexSource = document.getElementById(baseName.vertexElement);
  22504. if (!vertexSource) {
  22505. vertexSource = baseName.vertexElement;
  22506. }
  22507. }
  22508. else {
  22509. vertexSource = baseName.vertex || baseName;
  22510. }
  22511. if (baseName.fragmentElement) {
  22512. fragmentSource = document.getElementById(baseName.fragmentElement);
  22513. if (!fragmentSource) {
  22514. fragmentSource = baseName.fragmentElement;
  22515. }
  22516. }
  22517. else {
  22518. fragmentSource = baseName.fragment || baseName;
  22519. }
  22520. this._loadVertexShader(vertexSource, function (vertexCode) {
  22521. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22522. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22523. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22524. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22525. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22526. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22527. });
  22528. });
  22529. });
  22530. });
  22531. });
  22532. });
  22533. }
  22534. Object.defineProperty(Effect.prototype, "key", {
  22535. get: function () {
  22536. return this._key;
  22537. },
  22538. enumerable: true,
  22539. configurable: true
  22540. });
  22541. // Properties
  22542. Effect.prototype.isReady = function () {
  22543. return this._isReady;
  22544. };
  22545. Effect.prototype.getProgram = function () {
  22546. return this._program;
  22547. };
  22548. Effect.prototype.getAttributesNames = function () {
  22549. return this._attributesNames;
  22550. };
  22551. Effect.prototype.getAttributeLocation = function (index) {
  22552. return this._attributes[index];
  22553. };
  22554. Effect.prototype.getAttributeLocationByName = function (name) {
  22555. var index = this._attributesNames.indexOf(name);
  22556. return this._attributes[index];
  22557. };
  22558. Effect.prototype.getAttributesCount = function () {
  22559. return this._attributes.length;
  22560. };
  22561. Effect.prototype.getUniformIndex = function (uniformName) {
  22562. return this._uniformsNames.indexOf(uniformName);
  22563. };
  22564. Effect.prototype.getUniform = function (uniformName) {
  22565. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22566. };
  22567. Effect.prototype.getSamplers = function () {
  22568. return this._samplers;
  22569. };
  22570. Effect.prototype.getCompilationError = function () {
  22571. return this._compilationError;
  22572. };
  22573. Effect.prototype.getVertexShaderSource = function () {
  22574. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22575. };
  22576. Effect.prototype.getFragmentShaderSource = function () {
  22577. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22578. };
  22579. // Methods
  22580. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22581. // DOM element ?
  22582. if (vertex instanceof HTMLElement) {
  22583. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22584. callback(vertexCode);
  22585. return;
  22586. }
  22587. // Base64 encoded ?
  22588. if (vertex.substr(0, 7) === "base64:") {
  22589. var vertexBinary = window.atob(vertex.substr(7));
  22590. callback(vertexBinary);
  22591. return;
  22592. }
  22593. // Is in local store ?
  22594. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22595. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22596. return;
  22597. }
  22598. var vertexShaderUrl;
  22599. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22600. vertexShaderUrl = vertex;
  22601. }
  22602. else {
  22603. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22604. }
  22605. // Vertex shader
  22606. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22607. };
  22608. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22609. // DOM element ?
  22610. if (fragment instanceof HTMLElement) {
  22611. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22612. callback(fragmentCode);
  22613. return;
  22614. }
  22615. // Base64 encoded ?
  22616. if (fragment.substr(0, 7) === "base64:") {
  22617. var fragmentBinary = window.atob(fragment.substr(7));
  22618. callback(fragmentBinary);
  22619. return;
  22620. }
  22621. // Is in local store ?
  22622. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22623. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22624. return;
  22625. }
  22626. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22627. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22628. return;
  22629. }
  22630. var fragmentShaderUrl;
  22631. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22632. fragmentShaderUrl = fragment;
  22633. }
  22634. else {
  22635. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22636. }
  22637. // Fragment shader
  22638. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22639. };
  22640. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22641. // Rebuild shaders source code
  22642. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22643. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22644. vertexCode = prefix + vertexCode;
  22645. fragmentCode = prefix + fragmentCode;
  22646. // Number lines of shaders source code
  22647. var i = 2;
  22648. var regex = /\n/gm;
  22649. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22650. i = 2;
  22651. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22652. // Dump shaders name and formatted source code
  22653. if (this.name.vertexElement) {
  22654. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22655. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22656. }
  22657. else if (this.name.vertex) {
  22658. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22659. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22660. }
  22661. else {
  22662. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22663. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22664. }
  22665. };
  22666. ;
  22667. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22668. var preparedSourceCode = this._processPrecision(sourceCode);
  22669. if (this._engine.webGLVersion == 1) {
  22670. callback(preparedSourceCode);
  22671. return;
  22672. }
  22673. // Already converted
  22674. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22675. callback(preparedSourceCode.replace("#version 300 es", ""));
  22676. return;
  22677. }
  22678. // Remove extensions
  22679. // #extension GL_OES_standard_derivatives : enable
  22680. // #extension GL_EXT_shader_texture_lod : enable
  22681. // #extension GL_EXT_frag_depth : enable
  22682. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22683. var result = preparedSourceCode.replace(regex, "");
  22684. // Migrate to GLSL v300
  22685. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22686. result = result.replace(/attribute[ \t]/g, "in ");
  22687. result = result.replace(/[ \t]attribute/g, " in");
  22688. if (isFragment) {
  22689. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22690. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22691. result = result.replace(/texture2D\(/g, "texture(");
  22692. result = result.replace(/textureCube\(/g, "texture(");
  22693. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22694. result = result.replace(/gl_FragColor/g, "glFragColor");
  22695. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22696. }
  22697. callback(result);
  22698. };
  22699. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22700. var _this = this;
  22701. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22702. var match = regex.exec(sourceCode);
  22703. var returnValue = new String(sourceCode);
  22704. while (match != null) {
  22705. var includeFile = match[1];
  22706. // Uniform declaration
  22707. if (includeFile.indexOf("__decl__") !== -1) {
  22708. includeFile = includeFile.replace(/__decl__/, "");
  22709. if (this._engine.webGLVersion != 1) {
  22710. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22711. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22712. }
  22713. includeFile = includeFile + "Declaration";
  22714. }
  22715. if (Effect.IncludesShadersStore[includeFile]) {
  22716. // Substitution
  22717. var includeContent = Effect.IncludesShadersStore[includeFile];
  22718. if (match[2]) {
  22719. var splits = match[3].split(",");
  22720. for (var index = 0; index < splits.length; index += 2) {
  22721. var source = new RegExp(splits[index], "g");
  22722. var dest = splits[index + 1];
  22723. includeContent = includeContent.replace(source, dest);
  22724. }
  22725. }
  22726. if (match[4]) {
  22727. var indexString = match[5];
  22728. if (indexString.indexOf("..") !== -1) {
  22729. var indexSplits = indexString.split("..");
  22730. var minIndex = parseInt(indexSplits[0]);
  22731. var maxIndex = parseInt(indexSplits[1]);
  22732. var sourceIncludeContent = includeContent.slice(0);
  22733. includeContent = "";
  22734. if (isNaN(maxIndex)) {
  22735. maxIndex = this._indexParameters[indexSplits[1]];
  22736. }
  22737. for (var i = minIndex; i < maxIndex; i++) {
  22738. if (this._engine.webGLVersion === 1) {
  22739. // Ubo replacement
  22740. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22741. return p1 + "{X}";
  22742. });
  22743. }
  22744. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22745. }
  22746. }
  22747. else {
  22748. if (this._engine.webGLVersion === 1) {
  22749. // Ubo replacement
  22750. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22751. return p1 + "{X}";
  22752. });
  22753. }
  22754. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22755. }
  22756. }
  22757. // Replace
  22758. returnValue = returnValue.replace(match[0], includeContent);
  22759. }
  22760. else {
  22761. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22762. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22763. Effect.IncludesShadersStore[includeFile] = fileContent;
  22764. _this._processIncludes(returnValue, callback);
  22765. });
  22766. return;
  22767. }
  22768. match = regex.exec(sourceCode);
  22769. }
  22770. callback(returnValue);
  22771. };
  22772. Effect.prototype._processPrecision = function (source) {
  22773. if (source.indexOf("precision highp float") === -1) {
  22774. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22775. source = "precision mediump float;\n" + source;
  22776. }
  22777. else {
  22778. source = "precision highp float;\n" + source;
  22779. }
  22780. }
  22781. else {
  22782. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22783. source = source.replace("precision highp float", "precision mediump float");
  22784. }
  22785. }
  22786. return source;
  22787. };
  22788. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22789. try {
  22790. var engine = this._engine;
  22791. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22792. if (engine.webGLVersion > 1) {
  22793. for (var name in this._uniformBuffersNames) {
  22794. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22795. }
  22796. }
  22797. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22798. this._attributes = engine.getAttributes(this._program, attributesNames);
  22799. var index;
  22800. for (index = 0; index < this._samplers.length; index++) {
  22801. var sampler = this.getUniform(this._samplers[index]);
  22802. if (sampler == null) {
  22803. this._samplers.splice(index, 1);
  22804. index--;
  22805. }
  22806. }
  22807. engine.bindSamplers(this);
  22808. this._compilationError = "";
  22809. this._isReady = true;
  22810. if (this.onCompiled) {
  22811. this.onCompiled(this);
  22812. }
  22813. }
  22814. catch (e) {
  22815. this._compilationError = e.message;
  22816. // Let's go through fallbacks then
  22817. BABYLON.Tools.Error("Unable to compile effect:");
  22818. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22819. return " " + uniform;
  22820. }));
  22821. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22822. return " " + attribute;
  22823. }));
  22824. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22825. BABYLON.Tools.Error("Error: " + this._compilationError);
  22826. if (fallbacks && fallbacks.isMoreFallbacks) {
  22827. BABYLON.Tools.Error("Trying next fallback.");
  22828. defines = fallbacks.reduce(defines);
  22829. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22830. }
  22831. else {
  22832. if (this.onError) {
  22833. this.onError(this, this._compilationError);
  22834. }
  22835. }
  22836. }
  22837. };
  22838. Object.defineProperty(Effect.prototype, "isSupported", {
  22839. get: function () {
  22840. return this._compilationError === "";
  22841. },
  22842. enumerable: true,
  22843. configurable: true
  22844. });
  22845. Effect.prototype._bindTexture = function (channel, texture) {
  22846. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22847. };
  22848. Effect.prototype.setTexture = function (channel, texture) {
  22849. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22850. };
  22851. Effect.prototype.setTextureArray = function (channel, textures) {
  22852. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22853. var initialPos = this._samplers.indexOf(channel);
  22854. for (var index = 1; index < textures.length; index++) {
  22855. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22856. }
  22857. }
  22858. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22859. };
  22860. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22861. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22862. };
  22863. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22864. var cache = this._valueCache[uniformName];
  22865. var flag = matrix.updateFlag;
  22866. if (cache !== undefined && cache === flag) {
  22867. return false;
  22868. }
  22869. this._valueCache[uniformName] = flag;
  22870. return true;
  22871. };
  22872. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22873. var cache = this._valueCache[uniformName];
  22874. if (!cache) {
  22875. cache = [x, y];
  22876. this._valueCache[uniformName] = cache;
  22877. return true;
  22878. }
  22879. var changed = false;
  22880. if (cache[0] !== x) {
  22881. cache[0] = x;
  22882. changed = true;
  22883. }
  22884. if (cache[1] !== y) {
  22885. cache[1] = y;
  22886. changed = true;
  22887. }
  22888. return changed;
  22889. };
  22890. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22891. var cache = this._valueCache[uniformName];
  22892. if (!cache) {
  22893. cache = [x, y, z];
  22894. this._valueCache[uniformName] = cache;
  22895. return true;
  22896. }
  22897. var changed = false;
  22898. if (cache[0] !== x) {
  22899. cache[0] = x;
  22900. changed = true;
  22901. }
  22902. if (cache[1] !== y) {
  22903. cache[1] = y;
  22904. changed = true;
  22905. }
  22906. if (cache[2] !== z) {
  22907. cache[2] = z;
  22908. changed = true;
  22909. }
  22910. return changed;
  22911. };
  22912. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22913. var cache = this._valueCache[uniformName];
  22914. if (!cache) {
  22915. cache = [x, y, z, w];
  22916. this._valueCache[uniformName] = cache;
  22917. return true;
  22918. }
  22919. var changed = false;
  22920. if (cache[0] !== x) {
  22921. cache[0] = x;
  22922. changed = true;
  22923. }
  22924. if (cache[1] !== y) {
  22925. cache[1] = y;
  22926. changed = true;
  22927. }
  22928. if (cache[2] !== z) {
  22929. cache[2] = z;
  22930. changed = true;
  22931. }
  22932. if (cache[3] !== w) {
  22933. cache[3] = w;
  22934. changed = true;
  22935. }
  22936. return changed;
  22937. };
  22938. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22939. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22940. return;
  22941. }
  22942. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22943. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22944. };
  22945. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22946. this._engine.bindUniformBlock(this._program, blockName, index);
  22947. };
  22948. Effect.prototype.setIntArray = function (uniformName, array) {
  22949. this._valueCache[uniformName] = null;
  22950. this._engine.setIntArray(this.getUniform(uniformName), array);
  22951. return this;
  22952. };
  22953. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22954. this._valueCache[uniformName] = null;
  22955. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22956. return this;
  22957. };
  22958. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22959. this._valueCache[uniformName] = null;
  22960. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22961. return this;
  22962. };
  22963. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22964. this._valueCache[uniformName] = null;
  22965. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22966. return this;
  22967. };
  22968. Effect.prototype.setFloatArray = function (uniformName, array) {
  22969. this._valueCache[uniformName] = null;
  22970. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22971. return this;
  22972. };
  22973. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22974. this._valueCache[uniformName] = null;
  22975. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22976. return this;
  22977. };
  22978. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22979. this._valueCache[uniformName] = null;
  22980. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22981. return this;
  22982. };
  22983. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22984. this._valueCache[uniformName] = null;
  22985. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22986. return this;
  22987. };
  22988. Effect.prototype.setArray = function (uniformName, array) {
  22989. this._valueCache[uniformName] = null;
  22990. this._engine.setArray(this.getUniform(uniformName), array);
  22991. return this;
  22992. };
  22993. Effect.prototype.setArray2 = function (uniformName, array) {
  22994. this._valueCache[uniformName] = null;
  22995. this._engine.setArray2(this.getUniform(uniformName), array);
  22996. return this;
  22997. };
  22998. Effect.prototype.setArray3 = function (uniformName, array) {
  22999. this._valueCache[uniformName] = null;
  23000. this._engine.setArray3(this.getUniform(uniformName), array);
  23001. return this;
  23002. };
  23003. Effect.prototype.setArray4 = function (uniformName, array) {
  23004. this._valueCache[uniformName] = null;
  23005. this._engine.setArray4(this.getUniform(uniformName), array);
  23006. return this;
  23007. };
  23008. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23009. if (!matrices) {
  23010. return;
  23011. }
  23012. this._valueCache[uniformName] = null;
  23013. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23014. return this;
  23015. };
  23016. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23017. if (this._cacheMatrix(uniformName, matrix)) {
  23018. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23019. }
  23020. return this;
  23021. };
  23022. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23023. this._valueCache[uniformName] = null;
  23024. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23025. return this;
  23026. };
  23027. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23028. this._valueCache[uniformName] = null;
  23029. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23030. return this;
  23031. };
  23032. Effect.prototype.setFloat = function (uniformName, value) {
  23033. var cache = this._valueCache[uniformName];
  23034. if (cache !== undefined && cache === value)
  23035. return this;
  23036. this._valueCache[uniformName] = value;
  23037. this._engine.setFloat(this.getUniform(uniformName), value);
  23038. return this;
  23039. };
  23040. Effect.prototype.setBool = function (uniformName, bool) {
  23041. var cache = this._valueCache[uniformName];
  23042. if (cache !== undefined && cache === bool)
  23043. return this;
  23044. this._valueCache[uniformName] = bool;
  23045. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23046. return this;
  23047. };
  23048. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23049. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23050. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23051. }
  23052. return this;
  23053. };
  23054. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23055. if (this._cacheFloat2(uniformName, x, y)) {
  23056. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23057. }
  23058. return this;
  23059. };
  23060. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23061. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23062. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23063. }
  23064. return this;
  23065. };
  23066. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23067. if (this._cacheFloat3(uniformName, x, y, z)) {
  23068. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23069. }
  23070. return this;
  23071. };
  23072. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23073. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23074. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23075. }
  23076. return this;
  23077. };
  23078. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23079. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23080. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23081. }
  23082. return this;
  23083. };
  23084. Effect.prototype.setColor3 = function (uniformName, color3) {
  23085. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23086. this._engine.setColor3(this.getUniform(uniformName), color3);
  23087. }
  23088. return this;
  23089. };
  23090. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23091. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23092. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23093. }
  23094. return this;
  23095. };
  23096. Effect.prototype._recombineShader = function (node) {
  23097. if (node.define) {
  23098. if (node.condition) {
  23099. var defineIndex = this.defines.indexOf("#define " + node.define);
  23100. if (defineIndex === -1) {
  23101. return null;
  23102. }
  23103. var nextComma = this.defines.indexOf("\n", defineIndex);
  23104. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23105. var condition = defineValue + node.condition;
  23106. if (!eval(condition)) {
  23107. return null;
  23108. }
  23109. }
  23110. else if (node.ndef) {
  23111. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23112. return null;
  23113. }
  23114. }
  23115. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23116. return null;
  23117. }
  23118. }
  23119. var result = "";
  23120. for (var index = 0; index < node.children.length; index++) {
  23121. var line = node.children[index];
  23122. if (line.children) {
  23123. var combined = this._recombineShader(line);
  23124. if (combined !== null) {
  23125. result += combined + "\r\n";
  23126. }
  23127. continue;
  23128. }
  23129. if (line.length > 0) {
  23130. result += line + "\r\n";
  23131. }
  23132. }
  23133. return result;
  23134. };
  23135. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23136. var root = {
  23137. children: []
  23138. };
  23139. var currentNode = root;
  23140. var lines = shaderString.split("\n");
  23141. for (var index = 0; index < lines.length; index++) {
  23142. var line = lines[index].trim();
  23143. // #ifdef
  23144. var pos = line.indexOf("#ifdef ");
  23145. if (pos !== -1) {
  23146. var define = line.substr(pos + 7);
  23147. var newNode = {
  23148. condition: null,
  23149. ndef: false,
  23150. define: define,
  23151. children: [],
  23152. parent: currentNode
  23153. };
  23154. currentNode.children.push(newNode);
  23155. currentNode = newNode;
  23156. continue;
  23157. }
  23158. // #ifndef
  23159. var pos = line.indexOf("#ifndef ");
  23160. if (pos !== -1) {
  23161. var define = line.substr(pos + 8);
  23162. newNode = {
  23163. condition: null,
  23164. define: define,
  23165. ndef: true,
  23166. children: [],
  23167. parent: currentNode
  23168. };
  23169. currentNode.children.push(newNode);
  23170. currentNode = newNode;
  23171. continue;
  23172. }
  23173. // #if
  23174. var pos = line.indexOf("#if ");
  23175. if (pos !== -1) {
  23176. var define = line.substr(pos + 4).trim();
  23177. var conditionPos = define.indexOf(" ");
  23178. newNode = {
  23179. condition: define.substr(conditionPos + 1),
  23180. define: define.substr(0, conditionPos),
  23181. ndef: false,
  23182. children: [],
  23183. parent: currentNode
  23184. };
  23185. currentNode.children.push(newNode);
  23186. currentNode = newNode;
  23187. continue;
  23188. }
  23189. // #endif
  23190. pos = line.indexOf("#endif");
  23191. if (pos !== -1) {
  23192. currentNode = currentNode.parent;
  23193. continue;
  23194. }
  23195. currentNode.children.push(line);
  23196. }
  23197. // Recombine
  23198. return this._recombineShader(root);
  23199. };
  23200. return Effect;
  23201. }());
  23202. Effect._uniqueIdSeed = 0;
  23203. Effect._baseCache = {};
  23204. // Statics
  23205. Effect.ShadersStore = {};
  23206. Effect.IncludesShadersStore = {};
  23207. BABYLON.Effect = Effect;
  23208. })(BABYLON || (BABYLON = {}));
  23209. //# sourceMappingURL=babylon.effect.js.map
  23210. var BABYLON;
  23211. (function (BABYLON) {
  23212. var MaterialHelper = (function () {
  23213. function MaterialHelper() {
  23214. }
  23215. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23216. if (defines._areMiscDirty) {
  23217. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23218. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23219. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23220. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23221. }
  23222. };
  23223. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23224. var changed = false;
  23225. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23226. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23227. changed = true;
  23228. }
  23229. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23230. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23231. changed = true;
  23232. }
  23233. if (defines["INSTANCES"] !== useInstances) {
  23234. defines["INSTANCES"] = useInstances;
  23235. changed = true;
  23236. }
  23237. if (changed) {
  23238. defines.markAsUnprocessed();
  23239. }
  23240. };
  23241. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23242. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23243. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23244. return;
  23245. }
  23246. defines._normals = defines._needNormals;
  23247. defines._uvs = defines._needUVs;
  23248. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23249. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23250. defines["TANGENT"] = true;
  23251. }
  23252. if (defines._needUVs) {
  23253. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23254. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23255. }
  23256. else {
  23257. defines["UV1"] = false;
  23258. defines["UV2"] = false;
  23259. }
  23260. if (useVertexColor) {
  23261. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23262. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23263. }
  23264. if (useBones) {
  23265. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23266. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23267. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23268. }
  23269. else {
  23270. defines["NUM_BONE_INFLUENCERS"] = 0;
  23271. defines["BonesPerMesh"] = 0;
  23272. }
  23273. }
  23274. if (useMorphTargets) {
  23275. if (mesh.morphTargetManager) {
  23276. var manager = mesh.morphTargetManager;
  23277. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23278. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23279. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23280. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23281. }
  23282. else {
  23283. defines["MORPHTARGETS_TANGENT"] = false;
  23284. defines["MORPHTARGETS_NORMAL"] = false;
  23285. defines["MORPHTARGETS"] = false;
  23286. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23287. }
  23288. }
  23289. };
  23290. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23291. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23292. if (disableLighting === void 0) { disableLighting = false; }
  23293. if (!defines._areLightsDirty) {
  23294. return defines._needNormals;
  23295. }
  23296. var lightIndex = 0;
  23297. var needNormals = false;
  23298. var needRebuild = false;
  23299. var lightmapMode = false;
  23300. var shadowEnabled = false;
  23301. var specularEnabled = false;
  23302. if (scene.lightsEnabled && !disableLighting) {
  23303. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23304. var light = _a[_i];
  23305. needNormals = true;
  23306. if (defines["LIGHT" + lightIndex] === undefined) {
  23307. needRebuild = true;
  23308. }
  23309. defines["LIGHT" + lightIndex] = true;
  23310. defines["SPOTLIGHT" + lightIndex] = false;
  23311. defines["HEMILIGHT" + lightIndex] = false;
  23312. defines["POINTLIGHT" + lightIndex] = false;
  23313. defines["DIRLIGHT" + lightIndex] = false;
  23314. var type;
  23315. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23316. type = "SPOTLIGHT" + lightIndex;
  23317. }
  23318. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23319. type = "HEMILIGHT" + lightIndex;
  23320. }
  23321. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23322. type = "POINTLIGHT" + lightIndex;
  23323. }
  23324. else {
  23325. type = "DIRLIGHT" + lightIndex;
  23326. }
  23327. defines[type] = true;
  23328. // Specular
  23329. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23330. specularEnabled = true;
  23331. }
  23332. // Shadows
  23333. defines["SHADOW" + lightIndex] = false;
  23334. defines["SHADOWPCF" + lightIndex] = false;
  23335. defines["SHADOWESM" + lightIndex] = false;
  23336. defines["SHADOWCUBE" + lightIndex] = false;
  23337. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23338. var shadowGenerator = light.getShadowGenerator();
  23339. if (shadowGenerator) {
  23340. shadowEnabled = true;
  23341. shadowGenerator.prepareDefines(defines, lightIndex);
  23342. }
  23343. }
  23344. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23345. lightmapMode = true;
  23346. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23347. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23348. }
  23349. else {
  23350. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23351. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23352. }
  23353. lightIndex++;
  23354. if (lightIndex === maxSimultaneousLights)
  23355. break;
  23356. }
  23357. }
  23358. defines["SPECULARTERM"] = specularEnabled;
  23359. defines["SHADOWS"] = shadowEnabled;
  23360. // Resetting all other lights if any
  23361. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23362. if (defines["LIGHT" + index] !== undefined) {
  23363. defines["LIGHT" + index] = false;
  23364. }
  23365. }
  23366. var caps = scene.getEngine().getCaps();
  23367. if (defines["SHADOWFLOAT"] === undefined) {
  23368. needRebuild = true;
  23369. }
  23370. defines["SHADOWFLOAT"] = shadowEnabled &&
  23371. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23372. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23373. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23374. if (needRebuild) {
  23375. defines.rebuild();
  23376. }
  23377. return needNormals;
  23378. };
  23379. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23380. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23381. var uniformsList, uniformBuffersList, samplersList, defines;
  23382. if (uniformsListOrOptions.uniformsNames) {
  23383. var options = uniformsListOrOptions;
  23384. uniformsList = options.uniformsNames;
  23385. uniformBuffersList = options.uniformBuffersNames;
  23386. samplersList = options.samplers;
  23387. defines = options.defines;
  23388. maxSimultaneousLights = options.maxSimultaneousLights;
  23389. }
  23390. else {
  23391. uniformsList = uniformsListOrOptions;
  23392. }
  23393. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23394. if (!defines["LIGHT" + lightIndex]) {
  23395. break;
  23396. }
  23397. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23398. if (uniformBuffersList) {
  23399. uniformBuffersList.push("Light" + lightIndex);
  23400. }
  23401. samplersList.push("shadowSampler" + lightIndex);
  23402. }
  23403. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23404. uniformsList.push("morphTargetInfluences");
  23405. }
  23406. };
  23407. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23408. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23409. if (!defines["SHADOWS"]) {
  23410. return;
  23411. }
  23412. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23413. if (!defines["LIGHT" + lightIndex]) {
  23414. break;
  23415. }
  23416. if (lightIndex > 0) {
  23417. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23418. }
  23419. if (defines["SHADOW" + lightIndex]) {
  23420. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23421. }
  23422. if (defines["SHADOWPCF" + lightIndex]) {
  23423. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23424. }
  23425. if (defines["SHADOWESM" + lightIndex]) {
  23426. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23427. }
  23428. }
  23429. };
  23430. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23431. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23432. if (influencers > 0) {
  23433. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23434. var manager = mesh.morphTargetManager;
  23435. var normal = manager.supportsNormals && defines["NORMAL"];
  23436. var tangent = manager.supportsTangents && defines["TANGENT"];
  23437. for (var index = 0; index < influencers; index++) {
  23438. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23439. if (normal) {
  23440. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23441. }
  23442. if (tangent) {
  23443. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23444. }
  23445. if (attribs.length > maxAttributesCount) {
  23446. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23447. }
  23448. }
  23449. }
  23450. };
  23451. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23452. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23453. fallbacks.addCPUSkinningFallback(0, mesh);
  23454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23456. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23457. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23458. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23459. }
  23460. }
  23461. };
  23462. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23463. if (defines["INSTANCES"]) {
  23464. attribs.push("world0");
  23465. attribs.push("world1");
  23466. attribs.push("world2");
  23467. attribs.push("world3");
  23468. }
  23469. };
  23470. // Bindings
  23471. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23472. if (light.shadowEnabled && mesh.receiveShadows) {
  23473. var shadowGenerator = light.getShadowGenerator();
  23474. if (shadowGenerator) {
  23475. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23476. }
  23477. }
  23478. return depthValuesAlreadySet;
  23479. };
  23480. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23481. light.transferToEffect(effect, lightIndex + "");
  23482. };
  23483. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23484. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23485. var lightIndex = 0;
  23486. var depthValuesAlreadySet = false;
  23487. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23488. var light = _a[_i];
  23489. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23490. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23491. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23492. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23493. if (defines["SPECULARTERM"]) {
  23494. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23495. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23496. }
  23497. // Shadows
  23498. if (scene.shadowsEnabled) {
  23499. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23500. }
  23501. light._uniformBuffer.update();
  23502. lightIndex++;
  23503. if (lightIndex === maxSimultaneousLights)
  23504. break;
  23505. }
  23506. };
  23507. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23508. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23509. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23510. effect.setColor3("vFogColor", scene.fogColor);
  23511. }
  23512. };
  23513. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23514. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23515. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23516. if (matrices) {
  23517. effect.setMatrices("mBones", matrices);
  23518. }
  23519. }
  23520. };
  23521. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23522. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23523. return;
  23524. }
  23525. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23526. };
  23527. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23528. if (defines["LOGARITHMICDEPTH"]) {
  23529. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23530. }
  23531. };
  23532. MaterialHelper.BindClipPlane = function (effect, scene) {
  23533. if (scene.clipPlane) {
  23534. var clipPlane = scene.clipPlane;
  23535. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23536. }
  23537. };
  23538. return MaterialHelper;
  23539. }());
  23540. BABYLON.MaterialHelper = MaterialHelper;
  23541. })(BABYLON || (BABYLON = {}));
  23542. //# sourceMappingURL=babylon.materialHelper.js.map
  23543. var BABYLON;
  23544. (function (BABYLON) {
  23545. var MaterialDefines = (function () {
  23546. function MaterialDefines() {
  23547. this._isDirty = true;
  23548. this._areLightsDirty = true;
  23549. this._areAttributesDirty = true;
  23550. this._areTexturesDirty = true;
  23551. this._areFresnelDirty = true;
  23552. this._areMiscDirty = true;
  23553. this._normals = false;
  23554. this._uvs = false;
  23555. this._needNormals = false;
  23556. this._needUVs = false;
  23557. }
  23558. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23559. get: function () {
  23560. return this._isDirty;
  23561. },
  23562. enumerable: true,
  23563. configurable: true
  23564. });
  23565. MaterialDefines.prototype.markAsProcessed = function () {
  23566. this._isDirty = false;
  23567. this._areAttributesDirty = false;
  23568. this._areTexturesDirty = false;
  23569. this._areFresnelDirty = false;
  23570. this._areLightsDirty = false;
  23571. this._areMiscDirty = false;
  23572. };
  23573. MaterialDefines.prototype.markAsUnprocessed = function () {
  23574. this._isDirty = true;
  23575. };
  23576. MaterialDefines.prototype.markAllAsDirty = function () {
  23577. this._areTexturesDirty = true;
  23578. this._areAttributesDirty = true;
  23579. this._areLightsDirty = true;
  23580. this._areFresnelDirty = true;
  23581. this._areMiscDirty = true;
  23582. this._isDirty = true;
  23583. };
  23584. MaterialDefines.prototype.markAsLightDirty = function () {
  23585. this._areLightsDirty = true;
  23586. this._isDirty = true;
  23587. };
  23588. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23589. this._areAttributesDirty = true;
  23590. this._isDirty = true;
  23591. };
  23592. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23593. this._areTexturesDirty = true;
  23594. this._isDirty = true;
  23595. };
  23596. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23597. this._areFresnelDirty = true;
  23598. this._isDirty = true;
  23599. };
  23600. MaterialDefines.prototype.markAsMiscDirty = function () {
  23601. this._areMiscDirty = true;
  23602. this._isDirty = true;
  23603. };
  23604. MaterialDefines.prototype.rebuild = function () {
  23605. if (this._keys) {
  23606. delete this._keys;
  23607. }
  23608. this._keys = [];
  23609. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23610. var key = _a[_i];
  23611. if (key[0] === "_") {
  23612. continue;
  23613. }
  23614. this._keys.push(key);
  23615. }
  23616. };
  23617. MaterialDefines.prototype.isEqual = function (other) {
  23618. if (this._keys.length !== other._keys.length) {
  23619. return false;
  23620. }
  23621. for (var index = 0; index < this._keys.length; index++) {
  23622. var prop = this._keys[index];
  23623. if (this[prop] !== other[prop]) {
  23624. return false;
  23625. }
  23626. }
  23627. return true;
  23628. };
  23629. MaterialDefines.prototype.cloneTo = function (other) {
  23630. if (this._keys.length !== other._keys.length) {
  23631. other._keys = this._keys.slice(0);
  23632. }
  23633. for (var index = 0; index < this._keys.length; index++) {
  23634. var prop = this._keys[index];
  23635. other[prop] = this[prop];
  23636. }
  23637. };
  23638. MaterialDefines.prototype.reset = function () {
  23639. for (var index = 0; index < this._keys.length; index++) {
  23640. var prop = this._keys[index];
  23641. if (typeof (this[prop]) === "number") {
  23642. this[prop] = 0;
  23643. }
  23644. else {
  23645. this[prop] = false;
  23646. }
  23647. }
  23648. };
  23649. MaterialDefines.prototype.toString = function () {
  23650. var result = "";
  23651. for (var index = 0; index < this._keys.length; index++) {
  23652. var prop = this._keys[index];
  23653. var value = this[prop];
  23654. if (typeof (value) === "number") {
  23655. result += "#define " + prop + " " + this[prop] + "\n";
  23656. }
  23657. else if (value) {
  23658. result += "#define " + prop + "\n";
  23659. }
  23660. }
  23661. return result;
  23662. };
  23663. return MaterialDefines;
  23664. }());
  23665. BABYLON.MaterialDefines = MaterialDefines;
  23666. var Material = (function () {
  23667. function Material(name, scene, doNotAdd) {
  23668. this.checkReadyOnEveryCall = false;
  23669. this.checkReadyOnlyOnce = false;
  23670. this.state = "";
  23671. this.alpha = 1.0;
  23672. this._backFaceCulling = true;
  23673. this.doNotSerialize = false;
  23674. this.storeEffectOnSubMeshes = false;
  23675. /**
  23676. * An event triggered when the material is disposed.
  23677. * @type {BABYLON.Observable}
  23678. */
  23679. this.onDisposeObservable = new BABYLON.Observable();
  23680. /**
  23681. * An event triggered when the material is bound.
  23682. * @type {BABYLON.Observable}
  23683. */
  23684. this.onBindObservable = new BABYLON.Observable();
  23685. /**
  23686. * An event triggered when the material is unbound.
  23687. * @type {BABYLON.Observable}
  23688. */
  23689. this.onUnBindObservable = new BABYLON.Observable();
  23690. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23691. this.disableDepthWrite = false;
  23692. this._fogEnabled = true;
  23693. this.pointSize = 1.0;
  23694. this.zOffset = 0;
  23695. this._wasPreviouslyReady = false;
  23696. this._fillMode = Material.TriangleFillMode;
  23697. this.name = name;
  23698. this.id = name;
  23699. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23700. if (this._scene.useRightHandedSystem) {
  23701. this.sideOrientation = Material.ClockWiseSideOrientation;
  23702. }
  23703. else {
  23704. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23705. }
  23706. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23707. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23708. if (!doNotAdd) {
  23709. this._scene.materials.push(this);
  23710. }
  23711. }
  23712. Object.defineProperty(Material, "TriangleFillMode", {
  23713. get: function () {
  23714. return Material._TriangleFillMode;
  23715. },
  23716. enumerable: true,
  23717. configurable: true
  23718. });
  23719. Object.defineProperty(Material, "WireFrameFillMode", {
  23720. get: function () {
  23721. return Material._WireFrameFillMode;
  23722. },
  23723. enumerable: true,
  23724. configurable: true
  23725. });
  23726. Object.defineProperty(Material, "PointFillMode", {
  23727. get: function () {
  23728. return Material._PointFillMode;
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23734. get: function () {
  23735. return Material._ClockWiseSideOrientation;
  23736. },
  23737. enumerable: true,
  23738. configurable: true
  23739. });
  23740. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23741. get: function () {
  23742. return Material._CounterClockWiseSideOrientation;
  23743. },
  23744. enumerable: true,
  23745. configurable: true
  23746. });
  23747. Object.defineProperty(Material, "TextureDirtyFlag", {
  23748. get: function () {
  23749. return Material._TextureDirtyFlag;
  23750. },
  23751. enumerable: true,
  23752. configurable: true
  23753. });
  23754. Object.defineProperty(Material, "LightDirtyFlag", {
  23755. get: function () {
  23756. return Material._LightDirtyFlag;
  23757. },
  23758. enumerable: true,
  23759. configurable: true
  23760. });
  23761. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23762. get: function () {
  23763. return Material._FresnelDirtyFlag;
  23764. },
  23765. enumerable: true,
  23766. configurable: true
  23767. });
  23768. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23769. get: function () {
  23770. return Material._AttributesDirtyFlag;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. Object.defineProperty(Material, "MiscDirtyFlag", {
  23776. get: function () {
  23777. return Material._MiscDirtyFlag;
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23783. get: function () {
  23784. return this._backFaceCulling;
  23785. },
  23786. set: function (value) {
  23787. if (this._backFaceCulling === value) {
  23788. return;
  23789. }
  23790. this._backFaceCulling = value;
  23791. this.markAsDirty(Material.TextureDirtyFlag);
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. Object.defineProperty(Material.prototype, "onDispose", {
  23797. set: function (callback) {
  23798. if (this._onDisposeObserver) {
  23799. this.onDisposeObservable.remove(this._onDisposeObserver);
  23800. }
  23801. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23802. },
  23803. enumerable: true,
  23804. configurable: true
  23805. });
  23806. Object.defineProperty(Material.prototype, "onBind", {
  23807. set: function (callback) {
  23808. if (this._onBindObserver) {
  23809. this.onBindObservable.remove(this._onBindObserver);
  23810. }
  23811. this._onBindObserver = this.onBindObservable.add(callback);
  23812. },
  23813. enumerable: true,
  23814. configurable: true
  23815. });
  23816. Object.defineProperty(Material.prototype, "fogEnabled", {
  23817. get: function () {
  23818. return this._fogEnabled;
  23819. },
  23820. set: function (value) {
  23821. if (this._fogEnabled === value) {
  23822. return;
  23823. }
  23824. this._fogEnabled = value;
  23825. this.markAsDirty(Material.MiscDirtyFlag);
  23826. },
  23827. enumerable: true,
  23828. configurable: true
  23829. });
  23830. Object.defineProperty(Material.prototype, "wireframe", {
  23831. get: function () {
  23832. return this._fillMode === Material.WireFrameFillMode;
  23833. },
  23834. set: function (value) {
  23835. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23836. },
  23837. enumerable: true,
  23838. configurable: true
  23839. });
  23840. Object.defineProperty(Material.prototype, "pointsCloud", {
  23841. get: function () {
  23842. return this._fillMode === Material.PointFillMode;
  23843. },
  23844. set: function (value) {
  23845. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23846. },
  23847. enumerable: true,
  23848. configurable: true
  23849. });
  23850. Object.defineProperty(Material.prototype, "fillMode", {
  23851. get: function () {
  23852. return this._fillMode;
  23853. },
  23854. set: function (value) {
  23855. if (this._fillMode === value) {
  23856. return;
  23857. }
  23858. this._fillMode = value;
  23859. this.markAsDirty(Material.MiscDirtyFlag);
  23860. },
  23861. enumerable: true,
  23862. configurable: true
  23863. });
  23864. /**
  23865. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23866. * subclasses should override adding information pertainent to themselves
  23867. */
  23868. Material.prototype.toString = function (fullDetails) {
  23869. var ret = "Name: " + this.name;
  23870. if (fullDetails) {
  23871. }
  23872. return ret;
  23873. };
  23874. /**
  23875. * Child classes can use it to update shaders
  23876. */
  23877. Material.prototype.markAsDirty = function (flag) {
  23878. };
  23879. Material.prototype.getClassName = function () {
  23880. return "Material";
  23881. };
  23882. Object.defineProperty(Material.prototype, "isFrozen", {
  23883. get: function () {
  23884. return this.checkReadyOnlyOnce;
  23885. },
  23886. enumerable: true,
  23887. configurable: true
  23888. });
  23889. Material.prototype.freeze = function () {
  23890. this.checkReadyOnlyOnce = true;
  23891. };
  23892. Material.prototype.unfreeze = function () {
  23893. this.checkReadyOnlyOnce = false;
  23894. };
  23895. Material.prototype.isReady = function (mesh, useInstances) {
  23896. return true;
  23897. };
  23898. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23899. return false;
  23900. };
  23901. Material.prototype.getEffect = function () {
  23902. return this._effect;
  23903. };
  23904. Material.prototype.getScene = function () {
  23905. return this._scene;
  23906. };
  23907. Material.prototype.needAlphaBlending = function () {
  23908. return (this.alpha < 1.0);
  23909. };
  23910. Material.prototype.needAlphaTesting = function () {
  23911. return false;
  23912. };
  23913. Material.prototype.getAlphaTestTexture = function () {
  23914. return null;
  23915. };
  23916. Material.prototype.markDirty = function () {
  23917. this._wasPreviouslyReady = false;
  23918. };
  23919. Material.prototype._preBind = function (effect) {
  23920. var engine = this._scene.getEngine();
  23921. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23922. engine.enableEffect(effect ? effect : this._effect);
  23923. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23924. };
  23925. Material.prototype.bind = function (world, mesh) {
  23926. };
  23927. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23928. };
  23929. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23930. };
  23931. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23932. sceneUbo.bindToEffect(effect, "Scene");
  23933. };
  23934. Material.prototype.bindView = function (effect) {
  23935. if (!this._useUBO) {
  23936. effect.setMatrix("view", this.getScene().getViewMatrix());
  23937. }
  23938. else {
  23939. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23940. }
  23941. };
  23942. Material.prototype.bindViewProjection = function (effect) {
  23943. if (!this._useUBO) {
  23944. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23945. }
  23946. else {
  23947. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23948. }
  23949. };
  23950. Material.prototype._afterBind = function (mesh) {
  23951. this._scene._cachedMaterial = this;
  23952. this.onBindObservable.notifyObservers(mesh);
  23953. if (this.disableDepthWrite) {
  23954. var engine = this._scene.getEngine();
  23955. this._cachedDepthWriteState = engine.getDepthWrite();
  23956. engine.setDepthWrite(false);
  23957. }
  23958. };
  23959. Material.prototype.unbind = function () {
  23960. this.onUnBindObservable.notifyObservers(this);
  23961. if (this.disableDepthWrite) {
  23962. var engine = this._scene.getEngine();
  23963. engine.setDepthWrite(this._cachedDepthWriteState);
  23964. }
  23965. };
  23966. Material.prototype.clone = function (name) {
  23967. return null;
  23968. };
  23969. Material.prototype.getBindedMeshes = function () {
  23970. var result = new Array();
  23971. for (var index = 0; index < this._scene.meshes.length; index++) {
  23972. var mesh = this._scene.meshes[index];
  23973. if (mesh.material === this) {
  23974. result.push(mesh);
  23975. }
  23976. }
  23977. return result;
  23978. };
  23979. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23980. // Animations
  23981. this.getScene().stopAnimation(this);
  23982. // Remove from scene
  23983. var index = this._scene.materials.indexOf(this);
  23984. if (index >= 0) {
  23985. this._scene.materials.splice(index, 1);
  23986. }
  23987. // Remove from meshes
  23988. for (index = 0; index < this._scene.meshes.length; index++) {
  23989. var mesh = this._scene.meshes[index];
  23990. if (mesh.material === this) {
  23991. mesh.material = null;
  23992. if (mesh.geometry) {
  23993. var geometry = mesh.geometry;
  23994. if (this.storeEffectOnSubMeshes) {
  23995. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23996. var subMesh = _a[_i];
  23997. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23998. }
  23999. }
  24000. else {
  24001. geometry._releaseVertexArrayObject(this._effect);
  24002. }
  24003. }
  24004. }
  24005. }
  24006. this._uniformBuffer.dispose();
  24007. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24008. if (forceDisposeEffect && this._effect) {
  24009. if (this.storeEffectOnSubMeshes) {
  24010. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24011. var subMesh = _c[_b];
  24012. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24013. }
  24014. }
  24015. else {
  24016. this._scene.getEngine()._releaseEffect(this._effect);
  24017. }
  24018. this._effect = null;
  24019. }
  24020. // Callback
  24021. this.onDisposeObservable.notifyObservers(this);
  24022. this.onDisposeObservable.clear();
  24023. this.onBindObservable.clear();
  24024. this.onUnBindObservable.clear();
  24025. };
  24026. Material.prototype.serialize = function () {
  24027. return BABYLON.SerializationHelper.Serialize(this);
  24028. };
  24029. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24030. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24031. multiMaterial.id = parsedMultiMaterial.id;
  24032. if (BABYLON.Tags) {
  24033. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24034. }
  24035. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24036. var subMatId = parsedMultiMaterial.materials[matIndex];
  24037. if (subMatId) {
  24038. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24039. }
  24040. else {
  24041. multiMaterial.subMaterials.push(null);
  24042. }
  24043. }
  24044. return multiMaterial;
  24045. };
  24046. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24047. if (!parsedMaterial.customType) {
  24048. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24049. }
  24050. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24051. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24052. if (!BABYLON.LegacyPBRMaterial) {
  24053. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24054. return;
  24055. }
  24056. }
  24057. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24058. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24059. ;
  24060. };
  24061. return Material;
  24062. }());
  24063. Material._TriangleFillMode = 0;
  24064. Material._WireFrameFillMode = 1;
  24065. Material._PointFillMode = 2;
  24066. Material._ClockWiseSideOrientation = 0;
  24067. Material._CounterClockWiseSideOrientation = 1;
  24068. Material._TextureDirtyFlag = 1;
  24069. Material._LightDirtyFlag = 2;
  24070. Material._FresnelDirtyFlag = 4;
  24071. Material._AttributesDirtyFlag = 8;
  24072. Material._MiscDirtyFlag = 16;
  24073. __decorate([
  24074. BABYLON.serialize()
  24075. ], Material.prototype, "id", void 0);
  24076. __decorate([
  24077. BABYLON.serialize()
  24078. ], Material.prototype, "name", void 0);
  24079. __decorate([
  24080. BABYLON.serialize()
  24081. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24082. __decorate([
  24083. BABYLON.serialize()
  24084. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24085. __decorate([
  24086. BABYLON.serialize()
  24087. ], Material.prototype, "state", void 0);
  24088. __decorate([
  24089. BABYLON.serialize()
  24090. ], Material.prototype, "alpha", void 0);
  24091. __decorate([
  24092. BABYLON.serialize("backFaceCulling")
  24093. ], Material.prototype, "_backFaceCulling", void 0);
  24094. __decorate([
  24095. BABYLON.serialize()
  24096. ], Material.prototype, "sideOrientation", void 0);
  24097. __decorate([
  24098. BABYLON.serialize()
  24099. ], Material.prototype, "alphaMode", void 0);
  24100. __decorate([
  24101. BABYLON.serialize()
  24102. ], Material.prototype, "disableDepthWrite", void 0);
  24103. __decorate([
  24104. BABYLON.serialize("fogEnabled")
  24105. ], Material.prototype, "_fogEnabled", void 0);
  24106. __decorate([
  24107. BABYLON.serialize()
  24108. ], Material.prototype, "pointSize", void 0);
  24109. __decorate([
  24110. BABYLON.serialize()
  24111. ], Material.prototype, "zOffset", void 0);
  24112. __decorate([
  24113. BABYLON.serialize()
  24114. ], Material.prototype, "wireframe", null);
  24115. __decorate([
  24116. BABYLON.serialize()
  24117. ], Material.prototype, "pointsCloud", null);
  24118. __decorate([
  24119. BABYLON.serialize()
  24120. ], Material.prototype, "fillMode", null);
  24121. BABYLON.Material = Material;
  24122. })(BABYLON || (BABYLON = {}));
  24123. //# sourceMappingURL=babylon.material.js.map
  24124. var BABYLON;
  24125. (function (BABYLON) {
  24126. var UniformBuffer = (function () {
  24127. /**
  24128. * Uniform buffer objects.
  24129. *
  24130. * Handles blocks of uniform on the GPU.
  24131. *
  24132. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24133. *
  24134. * For more information, please refer to :
  24135. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24136. */
  24137. function UniformBuffer(engine, data, dynamic) {
  24138. this._engine = engine;
  24139. this._noUBO = engine.webGLVersion === 1;
  24140. this._dynamic = dynamic;
  24141. this._data = data || [];
  24142. this._uniformLocations = {};
  24143. this._uniformSizes = {};
  24144. this._uniformLocationPointer = 0;
  24145. this._needSync = false;
  24146. if (this._noUBO) {
  24147. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24148. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24149. this.updateFloat = this._updateFloatForEffect;
  24150. this.updateFloat2 = this._updateFloat2ForEffect;
  24151. this.updateFloat3 = this._updateFloat3ForEffect;
  24152. this.updateFloat4 = this._updateFloat4ForEffect;
  24153. this.updateMatrix = this._updateMatrixForEffect;
  24154. this.updateVector3 = this._updateVector3ForEffect;
  24155. this.updateVector4 = this._updateVector4ForEffect;
  24156. this.updateColor3 = this._updateColor3ForEffect;
  24157. this.updateColor4 = this._updateColor4ForEffect;
  24158. }
  24159. else {
  24160. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24161. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24162. this.updateFloat = this._updateFloatForUniform;
  24163. this.updateFloat2 = this._updateFloat2ForUniform;
  24164. this.updateFloat3 = this._updateFloat3ForUniform;
  24165. this.updateFloat4 = this._updateFloat4ForUniform;
  24166. this.updateMatrix = this._updateMatrixForUniform;
  24167. this.updateVector3 = this._updateVector3ForUniform;
  24168. this.updateVector4 = this._updateVector4ForUniform;
  24169. this.updateColor3 = this._updateColor3ForUniform;
  24170. this.updateColor4 = this._updateColor4ForUniform;
  24171. }
  24172. }
  24173. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24174. // Properties
  24175. /**
  24176. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24177. * or just falling back on setUniformXXX calls.
  24178. */
  24179. get: function () {
  24180. return !this._noUBO;
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24186. /**
  24187. * Indicates if the WebGL underlying uniform buffer is in sync
  24188. * with the javascript cache data.
  24189. */
  24190. get: function () {
  24191. return !this._needSync;
  24192. },
  24193. enumerable: true,
  24194. configurable: true
  24195. });
  24196. /**
  24197. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24198. * Also, a dynamic UniformBuffer will disable cache verification and always
  24199. * update the underlying WebGL uniform buffer to the GPU.
  24200. */
  24201. UniformBuffer.prototype.isDynamic = function () {
  24202. return this._dynamic;
  24203. };
  24204. /**
  24205. * The data cache on JS side.
  24206. */
  24207. UniformBuffer.prototype.getData = function () {
  24208. return this._bufferData;
  24209. };
  24210. /**
  24211. * The underlying WebGL Uniform buffer.
  24212. */
  24213. UniformBuffer.prototype.getBuffer = function () {
  24214. return this._buffer;
  24215. };
  24216. /**
  24217. * std140 layout specifies how to align data within an UBO structure.
  24218. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24219. * for specs.
  24220. */
  24221. UniformBuffer.prototype._fillAlignment = function (size) {
  24222. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24223. // and 4x4 matrices
  24224. // TODO : change if other types are used
  24225. var alignment;
  24226. if (size <= 2) {
  24227. alignment = size;
  24228. }
  24229. else {
  24230. alignment = 4;
  24231. }
  24232. if ((this._uniformLocationPointer % alignment) !== 0) {
  24233. var oldPointer = this._uniformLocationPointer;
  24234. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24235. var diff = this._uniformLocationPointer - oldPointer;
  24236. for (var i = 0; i < diff; i++) {
  24237. this._data.push(0);
  24238. }
  24239. }
  24240. };
  24241. /**
  24242. * Adds an uniform in the buffer.
  24243. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24244. * for the layout to be correct !
  24245. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24246. * @param {number|number[]} size Data size, or data directly.
  24247. */
  24248. UniformBuffer.prototype.addUniform = function (name, size) {
  24249. if (this._noUBO) {
  24250. return;
  24251. }
  24252. if (this._uniformLocations[name] !== undefined) {
  24253. // Already existing uniform
  24254. return;
  24255. }
  24256. // This function must be called in the order of the shader layout !
  24257. // size can be the size of the uniform, or data directly
  24258. var data;
  24259. if (size instanceof Array) {
  24260. data = size;
  24261. size = data.length;
  24262. }
  24263. else {
  24264. size = size;
  24265. data = [];
  24266. // Fill with zeros
  24267. for (var i = 0; i < size; i++) {
  24268. data.push(0);
  24269. }
  24270. }
  24271. this._fillAlignment(size);
  24272. this._uniformSizes[name] = size;
  24273. this._uniformLocations[name] = this._uniformLocationPointer;
  24274. this._uniformLocationPointer += size;
  24275. for (var i = 0; i < size; i++) {
  24276. this._data.push(data[i]);
  24277. }
  24278. this._needSync = true;
  24279. };
  24280. /**
  24281. * Wrapper for addUniform.
  24282. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24283. * @param {Matrix} mat A 4x4 matrix.
  24284. */
  24285. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24286. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24287. };
  24288. /**
  24289. * Wrapper for addUniform.
  24290. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24291. * @param {number} x
  24292. * @param {number} y
  24293. */
  24294. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24295. var temp = [x, y];
  24296. this.addUniform(name, temp);
  24297. };
  24298. /**
  24299. * Wrapper for addUniform.
  24300. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24301. * @param {number} x
  24302. * @param {number} y
  24303. * @param {number} z
  24304. */
  24305. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24306. var temp = [x, y, z];
  24307. this.addUniform(name, temp);
  24308. };
  24309. /**
  24310. * Wrapper for addUniform.
  24311. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24312. * @param {Color3} color
  24313. */
  24314. UniformBuffer.prototype.addColor3 = function (name, color) {
  24315. var temp = [];
  24316. color.toArray(temp);
  24317. this.addUniform(name, temp);
  24318. };
  24319. /**
  24320. * Wrapper for addUniform.
  24321. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24322. * @param {Color3} color
  24323. * @param {number} alpha
  24324. */
  24325. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24326. var temp = [];
  24327. color.toArray(temp);
  24328. temp.push(alpha);
  24329. this.addUniform(name, temp);
  24330. };
  24331. /**
  24332. * Wrapper for addUniform.
  24333. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24334. * @param {Vector3} vector
  24335. */
  24336. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24337. var temp = [];
  24338. vector.toArray(temp);
  24339. this.addUniform(name, temp);
  24340. };
  24341. /**
  24342. * Wrapper for addUniform.
  24343. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24344. */
  24345. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24346. this.addUniform(name, 12);
  24347. };
  24348. /**
  24349. * Wrapper for addUniform.
  24350. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24351. */
  24352. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24353. this.addUniform(name, 8);
  24354. };
  24355. /**
  24356. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24357. */
  24358. UniformBuffer.prototype.create = function () {
  24359. if (this._noUBO) {
  24360. return;
  24361. }
  24362. if (this._buffer) {
  24363. return; // nothing to do
  24364. }
  24365. // See spec, alignment must be filled as a vec4
  24366. this._fillAlignment(4);
  24367. this._bufferData = new Float32Array(this._data);
  24368. if (this._dynamic) {
  24369. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24370. }
  24371. else {
  24372. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24373. }
  24374. this._needSync = true;
  24375. };
  24376. /**
  24377. * Updates the WebGL Uniform Buffer on the GPU.
  24378. * If the `dynamic` flag is set to true, no cache comparison is done.
  24379. * Otherwise, the buffer will be updated only if the cache differs.
  24380. */
  24381. UniformBuffer.prototype.update = function () {
  24382. if (!this._buffer) {
  24383. this.create();
  24384. return;
  24385. }
  24386. if (!this._dynamic && !this._needSync) {
  24387. return;
  24388. }
  24389. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24390. this._needSync = false;
  24391. };
  24392. /**
  24393. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24394. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24395. * @param {number[]|Float32Array} data Flattened data
  24396. * @param {number} size Size of the data.
  24397. */
  24398. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24399. var location = this._uniformLocations[uniformName];
  24400. if (location === undefined) {
  24401. if (this._buffer) {
  24402. // Cannot add an uniform if the buffer is already created
  24403. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24404. return;
  24405. }
  24406. this.addUniform(uniformName, size);
  24407. location = this._uniformLocations[uniformName];
  24408. }
  24409. if (!this._buffer) {
  24410. this.create();
  24411. }
  24412. if (!this._dynamic) {
  24413. // Cache for static uniform buffers
  24414. var changed = false;
  24415. for (var i = 0; i < size; i++) {
  24416. if (this._bufferData[location + i] !== data[i]) {
  24417. changed = true;
  24418. this._bufferData[location + i] = data[i];
  24419. }
  24420. }
  24421. this._needSync = this._needSync || changed;
  24422. }
  24423. else {
  24424. // No cache for dynamic
  24425. for (var i = 0; i < size; i++) {
  24426. this._bufferData[location + i] = data[i];
  24427. }
  24428. }
  24429. };
  24430. // Update methods
  24431. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24432. // To match std140, matrix must be realigned
  24433. for (var i = 0; i < 3; i++) {
  24434. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24435. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24436. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24437. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24438. }
  24439. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24440. };
  24441. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24442. this._currentEffect.setMatrix3x3(name, matrix);
  24443. };
  24444. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24445. this._currentEffect.setMatrix2x2(name, matrix);
  24446. };
  24447. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24448. // To match std140, matrix must be realigned
  24449. for (var i = 0; i < 2; i++) {
  24450. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24451. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24452. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24453. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24454. }
  24455. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24456. };
  24457. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24458. this._currentEffect.setFloat(name, x);
  24459. };
  24460. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24461. UniformBuffer._tempBuffer[0] = x;
  24462. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24463. };
  24464. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24465. this._currentEffect.setFloat2(name, x, y);
  24466. };
  24467. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24468. UniformBuffer._tempBuffer[0] = x;
  24469. UniformBuffer._tempBuffer[1] = y;
  24470. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24471. };
  24472. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24473. if (suffix === void 0) { suffix = ""; }
  24474. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24475. };
  24476. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24477. if (suffix === void 0) { suffix = ""; }
  24478. UniformBuffer._tempBuffer[0] = x;
  24479. UniformBuffer._tempBuffer[1] = y;
  24480. UniformBuffer._tempBuffer[2] = z;
  24481. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24482. };
  24483. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24484. if (suffix === void 0) { suffix = ""; }
  24485. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24486. };
  24487. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24488. if (suffix === void 0) { suffix = ""; }
  24489. UniformBuffer._tempBuffer[0] = x;
  24490. UniformBuffer._tempBuffer[1] = y;
  24491. UniformBuffer._tempBuffer[2] = z;
  24492. UniformBuffer._tempBuffer[3] = w;
  24493. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24494. };
  24495. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24496. this._currentEffect.setMatrix(name, mat);
  24497. };
  24498. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24499. this.updateUniform(name, mat.toArray(), 16);
  24500. };
  24501. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24502. this._currentEffect.setVector3(name, vector);
  24503. };
  24504. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24505. vector.toArray(UniformBuffer._tempBuffer);
  24506. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24507. };
  24508. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24509. this._currentEffect.setVector4(name, vector);
  24510. };
  24511. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24512. vector.toArray(UniformBuffer._tempBuffer);
  24513. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24514. };
  24515. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24516. if (suffix === void 0) { suffix = ""; }
  24517. this._currentEffect.setColor3(name + suffix, color);
  24518. };
  24519. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24520. if (suffix === void 0) { suffix = ""; }
  24521. color.toArray(UniformBuffer._tempBuffer);
  24522. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24523. };
  24524. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24525. if (suffix === void 0) { suffix = ""; }
  24526. this._currentEffect.setColor4(name + suffix, color, alpha);
  24527. };
  24528. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24529. if (suffix === void 0) { suffix = ""; }
  24530. color.toArray(UniformBuffer._tempBuffer);
  24531. UniformBuffer._tempBuffer[3] = alpha;
  24532. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24533. };
  24534. /**
  24535. * Sets a sampler uniform on the effect.
  24536. * @param {string} name Name of the sampler.
  24537. * @param {Texture} texture
  24538. */
  24539. UniformBuffer.prototype.setTexture = function (name, texture) {
  24540. this._currentEffect.setTexture(name, texture);
  24541. };
  24542. /**
  24543. * Directly updates the value of the uniform in the cache AND on the GPU.
  24544. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24545. * @param {number[]|Float32Array} data Flattened data
  24546. */
  24547. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24548. this.updateUniform(uniformName, data, data.length);
  24549. this.update();
  24550. };
  24551. /**
  24552. * Binds this uniform buffer to an effect.
  24553. * @param {Effect} effect
  24554. * @param {string} name Name of the uniform block in the shader.
  24555. */
  24556. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24557. this._currentEffect = effect;
  24558. if (this._noUBO) {
  24559. return;
  24560. }
  24561. effect.bindUniformBuffer(this._buffer, name);
  24562. };
  24563. /**
  24564. * Disposes the uniform buffer.
  24565. */
  24566. UniformBuffer.prototype.dispose = function () {
  24567. if (!this._buffer) {
  24568. return;
  24569. }
  24570. if (this._engine._releaseBuffer(this._buffer)) {
  24571. this._buffer = null;
  24572. }
  24573. };
  24574. return UniformBuffer;
  24575. }());
  24576. // Pool for avoiding memory leaks
  24577. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24578. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24579. BABYLON.UniformBuffer = UniformBuffer;
  24580. })(BABYLON || (BABYLON = {}));
  24581. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24582. var BABYLON;
  24583. (function (BABYLON) {
  24584. var PushMaterial = (function (_super) {
  24585. __extends(PushMaterial, _super);
  24586. function PushMaterial(name, scene) {
  24587. var _this = _super.call(this, name, scene) || this;
  24588. _this.storeEffectOnSubMeshes = true;
  24589. return _this;
  24590. }
  24591. PushMaterial.prototype.getEffect = function () {
  24592. return this._activeEffect;
  24593. };
  24594. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24595. if (!mesh) {
  24596. return false;
  24597. }
  24598. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24599. return true;
  24600. }
  24601. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24602. };
  24603. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24604. this._activeEffect.setMatrix("world", world);
  24605. };
  24606. PushMaterial.prototype.bind = function (world, mesh) {
  24607. if (!mesh) {
  24608. return;
  24609. }
  24610. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24611. };
  24612. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24613. _super.prototype._afterBind.call(this, mesh);
  24614. this.getScene()._cachedEffect = effect;
  24615. };
  24616. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24617. if (visibility === void 0) { visibility = 0; }
  24618. return scene.isCachedMaterialValid(this, effect, visibility);
  24619. };
  24620. PushMaterial.prototype.markAsDirty = function (flag) {
  24621. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24622. this._markAllSubMeshesAsTexturesDirty();
  24623. }
  24624. if (flag & BABYLON.Material.LightDirtyFlag) {
  24625. this._markAllSubMeshesAsLightsDirty();
  24626. }
  24627. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24628. this._markAllSubMeshesAsFresnelDirty();
  24629. }
  24630. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24631. this._markAllSubMeshesAsAttributesDirty();
  24632. }
  24633. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24634. this._markAllSubMeshesAsMiscDirty();
  24635. }
  24636. };
  24637. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24638. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24639. var mesh = _a[_i];
  24640. if (!mesh.subMeshes) {
  24641. continue;
  24642. }
  24643. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24644. var subMesh = _c[_b];
  24645. if (subMesh.getMaterial() !== this) {
  24646. continue;
  24647. }
  24648. if (!subMesh._materialDefines) {
  24649. return;
  24650. }
  24651. func(subMesh._materialDefines);
  24652. }
  24653. }
  24654. };
  24655. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24656. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24657. };
  24658. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24659. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24660. };
  24661. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24662. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24663. };
  24664. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24665. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24666. };
  24667. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24668. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24669. };
  24670. return PushMaterial;
  24671. }(BABYLON.Material));
  24672. BABYLON.PushMaterial = PushMaterial;
  24673. })(BABYLON || (BABYLON = {}));
  24674. //# sourceMappingURL=babylon.pushMaterial.js.map
  24675. var BABYLON;
  24676. (function (BABYLON) {
  24677. var VertexData = (function () {
  24678. function VertexData() {
  24679. }
  24680. VertexData.prototype.set = function (data, kind) {
  24681. switch (kind) {
  24682. case BABYLON.VertexBuffer.PositionKind:
  24683. this.positions = data;
  24684. break;
  24685. case BABYLON.VertexBuffer.NormalKind:
  24686. this.normals = data;
  24687. break;
  24688. case BABYLON.VertexBuffer.TangentKind:
  24689. this.tangents = data;
  24690. break;
  24691. case BABYLON.VertexBuffer.UVKind:
  24692. this.uvs = data;
  24693. break;
  24694. case BABYLON.VertexBuffer.UV2Kind:
  24695. this.uvs2 = data;
  24696. break;
  24697. case BABYLON.VertexBuffer.UV3Kind:
  24698. this.uvs3 = data;
  24699. break;
  24700. case BABYLON.VertexBuffer.UV4Kind:
  24701. this.uvs4 = data;
  24702. break;
  24703. case BABYLON.VertexBuffer.UV5Kind:
  24704. this.uvs5 = data;
  24705. break;
  24706. case BABYLON.VertexBuffer.UV6Kind:
  24707. this.uvs6 = data;
  24708. break;
  24709. case BABYLON.VertexBuffer.ColorKind:
  24710. this.colors = data;
  24711. break;
  24712. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24713. this.matricesIndices = data;
  24714. break;
  24715. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24716. this.matricesWeights = data;
  24717. break;
  24718. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24719. this.matricesIndicesExtra = data;
  24720. break;
  24721. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24722. this.matricesWeightsExtra = data;
  24723. break;
  24724. }
  24725. };
  24726. /**
  24727. * Associates the vertexData to the passed Mesh.
  24728. * Sets it as updatable or not (default `false`).
  24729. * Returns the VertexData.
  24730. */
  24731. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24732. this._applyTo(mesh, updatable);
  24733. return this;
  24734. };
  24735. /**
  24736. * Associates the vertexData to the passed Geometry.
  24737. * Sets it as updatable or not (default `false`).
  24738. * Returns the VertexData.
  24739. */
  24740. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24741. this._applyTo(geometry, updatable);
  24742. return this;
  24743. };
  24744. /**
  24745. * Updates the associated mesh.
  24746. * Returns the VertexData.
  24747. */
  24748. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24749. this._update(mesh);
  24750. return this;
  24751. };
  24752. /**
  24753. * Updates the associated geometry.
  24754. * Returns the VertexData.
  24755. */
  24756. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24757. this._update(geometry);
  24758. return this;
  24759. };
  24760. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24761. if (this.positions) {
  24762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24763. }
  24764. if (this.normals) {
  24765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24766. }
  24767. if (this.tangents) {
  24768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24769. }
  24770. if (this.uvs) {
  24771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24772. }
  24773. if (this.uvs2) {
  24774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24775. }
  24776. if (this.uvs3) {
  24777. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24778. }
  24779. if (this.uvs4) {
  24780. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24781. }
  24782. if (this.uvs5) {
  24783. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24784. }
  24785. if (this.uvs6) {
  24786. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24787. }
  24788. if (this.colors) {
  24789. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24790. }
  24791. if (this.matricesIndices) {
  24792. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24793. }
  24794. if (this.matricesWeights) {
  24795. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24796. }
  24797. if (this.matricesIndicesExtra) {
  24798. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24799. }
  24800. if (this.matricesWeightsExtra) {
  24801. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24802. }
  24803. if (this.indices) {
  24804. meshOrGeometry.setIndices(this.indices);
  24805. }
  24806. return this;
  24807. };
  24808. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24809. if (this.positions) {
  24810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24811. }
  24812. if (this.normals) {
  24813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24814. }
  24815. if (this.tangents) {
  24816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24817. }
  24818. if (this.uvs) {
  24819. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24820. }
  24821. if (this.uvs2) {
  24822. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24823. }
  24824. if (this.uvs3) {
  24825. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24826. }
  24827. if (this.uvs4) {
  24828. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24829. }
  24830. if (this.uvs5) {
  24831. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24832. }
  24833. if (this.uvs6) {
  24834. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24835. }
  24836. if (this.colors) {
  24837. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24838. }
  24839. if (this.matricesIndices) {
  24840. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24841. }
  24842. if (this.matricesWeights) {
  24843. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24844. }
  24845. if (this.matricesIndicesExtra) {
  24846. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24847. }
  24848. if (this.matricesWeightsExtra) {
  24849. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24850. }
  24851. if (this.indices) {
  24852. meshOrGeometry.setIndices(this.indices);
  24853. }
  24854. return this;
  24855. };
  24856. /**
  24857. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24858. * Returns the VertexData.
  24859. */
  24860. VertexData.prototype.transform = function (matrix) {
  24861. var transformed = BABYLON.Vector3.Zero();
  24862. var index;
  24863. if (this.positions) {
  24864. var position = BABYLON.Vector3.Zero();
  24865. for (index = 0; index < this.positions.length; index += 3) {
  24866. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24867. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24868. this.positions[index] = transformed.x;
  24869. this.positions[index + 1] = transformed.y;
  24870. this.positions[index + 2] = transformed.z;
  24871. }
  24872. }
  24873. if (this.normals) {
  24874. var normal = BABYLON.Vector3.Zero();
  24875. for (index = 0; index < this.normals.length; index += 3) {
  24876. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24877. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24878. this.normals[index] = transformed.x;
  24879. this.normals[index + 1] = transformed.y;
  24880. this.normals[index + 2] = transformed.z;
  24881. }
  24882. }
  24883. if (this.tangents) {
  24884. var tangent = BABYLON.Vector4.Zero();
  24885. var tangentTransformed = BABYLON.Vector4.Zero();
  24886. for (index = 0; index < this.tangents.length; index += 4) {
  24887. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24888. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24889. this.tangents[index] = tangentTransformed.x;
  24890. this.tangents[index + 1] = tangentTransformed.y;
  24891. this.tangents[index + 2] = tangentTransformed.z;
  24892. this.tangents[index + 3] = tangentTransformed.w;
  24893. }
  24894. }
  24895. return this;
  24896. };
  24897. /**
  24898. * Merges the passed VertexData into the current one.
  24899. * Returns the modified VertexData.
  24900. */
  24901. VertexData.prototype.merge = function (other) {
  24902. if (other.indices) {
  24903. if (!this.indices) {
  24904. this.indices = [];
  24905. }
  24906. var offset = this.positions ? this.positions.length / 3 : 0;
  24907. for (var index = 0; index < other.indices.length; index++) {
  24908. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24909. this.indices.push(other.indices[index] + offset);
  24910. }
  24911. }
  24912. this.positions = this._mergeElement(this.positions, other.positions);
  24913. this.normals = this._mergeElement(this.normals, other.normals);
  24914. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24915. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24916. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24917. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24918. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24919. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24920. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24921. this.colors = this._mergeElement(this.colors, other.colors);
  24922. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24923. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24924. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24925. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24926. return this;
  24927. };
  24928. VertexData.prototype._mergeElement = function (source, other) {
  24929. if (!other)
  24930. return source;
  24931. if (!source)
  24932. return other;
  24933. var len = other.length + source.length;
  24934. var isSrcTypedArray = source instanceof Float32Array;
  24935. var isOthTypedArray = other instanceof Float32Array;
  24936. // use non-loop method when the source is Float32Array
  24937. if (isSrcTypedArray) {
  24938. var ret32 = new Float32Array(len);
  24939. ret32.set(source);
  24940. ret32.set(other, source.length);
  24941. return ret32;
  24942. // source is number[], when other is also use concat
  24943. }
  24944. else if (!isOthTypedArray) {
  24945. return source.concat(other);
  24946. // source is a number[], but other is a Float32Array, loop required
  24947. }
  24948. else {
  24949. var ret = source.slice(0); // copy source to a separate array
  24950. for (var i = 0, len = other.length; i < len; i++) {
  24951. ret.push(other[i]);
  24952. }
  24953. return ret;
  24954. }
  24955. };
  24956. /**
  24957. * Serializes the VertexData.
  24958. * Returns a serialized object.
  24959. */
  24960. VertexData.prototype.serialize = function () {
  24961. var serializationObject = this.serialize();
  24962. if (this.positions) {
  24963. serializationObject.positions = this.positions;
  24964. }
  24965. if (this.normals) {
  24966. serializationObject.normals = this.normals;
  24967. }
  24968. if (this.tangents) {
  24969. serializationObject.tangents = this.tangents;
  24970. }
  24971. if (this.uvs) {
  24972. serializationObject.uvs = this.uvs;
  24973. }
  24974. if (this.uvs2) {
  24975. serializationObject.uvs2 = this.uvs2;
  24976. }
  24977. if (this.uvs3) {
  24978. serializationObject.uvs3 = this.uvs3;
  24979. }
  24980. if (this.uvs4) {
  24981. serializationObject.uvs4 = this.uvs4;
  24982. }
  24983. if (this.uvs5) {
  24984. serializationObject.uvs5 = this.uvs5;
  24985. }
  24986. if (this.uvs6) {
  24987. serializationObject.uvs6 = this.uvs6;
  24988. }
  24989. if (this.colors) {
  24990. serializationObject.colors = this.colors;
  24991. }
  24992. if (this.matricesIndices) {
  24993. serializationObject.matricesIndices = this.matricesIndices;
  24994. serializationObject.matricesIndices._isExpanded = true;
  24995. }
  24996. if (this.matricesWeights) {
  24997. serializationObject.matricesWeights = this.matricesWeights;
  24998. }
  24999. if (this.matricesIndicesExtra) {
  25000. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25001. serializationObject.matricesIndicesExtra._isExpanded = true;
  25002. }
  25003. if (this.matricesWeightsExtra) {
  25004. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25005. }
  25006. serializationObject.indices = this.indices;
  25007. return serializationObject;
  25008. };
  25009. // Statics
  25010. /**
  25011. * Returns the object VertexData associated to the passed mesh.
  25012. */
  25013. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25014. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25015. };
  25016. /**
  25017. * Returns the object VertexData associated to the passed geometry.
  25018. */
  25019. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25020. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25021. };
  25022. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25023. var result = new VertexData();
  25024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25025. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25026. }
  25027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25028. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25029. }
  25030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25031. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25032. }
  25033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25034. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25035. }
  25036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25037. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25038. }
  25039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25040. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25041. }
  25042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25043. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25044. }
  25045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25046. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25047. }
  25048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25049. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25050. }
  25051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25052. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25053. }
  25054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25055. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25056. }
  25057. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25058. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25059. }
  25060. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25061. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25062. }
  25063. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25064. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25065. }
  25066. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25067. return result;
  25068. };
  25069. /**
  25070. * Creates the vertexData of the Ribbon.
  25071. */
  25072. VertexData.CreateRibbon = function (options) {
  25073. var pathArray = options.pathArray;
  25074. var closeArray = options.closeArray || false;
  25075. var closePath = options.closePath || false;
  25076. var invertUV = options.invertUV || false;
  25077. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25078. var offset = options.offset || defaultOffset;
  25079. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25080. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25081. var customUV = options.uvs;
  25082. var customColors = options.colors;
  25083. var positions = [];
  25084. var indices = [];
  25085. var normals = [];
  25086. var uvs = [];
  25087. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25088. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25089. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25090. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25091. var minlg; // minimal length among all paths from pathArray
  25092. var lg = []; // array of path lengths : nb of vertex per path
  25093. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25094. var p; // path iterator
  25095. var i; // point iterator
  25096. var j; // point iterator
  25097. // if single path in pathArray
  25098. if (pathArray.length < 2) {
  25099. var ar1 = [];
  25100. var ar2 = [];
  25101. for (i = 0; i < pathArray[0].length - offset; i++) {
  25102. ar1.push(pathArray[0][i]);
  25103. ar2.push(pathArray[0][i + offset]);
  25104. }
  25105. pathArray = [ar1, ar2];
  25106. }
  25107. // positions and horizontal distances (u)
  25108. var idc = 0;
  25109. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25110. var path;
  25111. var l;
  25112. minlg = pathArray[0].length;
  25113. var vectlg;
  25114. var dist;
  25115. for (p = 0; p < pathArray.length; p++) {
  25116. uTotalDistance[p] = 0;
  25117. us[p] = [0];
  25118. path = pathArray[p];
  25119. l = path.length;
  25120. minlg = (minlg < l) ? minlg : l;
  25121. j = 0;
  25122. while (j < l) {
  25123. positions.push(path[j].x, path[j].y, path[j].z);
  25124. if (j > 0) {
  25125. vectlg = path[j].subtract(path[j - 1]).length();
  25126. dist = vectlg + uTotalDistance[p];
  25127. us[p].push(dist);
  25128. uTotalDistance[p] = dist;
  25129. }
  25130. j++;
  25131. }
  25132. if (closePath) {
  25133. j--;
  25134. positions.push(path[0].x, path[0].y, path[0].z);
  25135. vectlg = path[j].subtract(path[0]).length();
  25136. dist = vectlg + uTotalDistance[p];
  25137. us[p].push(dist);
  25138. uTotalDistance[p] = dist;
  25139. }
  25140. lg[p] = l + closePathCorr;
  25141. idx[p] = idc;
  25142. idc += (l + closePathCorr);
  25143. }
  25144. // vertical distances (v)
  25145. var path1;
  25146. var path2;
  25147. var vertex1;
  25148. var vertex2;
  25149. for (i = 0; i < minlg + closePathCorr; i++) {
  25150. vTotalDistance[i] = 0;
  25151. vs[i] = [0];
  25152. for (p = 0; p < pathArray.length - 1; p++) {
  25153. path1 = pathArray[p];
  25154. path2 = pathArray[p + 1];
  25155. if (i === minlg) {
  25156. vertex1 = path1[0];
  25157. vertex2 = path2[0];
  25158. }
  25159. else {
  25160. vertex1 = path1[i];
  25161. vertex2 = path2[i];
  25162. }
  25163. vectlg = vertex2.subtract(vertex1).length();
  25164. dist = vectlg + vTotalDistance[i];
  25165. vs[i].push(dist);
  25166. vTotalDistance[i] = dist;
  25167. }
  25168. if (closeArray) {
  25169. path1 = pathArray[p];
  25170. path2 = pathArray[0];
  25171. if (i === minlg) {
  25172. vertex2 = path2[0];
  25173. }
  25174. vectlg = vertex2.subtract(vertex1).length();
  25175. dist = vectlg + vTotalDistance[i];
  25176. vTotalDistance[i] = dist;
  25177. }
  25178. }
  25179. // uvs
  25180. var u;
  25181. var v;
  25182. if (customUV) {
  25183. for (p = 0; p < customUV.length; p++) {
  25184. uvs.push(customUV[p].x, customUV[p].y);
  25185. }
  25186. }
  25187. else {
  25188. for (p = 0; p < pathArray.length; p++) {
  25189. for (i = 0; i < minlg + closePathCorr; i++) {
  25190. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25191. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25192. if (invertUV) {
  25193. uvs.push(v, u);
  25194. }
  25195. else {
  25196. uvs.push(u, v);
  25197. }
  25198. }
  25199. }
  25200. }
  25201. // indices
  25202. p = 0; // path index
  25203. var pi = 0; // positions array index
  25204. var l1 = lg[p] - 1; // path1 length
  25205. var l2 = lg[p + 1] - 1; // path2 length
  25206. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25207. var shft = idx[1] - idx[0]; // shift
  25208. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25209. while (pi <= min && p < path1nb) {
  25210. // 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
  25211. indices.push(pi, pi + shft, pi + 1);
  25212. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25213. pi += 1;
  25214. if (pi === min) {
  25215. p++;
  25216. if (p === lg.length - 1) {
  25217. shft = idx[0] - idx[p];
  25218. l1 = lg[p] - 1;
  25219. l2 = lg[0] - 1;
  25220. }
  25221. else {
  25222. shft = idx[p + 1] - idx[p];
  25223. l1 = lg[p] - 1;
  25224. l2 = lg[p + 1] - 1;
  25225. }
  25226. pi = idx[p];
  25227. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25228. }
  25229. }
  25230. // normals
  25231. VertexData.ComputeNormals(positions, indices, normals);
  25232. if (closePath) {
  25233. var indexFirst = 0;
  25234. var indexLast = 0;
  25235. for (p = 0; p < pathArray.length; p++) {
  25236. indexFirst = idx[p] * 3;
  25237. if (p + 1 < pathArray.length) {
  25238. indexLast = (idx[p + 1] - 1) * 3;
  25239. }
  25240. else {
  25241. indexLast = normals.length - 3;
  25242. }
  25243. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25244. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25245. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25246. normals[indexLast] = normals[indexFirst];
  25247. normals[indexLast + 1] = normals[indexFirst + 1];
  25248. normals[indexLast + 2] = normals[indexFirst + 2];
  25249. }
  25250. }
  25251. // sides
  25252. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25253. // Colors
  25254. if (customColors) {
  25255. var colors = new Float32Array(customColors.length * 4);
  25256. for (var c = 0; c < customColors.length; c++) {
  25257. colors[c * 4] = customColors[c].r;
  25258. colors[c * 4 + 1] = customColors[c].g;
  25259. colors[c * 4 + 2] = customColors[c].b;
  25260. colors[c * 4 + 3] = customColors[c].a;
  25261. }
  25262. }
  25263. // Result
  25264. var vertexData = new VertexData();
  25265. var positions32 = new Float32Array(positions);
  25266. var normals32 = new Float32Array(normals);
  25267. var uvs32 = new Float32Array(uvs);
  25268. vertexData.indices = indices;
  25269. vertexData.positions = positions32;
  25270. vertexData.normals = normals32;
  25271. vertexData.uvs = uvs32;
  25272. if (customColors) {
  25273. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25274. }
  25275. if (closePath) {
  25276. vertexData._idx = idx;
  25277. }
  25278. return vertexData;
  25279. };
  25280. /**
  25281. * Creates the VertexData of the Box.
  25282. */
  25283. VertexData.CreateBox = function (options) {
  25284. var normalsSource = [
  25285. new BABYLON.Vector3(0, 0, 1),
  25286. new BABYLON.Vector3(0, 0, -1),
  25287. new BABYLON.Vector3(1, 0, 0),
  25288. new BABYLON.Vector3(-1, 0, 0),
  25289. new BABYLON.Vector3(0, 1, 0),
  25290. new BABYLON.Vector3(0, -1, 0)
  25291. ];
  25292. var indices = [];
  25293. var positions = [];
  25294. var normals = [];
  25295. var uvs = [];
  25296. var width = options.width || options.size || 1;
  25297. var height = options.height || options.size || 1;
  25298. var depth = options.depth || options.size || 1;
  25299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25300. var faceUV = options.faceUV || new Array(6);
  25301. var faceColors = options.faceColors;
  25302. var colors = [];
  25303. // default face colors and UV if undefined
  25304. for (var f = 0; f < 6; f++) {
  25305. if (faceUV[f] === undefined) {
  25306. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25307. }
  25308. if (faceColors && faceColors[f] === undefined) {
  25309. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25310. }
  25311. }
  25312. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25313. // Create each face in turn.
  25314. for (var index = 0; index < normalsSource.length; index++) {
  25315. var normal = normalsSource[index];
  25316. // Get two vectors perpendicular to the face normal and to each other.
  25317. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25318. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25319. // Six indices (two triangles) per face.
  25320. var verticesLength = positions.length / 3;
  25321. indices.push(verticesLength);
  25322. indices.push(verticesLength + 1);
  25323. indices.push(verticesLength + 2);
  25324. indices.push(verticesLength);
  25325. indices.push(verticesLength + 2);
  25326. indices.push(verticesLength + 3);
  25327. // Four vertices per face.
  25328. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25329. positions.push(vertex.x, vertex.y, vertex.z);
  25330. normals.push(normal.x, normal.y, normal.z);
  25331. uvs.push(faceUV[index].z, faceUV[index].w);
  25332. if (faceColors) {
  25333. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25334. }
  25335. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25336. positions.push(vertex.x, vertex.y, vertex.z);
  25337. normals.push(normal.x, normal.y, normal.z);
  25338. uvs.push(faceUV[index].x, faceUV[index].w);
  25339. if (faceColors) {
  25340. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25341. }
  25342. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25343. positions.push(vertex.x, vertex.y, vertex.z);
  25344. normals.push(normal.x, normal.y, normal.z);
  25345. uvs.push(faceUV[index].x, faceUV[index].y);
  25346. if (faceColors) {
  25347. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25348. }
  25349. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25350. positions.push(vertex.x, vertex.y, vertex.z);
  25351. normals.push(normal.x, normal.y, normal.z);
  25352. uvs.push(faceUV[index].z, faceUV[index].y);
  25353. if (faceColors) {
  25354. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25355. }
  25356. }
  25357. // sides
  25358. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25359. // Result
  25360. var vertexData = new VertexData();
  25361. vertexData.indices = indices;
  25362. vertexData.positions = positions;
  25363. vertexData.normals = normals;
  25364. vertexData.uvs = uvs;
  25365. if (faceColors) {
  25366. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25367. vertexData.colors = totalColors;
  25368. }
  25369. return vertexData;
  25370. };
  25371. /**
  25372. * Creates the VertexData of the Sphere.
  25373. */
  25374. VertexData.CreateSphere = function (options) {
  25375. var segments = options.segments || 32;
  25376. var diameterX = options.diameterX || options.diameter || 1;
  25377. var diameterY = options.diameterY || options.diameter || 1;
  25378. var diameterZ = options.diameterZ || options.diameter || 1;
  25379. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25380. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25381. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25382. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25383. var totalZRotationSteps = 2 + segments;
  25384. var totalYRotationSteps = 2 * totalZRotationSteps;
  25385. var indices = [];
  25386. var positions = [];
  25387. var normals = [];
  25388. var uvs = [];
  25389. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25390. var normalizedZ = zRotationStep / totalZRotationSteps;
  25391. var angleZ = normalizedZ * Math.PI * slice;
  25392. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25393. var normalizedY = yRotationStep / totalYRotationSteps;
  25394. var angleY = normalizedY * Math.PI * 2 * arc;
  25395. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25396. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25397. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25398. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25399. var vertex = complete.multiply(radius);
  25400. var normal = complete.divide(radius).normalize();
  25401. positions.push(vertex.x, vertex.y, vertex.z);
  25402. normals.push(normal.x, normal.y, normal.z);
  25403. uvs.push(normalizedY, normalizedZ);
  25404. }
  25405. if (zRotationStep > 0) {
  25406. var verticesCount = positions.length / 3;
  25407. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25408. indices.push((firstIndex));
  25409. indices.push((firstIndex + 1));
  25410. indices.push(firstIndex + totalYRotationSteps + 1);
  25411. indices.push((firstIndex + totalYRotationSteps + 1));
  25412. indices.push((firstIndex + 1));
  25413. indices.push((firstIndex + totalYRotationSteps + 2));
  25414. }
  25415. }
  25416. }
  25417. // Sides
  25418. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25419. // Result
  25420. var vertexData = new VertexData();
  25421. vertexData.indices = indices;
  25422. vertexData.positions = positions;
  25423. vertexData.normals = normals;
  25424. vertexData.uvs = uvs;
  25425. return vertexData;
  25426. };
  25427. /**
  25428. * Creates the VertexData of the Cylinder or Cone.
  25429. */
  25430. VertexData.CreateCylinder = function (options) {
  25431. var height = options.height || 2;
  25432. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25433. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25434. var tessellation = options.tessellation || 24;
  25435. var subdivisions = options.subdivisions || 1;
  25436. var hasRings = options.hasRings;
  25437. var enclose = options.enclose;
  25438. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25439. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25440. var faceUV = options.faceUV || new Array(3);
  25441. var faceColors = options.faceColors;
  25442. // default face colors and UV if undefined
  25443. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25444. var ringNb = (hasRings) ? subdivisions : 1;
  25445. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25446. var f;
  25447. for (f = 0; f < surfaceNb; f++) {
  25448. if (faceColors && faceColors[f] === undefined) {
  25449. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25450. }
  25451. }
  25452. for (f = 0; f < surfaceNb; f++) {
  25453. if (faceUV && faceUV[f] === undefined) {
  25454. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25455. }
  25456. }
  25457. var indices = [];
  25458. var positions = [];
  25459. var normals = [];
  25460. var uvs = [];
  25461. var colors = [];
  25462. var angle_step = Math.PI * 2 * arc / tessellation;
  25463. var angle;
  25464. var h;
  25465. var radius;
  25466. var tan = (diameterBottom - diameterTop) / 2 / height;
  25467. var ringVertex = BABYLON.Vector3.Zero();
  25468. var ringNormal = BABYLON.Vector3.Zero();
  25469. var ringFirstVertex = BABYLON.Vector3.Zero();
  25470. var ringFirstNormal = BABYLON.Vector3.Zero();
  25471. var quadNormal = BABYLON.Vector3.Zero();
  25472. var Y = BABYLON.Axis.Y;
  25473. // positions, normals, uvs
  25474. var i;
  25475. var j;
  25476. var r;
  25477. var ringIdx = 1;
  25478. var s = 1; // surface index
  25479. var cs = 0;
  25480. var v = 0;
  25481. for (i = 0; i <= subdivisions; i++) {
  25482. h = i / subdivisions;
  25483. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25484. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25485. for (r = 0; r < ringIdx; r++) {
  25486. if (hasRings) {
  25487. s += r;
  25488. }
  25489. if (enclose) {
  25490. s += 2 * r;
  25491. }
  25492. for (j = 0; j <= tessellation; j++) {
  25493. angle = j * angle_step;
  25494. // position
  25495. ringVertex.x = Math.cos(-angle) * radius;
  25496. ringVertex.y = -height / 2 + h * height;
  25497. ringVertex.z = Math.sin(-angle) * radius;
  25498. // normal
  25499. if (diameterTop === 0 && i === subdivisions) {
  25500. // if no top cap, reuse former normals
  25501. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25502. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25503. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25504. }
  25505. else {
  25506. ringNormal.x = ringVertex.x;
  25507. ringNormal.z = ringVertex.z;
  25508. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25509. ringNormal.normalize();
  25510. }
  25511. // keep first ring vertex values for enclose
  25512. if (j === 0) {
  25513. ringFirstVertex.copyFrom(ringVertex);
  25514. ringFirstNormal.copyFrom(ringNormal);
  25515. }
  25516. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25517. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25518. if (hasRings) {
  25519. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25520. }
  25521. else {
  25522. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25523. }
  25524. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25525. if (faceColors) {
  25526. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25527. }
  25528. }
  25529. // if enclose, add four vertices and their dedicated normals
  25530. if (arc !== 1 && enclose) {
  25531. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25532. positions.push(0, ringVertex.y, 0);
  25533. positions.push(0, ringVertex.y, 0);
  25534. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25535. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25536. quadNormal.normalize();
  25537. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25538. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25539. quadNormal.normalize();
  25540. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25541. if (hasRings) {
  25542. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25543. }
  25544. else {
  25545. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25546. }
  25547. uvs.push(faceUV[s + 1].x, v);
  25548. uvs.push(faceUV[s + 1].z, v);
  25549. if (hasRings) {
  25550. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25551. }
  25552. else {
  25553. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25554. }
  25555. uvs.push(faceUV[s + 2].x, v);
  25556. uvs.push(faceUV[s + 2].z, v);
  25557. if (faceColors) {
  25558. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25559. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25560. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25561. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25562. }
  25563. }
  25564. if (cs !== s) {
  25565. cs = s;
  25566. }
  25567. }
  25568. }
  25569. // indices
  25570. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25571. var s;
  25572. i = 0;
  25573. for (s = 0; s < subdivisions; s++) {
  25574. for (j = 0; j < tessellation; j++) {
  25575. var i0 = i * (e + 1) + j;
  25576. var i1 = (i + 1) * (e + 1) + j;
  25577. var i2 = i * (e + 1) + (j + 1);
  25578. var i3 = (i + 1) * (e + 1) + (j + 1);
  25579. indices.push(i0, i1, i2);
  25580. indices.push(i3, i2, i1);
  25581. }
  25582. if (arc !== 1 && enclose) {
  25583. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25584. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25585. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25586. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25587. }
  25588. i = (hasRings) ? (i + 2) : (i + 1);
  25589. }
  25590. // Caps
  25591. var createCylinderCap = function (isTop) {
  25592. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25593. if (radius === 0) {
  25594. return;
  25595. }
  25596. // Cap positions, normals & uvs
  25597. var angle;
  25598. var circleVector;
  25599. var i;
  25600. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25601. var c;
  25602. if (faceColors) {
  25603. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25604. }
  25605. // cap center
  25606. var vbase = positions.length / 3;
  25607. var offset = isTop ? height / 2 : -height / 2;
  25608. var center = new BABYLON.Vector3(0, offset, 0);
  25609. positions.push(center.x, center.y, center.z);
  25610. normals.push(0, isTop ? 1 : -1, 0);
  25611. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25612. if (faceColors) {
  25613. colors.push(c.r, c.g, c.b, c.a);
  25614. }
  25615. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25616. for (i = 0; i <= tessellation; i++) {
  25617. angle = Math.PI * 2 * i * arc / tessellation;
  25618. var cos = Math.cos(-angle);
  25619. var sin = Math.sin(-angle);
  25620. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25621. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25622. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25623. normals.push(0, isTop ? 1 : -1, 0);
  25624. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25625. if (faceColors) {
  25626. colors.push(c.r, c.g, c.b, c.a);
  25627. }
  25628. }
  25629. // Cap indices
  25630. for (i = 0; i < tessellation; i++) {
  25631. if (!isTop) {
  25632. indices.push(vbase);
  25633. indices.push(vbase + (i + 1));
  25634. indices.push(vbase + (i + 2));
  25635. }
  25636. else {
  25637. indices.push(vbase);
  25638. indices.push(vbase + (i + 2));
  25639. indices.push(vbase + (i + 1));
  25640. }
  25641. }
  25642. };
  25643. // add caps to geometry
  25644. createCylinderCap(false);
  25645. createCylinderCap(true);
  25646. // Sides
  25647. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25648. var vertexData = new VertexData();
  25649. vertexData.indices = indices;
  25650. vertexData.positions = positions;
  25651. vertexData.normals = normals;
  25652. vertexData.uvs = uvs;
  25653. if (faceColors) {
  25654. vertexData.colors = colors;
  25655. }
  25656. return vertexData;
  25657. };
  25658. /**
  25659. * Creates the VertexData of the Torus.
  25660. */
  25661. VertexData.CreateTorus = function (options) {
  25662. var indices = [];
  25663. var positions = [];
  25664. var normals = [];
  25665. var uvs = [];
  25666. var diameter = options.diameter || 1;
  25667. var thickness = options.thickness || 0.5;
  25668. var tessellation = options.tessellation || 16;
  25669. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25670. var stride = tessellation + 1;
  25671. for (var i = 0; i <= tessellation; i++) {
  25672. var u = i / tessellation;
  25673. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25674. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25675. for (var j = 0; j <= tessellation; j++) {
  25676. var v = 1 - j / tessellation;
  25677. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25678. var dx = Math.cos(innerAngle);
  25679. var dy = Math.sin(innerAngle);
  25680. // Create a vertex.
  25681. var normal = new BABYLON.Vector3(dx, dy, 0);
  25682. var position = normal.scale(thickness / 2);
  25683. var textureCoordinate = new BABYLON.Vector2(u, v);
  25684. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25685. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25686. positions.push(position.x, position.y, position.z);
  25687. normals.push(normal.x, normal.y, normal.z);
  25688. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25689. // And create indices for two triangles.
  25690. var nextI = (i + 1) % stride;
  25691. var nextJ = (j + 1) % stride;
  25692. indices.push(i * stride + j);
  25693. indices.push(i * stride + nextJ);
  25694. indices.push(nextI * stride + j);
  25695. indices.push(i * stride + nextJ);
  25696. indices.push(nextI * stride + nextJ);
  25697. indices.push(nextI * stride + j);
  25698. }
  25699. }
  25700. // Sides
  25701. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25702. // Result
  25703. var vertexData = new VertexData();
  25704. vertexData.indices = indices;
  25705. vertexData.positions = positions;
  25706. vertexData.normals = normals;
  25707. vertexData.uvs = uvs;
  25708. return vertexData;
  25709. };
  25710. /**
  25711. * Creates the VertexData of the LineSystem.
  25712. */
  25713. VertexData.CreateLineSystem = function (options) {
  25714. var indices = [];
  25715. var positions = [];
  25716. var lines = options.lines;
  25717. var idx = 0;
  25718. for (var l = 0; l < lines.length; l++) {
  25719. var points = lines[l];
  25720. for (var index = 0; index < points.length; index++) {
  25721. positions.push(points[index].x, points[index].y, points[index].z);
  25722. if (index > 0) {
  25723. indices.push(idx - 1);
  25724. indices.push(idx);
  25725. }
  25726. idx++;
  25727. }
  25728. }
  25729. var vertexData = new VertexData();
  25730. vertexData.indices = indices;
  25731. vertexData.positions = positions;
  25732. return vertexData;
  25733. };
  25734. /**
  25735. * Create the VertexData of the DashedLines.
  25736. */
  25737. VertexData.CreateDashedLines = function (options) {
  25738. var dashSize = options.dashSize || 3;
  25739. var gapSize = options.gapSize || 1;
  25740. var dashNb = options.dashNb || 200;
  25741. var points = options.points;
  25742. var positions = new Array();
  25743. var indices = new Array();
  25744. var curvect = BABYLON.Vector3.Zero();
  25745. var lg = 0;
  25746. var nb = 0;
  25747. var shft = 0;
  25748. var dashshft = 0;
  25749. var curshft = 0;
  25750. var idx = 0;
  25751. var i = 0;
  25752. for (i = 0; i < points.length - 1; i++) {
  25753. points[i + 1].subtractToRef(points[i], curvect);
  25754. lg += curvect.length();
  25755. }
  25756. shft = lg / dashNb;
  25757. dashshft = dashSize * shft / (dashSize + gapSize);
  25758. for (i = 0; i < points.length - 1; i++) {
  25759. points[i + 1].subtractToRef(points[i], curvect);
  25760. nb = Math.floor(curvect.length() / shft);
  25761. curvect.normalize();
  25762. for (var j = 0; j < nb; j++) {
  25763. curshft = shft * j;
  25764. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25765. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25766. indices.push(idx, idx + 1);
  25767. idx += 2;
  25768. }
  25769. }
  25770. // Result
  25771. var vertexData = new VertexData();
  25772. vertexData.positions = positions;
  25773. vertexData.indices = indices;
  25774. return vertexData;
  25775. };
  25776. /**
  25777. * Creates the VertexData of the Ground.
  25778. */
  25779. VertexData.CreateGround = function (options) {
  25780. var indices = [];
  25781. var positions = [];
  25782. var normals = [];
  25783. var uvs = [];
  25784. var row, col;
  25785. var width = options.width || 1;
  25786. var height = options.height || 1;
  25787. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25788. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25789. for (row = 0; row <= subdivisionsY; row++) {
  25790. for (col = 0; col <= subdivisionsX; col++) {
  25791. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25792. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25793. positions.push(position.x, position.y, position.z);
  25794. normals.push(normal.x, normal.y, normal.z);
  25795. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25796. }
  25797. }
  25798. for (row = 0; row < subdivisionsY; row++) {
  25799. for (col = 0; col < subdivisionsX; col++) {
  25800. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25801. indices.push(col + 1 + row * (subdivisionsX + 1));
  25802. indices.push(col + row * (subdivisionsX + 1));
  25803. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25804. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25805. indices.push(col + row * (subdivisionsX + 1));
  25806. }
  25807. }
  25808. // Result
  25809. var vertexData = new VertexData();
  25810. vertexData.indices = indices;
  25811. vertexData.positions = positions;
  25812. vertexData.normals = normals;
  25813. vertexData.uvs = uvs;
  25814. return vertexData;
  25815. };
  25816. /**
  25817. * Creates the VertexData of the TiledGround.
  25818. */
  25819. VertexData.CreateTiledGround = function (options) {
  25820. var xmin = options.xmin || -1.0;
  25821. var zmin = options.zmin || -1.0;
  25822. var xmax = options.xmax || 1.0;
  25823. var zmax = options.zmax || 1.0;
  25824. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25825. var precision = options.precision || { w: 1, h: 1 };
  25826. var indices = [];
  25827. var positions = [];
  25828. var normals = [];
  25829. var uvs = [];
  25830. var row, col, tileRow, tileCol;
  25831. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25832. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25833. precision.w = (precision.w < 1) ? 1 : precision.w;
  25834. precision.h = (precision.h < 1) ? 1 : precision.h;
  25835. var tileSize = {
  25836. 'w': (xmax - xmin) / subdivisions.w,
  25837. 'h': (zmax - zmin) / subdivisions.h
  25838. };
  25839. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25840. // Indices
  25841. var base = positions.length / 3;
  25842. var rowLength = precision.w + 1;
  25843. for (row = 0; row < precision.h; row++) {
  25844. for (col = 0; col < precision.w; col++) {
  25845. var square = [
  25846. base + col + row * rowLength,
  25847. base + (col + 1) + row * rowLength,
  25848. base + (col + 1) + (row + 1) * rowLength,
  25849. base + col + (row + 1) * rowLength
  25850. ];
  25851. indices.push(square[1]);
  25852. indices.push(square[2]);
  25853. indices.push(square[3]);
  25854. indices.push(square[0]);
  25855. indices.push(square[1]);
  25856. indices.push(square[3]);
  25857. }
  25858. }
  25859. // Position, normals and uvs
  25860. var position = BABYLON.Vector3.Zero();
  25861. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25862. for (row = 0; row <= precision.h; row++) {
  25863. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25864. for (col = 0; col <= precision.w; col++) {
  25865. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25866. position.y = 0;
  25867. positions.push(position.x, position.y, position.z);
  25868. normals.push(normal.x, normal.y, normal.z);
  25869. uvs.push(col / precision.w, row / precision.h);
  25870. }
  25871. }
  25872. }
  25873. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25874. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25875. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25876. }
  25877. }
  25878. // Result
  25879. var vertexData = new VertexData();
  25880. vertexData.indices = indices;
  25881. vertexData.positions = positions;
  25882. vertexData.normals = normals;
  25883. vertexData.uvs = uvs;
  25884. return vertexData;
  25885. };
  25886. /**
  25887. * Creates the VertexData of the Ground designed from a heightmap.
  25888. */
  25889. VertexData.CreateGroundFromHeightMap = function (options) {
  25890. var indices = [];
  25891. var positions = [];
  25892. var normals = [];
  25893. var uvs = [];
  25894. var row, col;
  25895. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25896. // Vertices
  25897. for (row = 0; row <= options.subdivisions; row++) {
  25898. for (col = 0; col <= options.subdivisions; col++) {
  25899. 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));
  25900. // Compute height
  25901. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25902. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25903. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25904. var r = options.buffer[pos] / 255.0;
  25905. var g = options.buffer[pos + 1] / 255.0;
  25906. var b = options.buffer[pos + 2] / 255.0;
  25907. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25908. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25909. // Add vertex
  25910. positions.push(position.x, position.y, position.z);
  25911. normals.push(0, 0, 0);
  25912. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25913. }
  25914. }
  25915. // Indices
  25916. for (row = 0; row < options.subdivisions; row++) {
  25917. for (col = 0; col < options.subdivisions; col++) {
  25918. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25919. indices.push(col + 1 + row * (options.subdivisions + 1));
  25920. indices.push(col + row * (options.subdivisions + 1));
  25921. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25922. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25923. indices.push(col + row * (options.subdivisions + 1));
  25924. }
  25925. }
  25926. // Normals
  25927. VertexData.ComputeNormals(positions, indices, normals);
  25928. // Result
  25929. var vertexData = new VertexData();
  25930. vertexData.indices = indices;
  25931. vertexData.positions = positions;
  25932. vertexData.normals = normals;
  25933. vertexData.uvs = uvs;
  25934. return vertexData;
  25935. };
  25936. /**
  25937. * Creates the VertexData of the Plane.
  25938. */
  25939. VertexData.CreatePlane = function (options) {
  25940. var indices = [];
  25941. var positions = [];
  25942. var normals = [];
  25943. var uvs = [];
  25944. var width = options.width || options.size || 1;
  25945. var height = options.height || options.size || 1;
  25946. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25947. // Vertices
  25948. var halfWidth = width / 2.0;
  25949. var halfHeight = height / 2.0;
  25950. positions.push(-halfWidth, -halfHeight, 0);
  25951. normals.push(0, 0, -1.0);
  25952. uvs.push(0.0, 0.0);
  25953. positions.push(halfWidth, -halfHeight, 0);
  25954. normals.push(0, 0, -1.0);
  25955. uvs.push(1.0, 0.0);
  25956. positions.push(halfWidth, halfHeight, 0);
  25957. normals.push(0, 0, -1.0);
  25958. uvs.push(1.0, 1.0);
  25959. positions.push(-halfWidth, halfHeight, 0);
  25960. normals.push(0, 0, -1.0);
  25961. uvs.push(0.0, 1.0);
  25962. // Indices
  25963. indices.push(0);
  25964. indices.push(1);
  25965. indices.push(2);
  25966. indices.push(0);
  25967. indices.push(2);
  25968. indices.push(3);
  25969. // Sides
  25970. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25971. // Result
  25972. var vertexData = new VertexData();
  25973. vertexData.indices = indices;
  25974. vertexData.positions = positions;
  25975. vertexData.normals = normals;
  25976. vertexData.uvs = uvs;
  25977. return vertexData;
  25978. };
  25979. /**
  25980. * Creates the VertexData of the Disc or regular Polygon.
  25981. */
  25982. VertexData.CreateDisc = function (options) {
  25983. var positions = [];
  25984. var indices = [];
  25985. var normals = [];
  25986. var uvs = [];
  25987. var radius = options.radius || 0.5;
  25988. var tessellation = options.tessellation || 64;
  25989. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25990. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25991. // positions and uvs
  25992. positions.push(0, 0, 0); // disc center first
  25993. uvs.push(0.5, 0.5);
  25994. var theta = Math.PI * 2 * arc;
  25995. var step = theta / tessellation;
  25996. for (var a = 0; a < theta; a += step) {
  25997. var x = Math.cos(a);
  25998. var y = Math.sin(a);
  25999. var u = (x + 1) / 2;
  26000. var v = (1 - y) / 2;
  26001. positions.push(radius * x, radius * y, 0);
  26002. uvs.push(u, v);
  26003. }
  26004. if (arc === 1) {
  26005. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26006. uvs.push(uvs[2], uvs[3]);
  26007. }
  26008. //indices
  26009. var vertexNb = positions.length / 3;
  26010. for (var i = 1; i < vertexNb - 1; i++) {
  26011. indices.push(i + 1, 0, i);
  26012. }
  26013. // result
  26014. VertexData.ComputeNormals(positions, indices, normals);
  26015. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26016. var vertexData = new VertexData();
  26017. vertexData.indices = indices;
  26018. vertexData.positions = positions;
  26019. vertexData.normals = normals;
  26020. vertexData.uvs = uvs;
  26021. return vertexData;
  26022. };
  26023. /**
  26024. * Re-creates the VertexData of the Polygon for sideOrientation.
  26025. */
  26026. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26027. var faceUV = fUV || new Array(3);
  26028. var faceColors = fColors;
  26029. var colors = [];
  26030. // default face colors and UV if undefined
  26031. for (var f = 0; f < 3; f++) {
  26032. if (faceUV[f] === undefined) {
  26033. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26034. }
  26035. if (faceColors && faceColors[f] === undefined) {
  26036. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26037. }
  26038. }
  26039. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26040. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26041. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26042. var indices = polygon.getIndices();
  26043. // set face colours and textures
  26044. var idx = 0;
  26045. var face = 0;
  26046. for (var index = 0; index < normals.length; index += 3) {
  26047. //Edge Face no. 1
  26048. if (Math.abs(normals[index + 1]) == 0) {
  26049. face = 1;
  26050. }
  26051. //Top Face no. 0
  26052. if (normals[index + 1] == 1) {
  26053. face = 0;
  26054. }
  26055. //Bottom Face no. 2
  26056. if (normals[index + 1] == -1) {
  26057. face = 2;
  26058. }
  26059. idx = index / 3;
  26060. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26061. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26062. if (faceColors) {
  26063. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26064. }
  26065. }
  26066. // sides
  26067. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26068. // Result
  26069. var vertexData = new VertexData();
  26070. vertexData.indices = indices;
  26071. vertexData.positions = positions;
  26072. vertexData.normals = normals;
  26073. vertexData.uvs = uvs;
  26074. if (faceColors) {
  26075. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26076. vertexData.colors = totalColors;
  26077. }
  26078. return vertexData;
  26079. };
  26080. /**
  26081. * Creates the VertexData of the IcoSphere.
  26082. */
  26083. VertexData.CreateIcoSphere = function (options) {
  26084. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26085. var radius = options.radius || 1;
  26086. var flat = (options.flat === undefined) ? true : options.flat;
  26087. var subdivisions = options.subdivisions || 4;
  26088. var radiusX = options.radiusX || radius;
  26089. var radiusY = options.radiusY || radius;
  26090. var radiusZ = options.radiusZ || radius;
  26091. var t = (1 + Math.sqrt(5)) / 2;
  26092. // 12 vertex x,y,z
  26093. var ico_vertices = [
  26094. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26095. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26096. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26097. ];
  26098. // index of 3 vertex makes a face of icopshere
  26099. var ico_indices = [
  26100. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26101. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26102. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26103. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26104. ];
  26105. // vertex for uv have aliased position, not for UV
  26106. var vertices_unalias_id = [
  26107. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26108. // vertex alias
  26109. 0,
  26110. 2,
  26111. 3,
  26112. 3,
  26113. 3,
  26114. 4,
  26115. 7,
  26116. 8,
  26117. 9,
  26118. 9,
  26119. 10,
  26120. 11 // 23: B + 12
  26121. ];
  26122. // uv as integer step (not pixels !)
  26123. var ico_vertexuv = [
  26124. 5, 1, 3, 1, 6, 4, 0, 0,
  26125. 5, 3, 4, 2, 2, 2, 4, 0,
  26126. 2, 0, 1, 1, 6, 0, 6, 2,
  26127. // vertex alias (for same vertex on different faces)
  26128. 0, 4,
  26129. 3, 3,
  26130. 4, 4,
  26131. 3, 1,
  26132. 4, 2,
  26133. 4, 4,
  26134. 0, 2,
  26135. 1, 1,
  26136. 2, 2,
  26137. 3, 3,
  26138. 1, 3,
  26139. 2, 4 // 23: B + 12
  26140. ];
  26141. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26142. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26143. // First island of uv mapping
  26144. // v = 4h 3+ 2
  26145. // v = 3h 9+ 4
  26146. // v = 2h 9+ 5 B
  26147. // v = 1h 9 1 0
  26148. // v = 0h 3 8 7 A
  26149. // u = 0 1 2 3 4 5 6 *a
  26150. // Second island of uv mapping
  26151. // v = 4h 0+ B+ 4+
  26152. // v = 3h A+ 2+
  26153. // v = 2h 7+ 6 3+
  26154. // v = 1h 8+ 3+
  26155. // v = 0h
  26156. // u = 0 1 2 3 4 5 6 *a
  26157. // Face layout on texture UV mapping
  26158. // ============
  26159. // \ 4 /\ 16 / ======
  26160. // \ / \ / /\ 11 /
  26161. // \/ 7 \/ / \ /
  26162. // ======= / 10 \/
  26163. // /\ 17 /\ =======
  26164. // / \ / \ \ 15 /\
  26165. // / 8 \/ 12 \ \ / \
  26166. // ============ \/ 6 \
  26167. // \ 18 /\ ============
  26168. // \ / \ \ 5 /\ 0 /
  26169. // \/ 13 \ \ / \ /
  26170. // ======= \/ 1 \/
  26171. // =============
  26172. // /\ 19 /\ 2 /\
  26173. // / \ / \ / \
  26174. // / 14 \/ 9 \/ 3 \
  26175. // ===================
  26176. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26177. var ustep = 138 / 1024;
  26178. var vstep = 239 / 1024;
  26179. var uoffset = 60 / 1024;
  26180. var voffset = 26 / 1024;
  26181. // Second island should have margin, not to touch the first island
  26182. // avoid any borderline artefact in pixel rounding
  26183. var island_u_offset = -40 / 1024;
  26184. var island_v_offset = +20 / 1024;
  26185. // face is either island 0 or 1 :
  26186. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26187. var island = [
  26188. 0, 0, 0, 0, 1,
  26189. 0, 0, 1, 1, 0,
  26190. 0, 0, 1, 1, 0,
  26191. 0, 1, 1, 1, 0 // 15 - 19
  26192. ];
  26193. var indices = [];
  26194. var positions = [];
  26195. var normals = [];
  26196. var uvs = [];
  26197. var current_indice = 0;
  26198. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26199. var face_vertex_pos = new Array(3);
  26200. var face_vertex_uv = new Array(3);
  26201. var v012;
  26202. for (v012 = 0; v012 < 3; v012++) {
  26203. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26204. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26205. }
  26206. // create all with normals
  26207. for (var face = 0; face < 20; face++) {
  26208. // 3 vertex per face
  26209. for (v012 = 0; v012 < 3; v012++) {
  26210. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26211. var v_id = ico_indices[3 * face + v012];
  26212. // vertex have 3D position (x,y,z)
  26213. 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]);
  26214. // Normalize to get normal, then scale to radius
  26215. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26216. // uv Coordinates from vertex ID
  26217. 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);
  26218. }
  26219. // Subdivide the face (interpolate pos, norm, uv)
  26220. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26221. // - norm is linear interpolation of vertex corner normal
  26222. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26223. // - uv is linear interpolation
  26224. //
  26225. // Topology is as below for sub-divide by 2
  26226. // vertex shown as v0,v1,v2
  26227. // interp index is i1 to progress in range [v0,v1[
  26228. // interp index is i2 to progress in range [v0,v2[
  26229. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26230. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26231. //
  26232. //
  26233. // i2 v2
  26234. // ^ ^
  26235. // / / \
  26236. // / / \
  26237. // / / \
  26238. // / / (0,1) \
  26239. // / #---------\
  26240. // / / \ (0,0)'/ \
  26241. // / / \ / \
  26242. // / / \ / \
  26243. // / / (0,0) \ / (1,0) \
  26244. // / #---------#---------\
  26245. // v0 v1
  26246. //
  26247. // --------------------> i1
  26248. //
  26249. // interp of (i1,i2):
  26250. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26251. // along i1 : lerp(x0,x1, i1/(S-i2))
  26252. //
  26253. // centroid of triangle is needed to get help normal computation
  26254. // (c1,c2) are used for centroid location
  26255. var interp_vertex = function (i1, i2, c1, c2) {
  26256. // vertex is interpolated from
  26257. // - face_vertex_pos[0..2]
  26258. // - face_vertex_uv[0..2]
  26259. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26260. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26261. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26262. pos_interp.normalize();
  26263. var vertex_normal;
  26264. if (flat) {
  26265. // in flat mode, recalculate normal as face centroid normal
  26266. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26267. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26268. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26269. }
  26270. else {
  26271. // in smooth mode, recalculate normal from each single vertex position
  26272. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26273. }
  26274. // Vertex normal need correction due to X,Y,Z radius scaling
  26275. vertex_normal.x /= radiusX;
  26276. vertex_normal.y /= radiusY;
  26277. vertex_normal.z /= radiusZ;
  26278. vertex_normal.normalize();
  26279. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26280. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26281. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26282. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26283. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26284. uvs.push(uv_interp.x, uv_interp.y);
  26285. // push each vertex has member of a face
  26286. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26287. indices.push(current_indice);
  26288. current_indice++;
  26289. };
  26290. for (var i2 = 0; i2 < subdivisions; i2++) {
  26291. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26292. // face : (i1,i2) for /\ :
  26293. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26294. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26295. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26296. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26297. if (i1 + i2 + 1 < subdivisions) {
  26298. // face : (i1,i2)' for \/ :
  26299. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26300. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26301. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26302. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26303. }
  26304. }
  26305. }
  26306. }
  26307. // Sides
  26308. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26309. // Result
  26310. var vertexData = new VertexData();
  26311. vertexData.indices = indices;
  26312. vertexData.positions = positions;
  26313. vertexData.normals = normals;
  26314. vertexData.uvs = uvs;
  26315. return vertexData;
  26316. };
  26317. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26318. /**
  26319. * Creates the VertexData of the Polyhedron.
  26320. */
  26321. VertexData.CreatePolyhedron = function (options) {
  26322. // provided polyhedron types :
  26323. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26324. // 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)
  26325. var polyhedra = [];
  26326. 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]] };
  26327. 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]] };
  26328. polyhedra[2] = {
  26329. 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]],
  26330. 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]]
  26331. };
  26332. polyhedra[3] = {
  26333. 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]],
  26334. 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]]
  26335. };
  26336. polyhedra[4] = {
  26337. 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]],
  26338. 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]]
  26339. };
  26340. 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]] };
  26341. 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]] };
  26342. 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]] };
  26343. 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]] };
  26344. 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]] };
  26345. 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]] };
  26346. 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]] };
  26347. 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]] };
  26348. 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]] };
  26349. polyhedra[14] = {
  26350. 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]],
  26351. 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]]
  26352. };
  26353. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26354. var size = options.size;
  26355. var sizeX = options.sizeX || size || 1;
  26356. var sizeY = options.sizeY || size || 1;
  26357. var sizeZ = options.sizeZ || size || 1;
  26358. var data = options.custom || polyhedra[type];
  26359. var nbfaces = data.face.length;
  26360. var faceUV = options.faceUV || new Array(nbfaces);
  26361. var faceColors = options.faceColors;
  26362. var flat = (options.flat === undefined) ? true : options.flat;
  26363. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26364. var positions = [];
  26365. var indices = [];
  26366. var normals = [];
  26367. var uvs = [];
  26368. var colors = [];
  26369. var index = 0;
  26370. var faceIdx = 0; // face cursor in the array "indexes"
  26371. var indexes = [];
  26372. var i = 0;
  26373. var f = 0;
  26374. var u, v, ang, x, y, tmp;
  26375. // default face colors and UV if undefined
  26376. if (flat) {
  26377. for (f = 0; f < nbfaces; f++) {
  26378. if (faceColors && faceColors[f] === undefined) {
  26379. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26380. }
  26381. if (faceUV && faceUV[f] === undefined) {
  26382. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26383. }
  26384. }
  26385. }
  26386. if (!flat) {
  26387. for (i = 0; i < data.vertex.length; i++) {
  26388. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26389. uvs.push(0, 0);
  26390. }
  26391. for (f = 0; f < nbfaces; f++) {
  26392. for (i = 0; i < data.face[f].length - 2; i++) {
  26393. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26394. }
  26395. }
  26396. }
  26397. else {
  26398. for (f = 0; f < nbfaces; f++) {
  26399. var fl = data.face[f].length; // number of vertices of the current face
  26400. ang = 2 * Math.PI / fl;
  26401. x = 0.5 * Math.tan(ang / 2);
  26402. y = 0.5;
  26403. // positions, uvs, colors
  26404. for (i = 0; i < fl; i++) {
  26405. // positions
  26406. 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);
  26407. indexes.push(index);
  26408. index++;
  26409. // uvs
  26410. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26411. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26412. uvs.push(u, v);
  26413. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26414. y = x * Math.sin(ang) + y * Math.cos(ang);
  26415. x = tmp;
  26416. // colors
  26417. if (faceColors) {
  26418. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26419. }
  26420. }
  26421. // indices from indexes
  26422. for (i = 0; i < fl - 2; i++) {
  26423. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26424. }
  26425. faceIdx += fl;
  26426. }
  26427. }
  26428. VertexData.ComputeNormals(positions, indices, normals);
  26429. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26430. var vertexData = new VertexData();
  26431. vertexData.positions = positions;
  26432. vertexData.indices = indices;
  26433. vertexData.normals = normals;
  26434. vertexData.uvs = uvs;
  26435. if (faceColors && flat) {
  26436. vertexData.colors = colors;
  26437. }
  26438. return vertexData;
  26439. };
  26440. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26441. /**
  26442. * Creates the VertexData of the Torus Knot.
  26443. */
  26444. VertexData.CreateTorusKnot = function (options) {
  26445. var indices = [];
  26446. var positions = [];
  26447. var normals = [];
  26448. var uvs = [];
  26449. var radius = options.radius || 2;
  26450. var tube = options.tube || 0.5;
  26451. var radialSegments = options.radialSegments || 32;
  26452. var tubularSegments = options.tubularSegments || 32;
  26453. var p = options.p || 2;
  26454. var q = options.q || 3;
  26455. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26456. // Helper
  26457. var getPos = function (angle) {
  26458. var cu = Math.cos(angle);
  26459. var su = Math.sin(angle);
  26460. var quOverP = q / p * angle;
  26461. var cs = Math.cos(quOverP);
  26462. var tx = radius * (2 + cs) * 0.5 * cu;
  26463. var ty = radius * (2 + cs) * su * 0.5;
  26464. var tz = radius * Math.sin(quOverP) * 0.5;
  26465. return new BABYLON.Vector3(tx, ty, tz);
  26466. };
  26467. // Vertices
  26468. var i;
  26469. var j;
  26470. for (i = 0; i <= radialSegments; i++) {
  26471. var modI = i % radialSegments;
  26472. var u = modI / radialSegments * 2 * p * Math.PI;
  26473. var p1 = getPos(u);
  26474. var p2 = getPos(u + 0.01);
  26475. var tang = p2.subtract(p1);
  26476. var n = p2.add(p1);
  26477. var bitan = BABYLON.Vector3.Cross(tang, n);
  26478. n = BABYLON.Vector3.Cross(bitan, tang);
  26479. bitan.normalize();
  26480. n.normalize();
  26481. for (j = 0; j < tubularSegments; j++) {
  26482. var modJ = j % tubularSegments;
  26483. var v = modJ / tubularSegments * 2 * Math.PI;
  26484. var cx = -tube * Math.cos(v);
  26485. var cy = tube * Math.sin(v);
  26486. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26487. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26488. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26489. uvs.push(i / radialSegments);
  26490. uvs.push(j / tubularSegments);
  26491. }
  26492. }
  26493. for (i = 0; i < radialSegments; i++) {
  26494. for (j = 0; j < tubularSegments; j++) {
  26495. var jNext = (j + 1) % tubularSegments;
  26496. var a = i * tubularSegments + j;
  26497. var b = (i + 1) * tubularSegments + j;
  26498. var c = (i + 1) * tubularSegments + jNext;
  26499. var d = i * tubularSegments + jNext;
  26500. indices.push(d);
  26501. indices.push(b);
  26502. indices.push(a);
  26503. indices.push(d);
  26504. indices.push(c);
  26505. indices.push(b);
  26506. }
  26507. }
  26508. // Normals
  26509. VertexData.ComputeNormals(positions, indices, normals);
  26510. // Sides
  26511. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26512. // Result
  26513. var vertexData = new VertexData();
  26514. vertexData.indices = indices;
  26515. vertexData.positions = positions;
  26516. vertexData.normals = normals;
  26517. vertexData.uvs = uvs;
  26518. return vertexData;
  26519. };
  26520. // Tools
  26521. /**
  26522. * @param {any} - positions (number[] or Float32Array)
  26523. * @param {any} - indices (number[] or Uint16Array)
  26524. * @param {any} - normals (number[] or Float32Array)
  26525. * options (optional) :
  26526. * facetPositions : optional array of facet positions (vector3)
  26527. * facetNormals : optional array of facet normals (vector3)
  26528. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26529. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26530. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26531. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26532. * bInfo : optional bounding info, required for facetPartitioning computation
  26533. */
  26534. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26535. // temporary scalar variables
  26536. var index = 0; // facet index
  26537. var p1p2x = 0.0; // p1p2 vector x coordinate
  26538. var p1p2y = 0.0; // p1p2 vector y coordinate
  26539. var p1p2z = 0.0; // p1p2 vector z coordinate
  26540. var p3p2x = 0.0; // p3p2 vector x coordinate
  26541. var p3p2y = 0.0; // p3p2 vector y coordinate
  26542. var p3p2z = 0.0; // p3p2 vector z coordinate
  26543. var faceNormalx = 0.0; // facet normal x coordinate
  26544. var faceNormaly = 0.0; // facet normal y coordinate
  26545. var faceNormalz = 0.0; // facet normal z coordinate
  26546. var length = 0.0; // facet normal length before normalization
  26547. var v1x = 0; // vector1 x index in the positions array
  26548. var v1y = 0; // vector1 y index in the positions array
  26549. var v1z = 0; // vector1 z index in the positions array
  26550. var v2x = 0; // vector2 x index in the positions array
  26551. var v2y = 0; // vector2 y index in the positions array
  26552. var v2z = 0; // vector2 z index in the positions array
  26553. var v3x = 0; // vector3 x index in the positions array
  26554. var v3y = 0; // vector3 y index in the positions array
  26555. var v3z = 0; // vector3 z index in the positions array
  26556. var computeFacetNormals = false;
  26557. var computeFacetPositions = false;
  26558. var computeFacetPartitioning = false;
  26559. var faceNormalSign = 1;
  26560. if (options) {
  26561. computeFacetNormals = (options.facetNormals) ? true : false;
  26562. computeFacetPositions = (options.facetPositions) ? true : false;
  26563. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26564. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26565. }
  26566. // facetPartitioning reinit if needed
  26567. if (computeFacetPartitioning) {
  26568. var ox = 0; // X partitioning index for facet position
  26569. var oy = 0; // Y partinioning index for facet position
  26570. var oz = 0; // Z partinioning index for facet position
  26571. var b1x = 0; // X partitioning index for facet v1 vertex
  26572. var b1y = 0; // Y partitioning index for facet v1 vertex
  26573. var b1z = 0; // z partitioning index for facet v1 vertex
  26574. var b2x = 0; // X partitioning index for facet v2 vertex
  26575. var b2y = 0; // Y partitioning index for facet v2 vertex
  26576. var b2z = 0; // Z partitioning index for facet v2 vertex
  26577. var b3x = 0; // X partitioning index for facet v3 vertex
  26578. var b3y = 0; // Y partitioning index for facet v3 vertex
  26579. var b3z = 0; // Z partitioning index for facet v3 vertex
  26580. var block_idx_o = 0; // facet barycenter block index
  26581. var block_idx_v1 = 0; // v1 vertex block index
  26582. var block_idx_v2 = 0; // v2 vertex block index
  26583. var block_idx_v3 = 0; // v3 vertex block index
  26584. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26585. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26586. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26587. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26588. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26589. var subSq = options.subDiv.max * options.subDiv.max;
  26590. options.facetPartitioning.length = 0;
  26591. }
  26592. // reset the normals
  26593. for (index = 0; index < positions.length; index++) {
  26594. normals[index] = 0.0;
  26595. }
  26596. // Loop : 1 indice triplet = 1 facet
  26597. var nbFaces = indices.length / 3;
  26598. for (index = 0; index < nbFaces; index++) {
  26599. // get the indexes of the coordinates of each vertex of the facet
  26600. v1x = indices[index * 3] * 3;
  26601. v1y = v1x + 1;
  26602. v1z = v1x + 2;
  26603. v2x = indices[index * 3 + 1] * 3;
  26604. v2y = v2x + 1;
  26605. v2z = v2x + 2;
  26606. v3x = indices[index * 3 + 2] * 3;
  26607. v3y = v3x + 1;
  26608. v3z = v3x + 2;
  26609. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26610. p1p2y = positions[v1y] - positions[v2y];
  26611. p1p2z = positions[v1z] - positions[v2z];
  26612. p3p2x = positions[v3x] - positions[v2x];
  26613. p3p2y = positions[v3y] - positions[v2y];
  26614. p3p2z = positions[v3z] - positions[v2z];
  26615. // compute the face normal with the cross product
  26616. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26617. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26618. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26619. // normalize this normal and store it in the array facetData
  26620. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26621. length = (length === 0) ? 1.0 : length;
  26622. faceNormalx /= length;
  26623. faceNormaly /= length;
  26624. faceNormalz /= length;
  26625. if (computeFacetNormals) {
  26626. options.facetNormals[index].x = faceNormalx;
  26627. options.facetNormals[index].y = faceNormaly;
  26628. options.facetNormals[index].z = faceNormalz;
  26629. }
  26630. if (computeFacetPositions) {
  26631. // compute and the facet barycenter coordinates in the array facetPositions
  26632. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26633. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26634. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26635. }
  26636. if (computeFacetPartitioning) {
  26637. // store the facet indexes in arrays in the main facetPartitioning array :
  26638. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26639. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26640. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26641. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26642. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26643. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26644. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26645. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26646. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26647. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26648. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26649. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26650. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26651. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26652. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26653. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26654. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26655. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26656. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26657. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26658. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26659. // push each facet index in each block containing the vertex
  26660. options.facetPartitioning[block_idx_v1].push(index);
  26661. if (block_idx_v2 != block_idx_v1) {
  26662. options.facetPartitioning[block_idx_v2].push(index);
  26663. }
  26664. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26665. options.facetPartitioning[block_idx_v3].push(index);
  26666. }
  26667. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26668. options.facetPartitioning[block_idx_o].push(index);
  26669. }
  26670. }
  26671. // compute the normals anyway
  26672. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26673. normals[v1y] += faceNormaly;
  26674. normals[v1z] += faceNormalz;
  26675. normals[v2x] += faceNormalx;
  26676. normals[v2y] += faceNormaly;
  26677. normals[v2z] += faceNormalz;
  26678. normals[v3x] += faceNormalx;
  26679. normals[v3y] += faceNormaly;
  26680. normals[v3z] += faceNormalz;
  26681. }
  26682. // last normalization of each normal
  26683. for (index = 0; index < normals.length / 3; index++) {
  26684. faceNormalx = normals[index * 3];
  26685. faceNormaly = normals[index * 3 + 1];
  26686. faceNormalz = normals[index * 3 + 2];
  26687. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26688. length = (length === 0) ? 1.0 : length;
  26689. faceNormalx /= length;
  26690. faceNormaly /= length;
  26691. faceNormalz /= length;
  26692. normals[index * 3] = faceNormalx;
  26693. normals[index * 3 + 1] = faceNormaly;
  26694. normals[index * 3 + 2] = faceNormalz;
  26695. }
  26696. };
  26697. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26698. var li = indices.length;
  26699. var ln = normals.length;
  26700. var i;
  26701. var n;
  26702. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26703. switch (sideOrientation) {
  26704. case BABYLON.Mesh.FRONTSIDE:
  26705. // nothing changed
  26706. break;
  26707. case BABYLON.Mesh.BACKSIDE:
  26708. var tmp;
  26709. // indices
  26710. for (i = 0; i < li; i += 3) {
  26711. tmp = indices[i];
  26712. indices[i] = indices[i + 2];
  26713. indices[i + 2] = tmp;
  26714. }
  26715. // normals
  26716. for (n = 0; n < ln; n++) {
  26717. normals[n] = -normals[n];
  26718. }
  26719. break;
  26720. case BABYLON.Mesh.DOUBLESIDE:
  26721. // positions
  26722. var lp = positions.length;
  26723. var l = lp / 3;
  26724. for (var p = 0; p < lp; p++) {
  26725. positions[lp + p] = positions[p];
  26726. }
  26727. // indices
  26728. for (i = 0; i < li; i += 3) {
  26729. indices[i + li] = indices[i + 2] + l;
  26730. indices[i + 1 + li] = indices[i + 1] + l;
  26731. indices[i + 2 + li] = indices[i] + l;
  26732. }
  26733. // normals
  26734. for (n = 0; n < ln; n++) {
  26735. normals[ln + n] = -normals[n];
  26736. }
  26737. // uvs
  26738. var lu = uvs.length;
  26739. var u = 0;
  26740. for (u = 0; u < lu; u++) {
  26741. uvs[u + lu] = uvs[u];
  26742. }
  26743. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26744. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26745. u = 0;
  26746. for (i = 0; i < lu / 2; i++) {
  26747. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26748. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26749. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26750. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26751. u += 2;
  26752. }
  26753. break;
  26754. }
  26755. };
  26756. /**
  26757. * Creates a new VertexData from the imported parameters.
  26758. */
  26759. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26760. var vertexData = new VertexData();
  26761. // positions
  26762. var positions = parsedVertexData.positions;
  26763. if (positions) {
  26764. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26765. }
  26766. // normals
  26767. var normals = parsedVertexData.normals;
  26768. if (normals) {
  26769. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26770. }
  26771. // tangents
  26772. var tangents = parsedVertexData.tangents;
  26773. if (tangents) {
  26774. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26775. }
  26776. // uvs
  26777. var uvs = parsedVertexData.uvs;
  26778. if (uvs) {
  26779. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26780. }
  26781. // uv2s
  26782. var uv2s = parsedVertexData.uv2s;
  26783. if (uv2s) {
  26784. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26785. }
  26786. // uv3s
  26787. var uv3s = parsedVertexData.uv3s;
  26788. if (uv3s) {
  26789. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26790. }
  26791. // uv4s
  26792. var uv4s = parsedVertexData.uv4s;
  26793. if (uv4s) {
  26794. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26795. }
  26796. // uv5s
  26797. var uv5s = parsedVertexData.uv5s;
  26798. if (uv5s) {
  26799. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26800. }
  26801. // uv6s
  26802. var uv6s = parsedVertexData.uv6s;
  26803. if (uv6s) {
  26804. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26805. }
  26806. // colors
  26807. var colors = parsedVertexData.colors;
  26808. if (colors) {
  26809. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26810. }
  26811. // matricesIndices
  26812. var matricesIndices = parsedVertexData.matricesIndices;
  26813. if (matricesIndices) {
  26814. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26815. }
  26816. // matricesWeights
  26817. var matricesWeights = parsedVertexData.matricesWeights;
  26818. if (matricesWeights) {
  26819. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26820. }
  26821. // indices
  26822. var indices = parsedVertexData.indices;
  26823. if (indices) {
  26824. vertexData.indices = indices;
  26825. }
  26826. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26827. };
  26828. return VertexData;
  26829. }());
  26830. BABYLON.VertexData = VertexData;
  26831. })(BABYLON || (BABYLON = {}));
  26832. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26833. var BABYLON;
  26834. (function (BABYLON) {
  26835. var Geometry = (function () {
  26836. function Geometry(id, scene, vertexData, updatable, mesh) {
  26837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26838. this._totalVertices = 0;
  26839. this._isDisposed = false;
  26840. this.id = id;
  26841. this._engine = scene.getEngine();
  26842. this._meshes = [];
  26843. this._scene = scene;
  26844. //Init vertex buffer cache
  26845. this._vertexBuffers = {};
  26846. this._indices = [];
  26847. // vertexData
  26848. if (vertexData) {
  26849. this.setAllVerticesData(vertexData, updatable);
  26850. }
  26851. else {
  26852. this._totalVertices = 0;
  26853. this._indices = [];
  26854. }
  26855. if (this._engine.getCaps().vertexArrayObject) {
  26856. this._vertexArrayObjects = {};
  26857. }
  26858. // applyToMesh
  26859. if (mesh) {
  26860. if (mesh.getClassName() === "LinesMesh") {
  26861. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26862. this.updateExtend();
  26863. }
  26864. this.applyToMesh(mesh);
  26865. mesh.computeWorldMatrix(true);
  26866. }
  26867. }
  26868. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26869. /**
  26870. * 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
  26871. * @returns The Bias Vector
  26872. */
  26873. get: function () {
  26874. return this._boundingBias;
  26875. },
  26876. set: function (value) {
  26877. if (this._boundingBias && this._boundingBias.equals(value)) {
  26878. return;
  26879. }
  26880. this._boundingBias = value.clone();
  26881. this.updateBoundingInfo(true, null);
  26882. },
  26883. enumerable: true,
  26884. configurable: true
  26885. });
  26886. Object.defineProperty(Geometry.prototype, "extend", {
  26887. get: function () {
  26888. return this._extend;
  26889. },
  26890. enumerable: true,
  26891. configurable: true
  26892. });
  26893. Geometry.prototype.getScene = function () {
  26894. return this._scene;
  26895. };
  26896. Geometry.prototype.getEngine = function () {
  26897. return this._engine;
  26898. };
  26899. Geometry.prototype.isReady = function () {
  26900. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26901. };
  26902. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26903. get: function () {
  26904. for (var index = 0; index < this._meshes.length; index++) {
  26905. if (!this._meshes[index].doNotSerialize) {
  26906. return false;
  26907. }
  26908. }
  26909. return true;
  26910. },
  26911. enumerable: true,
  26912. configurable: true
  26913. });
  26914. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26915. vertexData.applyToGeometry(this, updatable);
  26916. this.notifyUpdate();
  26917. };
  26918. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26919. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26920. this.setVerticesBuffer(buffer);
  26921. };
  26922. Geometry.prototype.removeVerticesData = function (kind) {
  26923. if (this._vertexBuffers[kind]) {
  26924. this._vertexBuffers[kind].dispose();
  26925. delete this._vertexBuffers[kind];
  26926. }
  26927. };
  26928. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26929. var kind = buffer.getKind();
  26930. if (this._vertexBuffers[kind]) {
  26931. this._vertexBuffers[kind].dispose();
  26932. }
  26933. this._vertexBuffers[kind] = buffer;
  26934. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26935. var data = buffer.getData();
  26936. var stride = buffer.getStrideSize();
  26937. this._totalVertices = data.length / stride;
  26938. this.updateExtend(data, stride);
  26939. this._resetPointsArrayCache();
  26940. var meshes = this._meshes;
  26941. var numOfMeshes = meshes.length;
  26942. for (var index = 0; index < numOfMeshes; index++) {
  26943. var mesh = meshes[index];
  26944. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26945. mesh._createGlobalSubMesh();
  26946. mesh.computeWorldMatrix(true);
  26947. }
  26948. }
  26949. this.notifyUpdate(kind);
  26950. if (this._vertexArrayObjects) {
  26951. this._disposeVertexArrayObjects();
  26952. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26953. }
  26954. };
  26955. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26956. var vertexBuffer = this.getVertexBuffer(kind);
  26957. if (!vertexBuffer) {
  26958. return;
  26959. }
  26960. vertexBuffer.updateDirectly(data, offset);
  26961. this.notifyUpdate(kind);
  26962. };
  26963. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26964. var vertexBuffer = this.getVertexBuffer(kind);
  26965. if (!vertexBuffer) {
  26966. return;
  26967. }
  26968. vertexBuffer.update(data);
  26969. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26970. var stride = vertexBuffer.getStrideSize();
  26971. this._totalVertices = data.length / stride;
  26972. this.updateBoundingInfo(updateExtends, data);
  26973. }
  26974. this.notifyUpdate(kind);
  26975. };
  26976. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26977. if (updateExtends) {
  26978. this.updateExtend(data);
  26979. }
  26980. var meshes = this._meshes;
  26981. var numOfMeshes = meshes.length;
  26982. this._resetPointsArrayCache();
  26983. for (var index = 0; index < numOfMeshes; index++) {
  26984. var mesh = meshes[index];
  26985. if (updateExtends) {
  26986. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26987. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26988. var subMesh = mesh.subMeshes[subIndex];
  26989. subMesh.refreshBoundingInfo();
  26990. }
  26991. }
  26992. }
  26993. };
  26994. Geometry.prototype._bind = function (effect, indexToBind) {
  26995. if (indexToBind === void 0) { indexToBind = undefined; }
  26996. if (indexToBind === undefined) {
  26997. indexToBind = this._indexBuffer;
  26998. }
  26999. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27000. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27001. return;
  27002. }
  27003. // Using VAO
  27004. if (!this._vertexArrayObjects[effect.key]) {
  27005. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27006. }
  27007. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27008. };
  27009. Geometry.prototype.getTotalVertices = function () {
  27010. if (!this.isReady()) {
  27011. return 0;
  27012. }
  27013. return this._totalVertices;
  27014. };
  27015. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27016. var vertexBuffer = this.getVertexBuffer(kind);
  27017. if (!vertexBuffer) {
  27018. return null;
  27019. }
  27020. var orig = vertexBuffer.getData();
  27021. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27022. return orig;
  27023. }
  27024. else {
  27025. var len = orig.length;
  27026. var copy = [];
  27027. for (var i = 0; i < len; i++) {
  27028. copy.push(orig[i]);
  27029. }
  27030. return copy;
  27031. }
  27032. };
  27033. Geometry.prototype.getVertexBuffer = function (kind) {
  27034. if (!this.isReady()) {
  27035. return null;
  27036. }
  27037. return this._vertexBuffers[kind];
  27038. };
  27039. Geometry.prototype.getVertexBuffers = function () {
  27040. if (!this.isReady()) {
  27041. return null;
  27042. }
  27043. return this._vertexBuffers;
  27044. };
  27045. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27046. if (!this._vertexBuffers) {
  27047. if (this._delayInfo) {
  27048. return this._delayInfo.indexOf(kind) !== -1;
  27049. }
  27050. return false;
  27051. }
  27052. return this._vertexBuffers[kind] !== undefined;
  27053. };
  27054. Geometry.prototype.getVerticesDataKinds = function () {
  27055. var result = [];
  27056. var kind;
  27057. if (!this._vertexBuffers && this._delayInfo) {
  27058. for (kind in this._delayInfo) {
  27059. result.push(kind);
  27060. }
  27061. }
  27062. else {
  27063. for (kind in this._vertexBuffers) {
  27064. result.push(kind);
  27065. }
  27066. }
  27067. return result;
  27068. };
  27069. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27070. if (this._indexBuffer) {
  27071. this._engine._releaseBuffer(this._indexBuffer);
  27072. }
  27073. this._disposeVertexArrayObjects();
  27074. this._indices = indices;
  27075. if (this._meshes.length !== 0 && this._indices) {
  27076. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27077. }
  27078. if (totalVertices !== undefined) {
  27079. this._totalVertices = totalVertices;
  27080. }
  27081. var meshes = this._meshes;
  27082. var numOfMeshes = meshes.length;
  27083. for (var index = 0; index < numOfMeshes; index++) {
  27084. meshes[index]._createGlobalSubMesh();
  27085. }
  27086. this.notifyUpdate();
  27087. };
  27088. Geometry.prototype.getTotalIndices = function () {
  27089. if (!this.isReady()) {
  27090. return 0;
  27091. }
  27092. return this._indices.length;
  27093. };
  27094. Geometry.prototype.getIndices = function (copyWhenShared) {
  27095. if (!this.isReady()) {
  27096. return null;
  27097. }
  27098. var orig = this._indices;
  27099. if (!copyWhenShared || this._meshes.length === 1) {
  27100. return orig;
  27101. }
  27102. else {
  27103. var len = orig.length;
  27104. var copy = [];
  27105. for (var i = 0; i < len; i++) {
  27106. copy.push(orig[i]);
  27107. }
  27108. return copy;
  27109. }
  27110. };
  27111. Geometry.prototype.getIndexBuffer = function () {
  27112. if (!this.isReady()) {
  27113. return null;
  27114. }
  27115. return this._indexBuffer;
  27116. };
  27117. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27118. if (!effect || !this._vertexArrayObjects) {
  27119. return;
  27120. }
  27121. if (this._vertexArrayObjects[effect.key]) {
  27122. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27123. delete this._vertexArrayObjects[effect.key];
  27124. }
  27125. };
  27126. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27127. var meshes = this._meshes;
  27128. var index = meshes.indexOf(mesh);
  27129. if (index === -1) {
  27130. return;
  27131. }
  27132. meshes.splice(index, 1);
  27133. mesh._geometry = null;
  27134. if (meshes.length === 0 && shouldDispose) {
  27135. this.dispose();
  27136. }
  27137. };
  27138. Geometry.prototype.applyToMesh = function (mesh) {
  27139. if (mesh._geometry === this) {
  27140. return;
  27141. }
  27142. var previousGeometry = mesh._geometry;
  27143. if (previousGeometry) {
  27144. previousGeometry.releaseForMesh(mesh);
  27145. }
  27146. var meshes = this._meshes;
  27147. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27148. mesh._geometry = this;
  27149. this._scene.pushGeometry(this);
  27150. meshes.push(mesh);
  27151. if (this.isReady()) {
  27152. this._applyToMesh(mesh);
  27153. }
  27154. else {
  27155. mesh._boundingInfo = this._boundingInfo;
  27156. }
  27157. };
  27158. Geometry.prototype.updateExtend = function (data, stride) {
  27159. if (data === void 0) { data = null; }
  27160. if (!data) {
  27161. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27162. }
  27163. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27164. };
  27165. Geometry.prototype._applyToMesh = function (mesh) {
  27166. var numOfMeshes = this._meshes.length;
  27167. // vertexBuffers
  27168. for (var kind in this._vertexBuffers) {
  27169. if (numOfMeshes === 1) {
  27170. this._vertexBuffers[kind].create();
  27171. }
  27172. var buffer = this._vertexBuffers[kind].getBuffer();
  27173. if (buffer)
  27174. buffer.references = numOfMeshes;
  27175. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27176. if (!this._extend) {
  27177. this.updateExtend(this._vertexBuffers[kind].getData());
  27178. }
  27179. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27180. mesh._createGlobalSubMesh();
  27181. //bounding info was just created again, world matrix should be applied again.
  27182. mesh._updateBoundingInfo();
  27183. }
  27184. }
  27185. // indexBuffer
  27186. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27187. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27188. }
  27189. if (this._indexBuffer) {
  27190. this._indexBuffer.references = numOfMeshes;
  27191. }
  27192. };
  27193. Geometry.prototype.notifyUpdate = function (kind) {
  27194. if (this.onGeometryUpdated) {
  27195. this.onGeometryUpdated(this, kind);
  27196. }
  27197. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27198. var mesh = _a[_i];
  27199. mesh._markSubMeshesAsAttributesDirty();
  27200. }
  27201. };
  27202. Geometry.prototype.load = function (scene, onLoaded) {
  27203. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27204. return;
  27205. }
  27206. if (this.isReady()) {
  27207. if (onLoaded) {
  27208. onLoaded();
  27209. }
  27210. return;
  27211. }
  27212. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27213. this._queueLoad(scene, onLoaded);
  27214. };
  27215. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27216. var _this = this;
  27217. scene._addPendingData(this);
  27218. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27219. _this._delayLoadingFunction(JSON.parse(data), _this);
  27220. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27221. _this._delayInfo = [];
  27222. scene._removePendingData(_this);
  27223. var meshes = _this._meshes;
  27224. var numOfMeshes = meshes.length;
  27225. for (var index = 0; index < numOfMeshes; index++) {
  27226. _this._applyToMesh(meshes[index]);
  27227. }
  27228. if (onLoaded) {
  27229. onLoaded();
  27230. }
  27231. }, function () { }, scene.database);
  27232. };
  27233. /**
  27234. * Invert the geometry to move from a right handed system to a left handed one.
  27235. */
  27236. Geometry.prototype.toLeftHanded = function () {
  27237. // Flip faces
  27238. var tIndices = this.getIndices(false);
  27239. if (tIndices != null && tIndices.length > 0) {
  27240. for (var i = 0; i < tIndices.length; i += 3) {
  27241. var tTemp = tIndices[i + 0];
  27242. tIndices[i + 0] = tIndices[i + 2];
  27243. tIndices[i + 2] = tTemp;
  27244. }
  27245. this.setIndices(tIndices);
  27246. }
  27247. // Negate position.z
  27248. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27249. if (tPositions != null && tPositions.length > 0) {
  27250. for (var i = 0; i < tPositions.length; i += 3) {
  27251. tPositions[i + 2] = -tPositions[i + 2];
  27252. }
  27253. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27254. }
  27255. // Negate normal.z
  27256. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27257. if (tNormals != null && tNormals.length > 0) {
  27258. for (var i = 0; i < tNormals.length; i += 3) {
  27259. tNormals[i + 2] = -tNormals[i + 2];
  27260. }
  27261. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27262. }
  27263. };
  27264. // Cache
  27265. Geometry.prototype._resetPointsArrayCache = function () {
  27266. this._positions = null;
  27267. };
  27268. Geometry.prototype._generatePointsArray = function () {
  27269. if (this._positions)
  27270. return true;
  27271. this._positions = [];
  27272. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27273. if (!data) {
  27274. return false;
  27275. }
  27276. for (var index = 0; index < data.length; index += 3) {
  27277. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27278. }
  27279. return true;
  27280. };
  27281. Geometry.prototype.isDisposed = function () {
  27282. return this._isDisposed;
  27283. };
  27284. Geometry.prototype._disposeVertexArrayObjects = function () {
  27285. if (this._vertexArrayObjects) {
  27286. for (var kind in this._vertexArrayObjects) {
  27287. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27288. }
  27289. this._vertexArrayObjects = {};
  27290. }
  27291. };
  27292. Geometry.prototype.dispose = function () {
  27293. var meshes = this._meshes;
  27294. var numOfMeshes = meshes.length;
  27295. var index;
  27296. for (index = 0; index < numOfMeshes; index++) {
  27297. this.releaseForMesh(meshes[index]);
  27298. }
  27299. this._meshes = [];
  27300. this._disposeVertexArrayObjects();
  27301. for (var kind in this._vertexBuffers) {
  27302. this._vertexBuffers[kind].dispose();
  27303. }
  27304. this._vertexBuffers = {};
  27305. this._totalVertices = 0;
  27306. if (this._indexBuffer) {
  27307. this._engine._releaseBuffer(this._indexBuffer);
  27308. }
  27309. this._indexBuffer = null;
  27310. this._indices = [];
  27311. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27312. this.delayLoadingFile = null;
  27313. this._delayLoadingFunction = null;
  27314. this._delayInfo = [];
  27315. this._boundingInfo = null;
  27316. this._scene.removeGeometry(this);
  27317. this._isDisposed = true;
  27318. };
  27319. Geometry.prototype.copy = function (id) {
  27320. var vertexData = new BABYLON.VertexData();
  27321. vertexData.indices = [];
  27322. var indices = this.getIndices();
  27323. for (var index = 0; index < indices.length; index++) {
  27324. vertexData.indices.push(indices[index]);
  27325. }
  27326. var updatable = false;
  27327. var stopChecking = false;
  27328. var kind;
  27329. for (kind in this._vertexBuffers) {
  27330. // using slice() to make a copy of the array and not just reference it
  27331. var data = this.getVerticesData(kind);
  27332. if (data instanceof Float32Array) {
  27333. vertexData.set(new Float32Array(data), kind);
  27334. }
  27335. else {
  27336. vertexData.set(data.slice(0), kind);
  27337. }
  27338. if (!stopChecking) {
  27339. updatable = this.getVertexBuffer(kind).isUpdatable();
  27340. stopChecking = !updatable;
  27341. }
  27342. }
  27343. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27344. geometry.delayLoadState = this.delayLoadState;
  27345. geometry.delayLoadingFile = this.delayLoadingFile;
  27346. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27347. for (kind in this._delayInfo) {
  27348. geometry._delayInfo = geometry._delayInfo || [];
  27349. geometry._delayInfo.push(kind);
  27350. }
  27351. // Bounding info
  27352. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27353. return geometry;
  27354. };
  27355. Geometry.prototype.serialize = function () {
  27356. var serializationObject = {};
  27357. serializationObject.id = this.id;
  27358. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27359. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27360. }
  27361. return serializationObject;
  27362. };
  27363. Geometry.prototype.toNumberArray = function (origin) {
  27364. if (Array.isArray(origin)) {
  27365. return origin;
  27366. }
  27367. else {
  27368. return Array.prototype.slice.call(origin);
  27369. }
  27370. };
  27371. Geometry.prototype.serializeVerticeData = function () {
  27372. var serializationObject = this.serialize();
  27373. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27374. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27375. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27376. serializationObject.positions._updatable = true;
  27377. }
  27378. }
  27379. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27380. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27381. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27382. serializationObject.normals._updatable = true;
  27383. }
  27384. }
  27385. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27386. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27387. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27388. serializationObject.uvs._updatable = true;
  27389. }
  27390. }
  27391. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27392. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27393. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27394. serializationObject.uv2s._updatable = true;
  27395. }
  27396. }
  27397. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27398. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27399. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27400. serializationObject.uv3s._updatable = true;
  27401. }
  27402. }
  27403. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27404. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27405. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27406. serializationObject.uv4s._updatable = true;
  27407. }
  27408. }
  27409. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27410. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27411. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27412. serializationObject.uv5s._updatable = true;
  27413. }
  27414. }
  27415. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27416. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27417. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27418. serializationObject.uv6s._updatable = true;
  27419. }
  27420. }
  27421. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27422. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27423. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27424. serializationObject.colors._updatable = true;
  27425. }
  27426. }
  27427. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27428. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27429. serializationObject.matricesIndices._isExpanded = true;
  27430. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27431. serializationObject.matricesIndices._updatable = true;
  27432. }
  27433. }
  27434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27435. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27436. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27437. serializationObject.matricesWeights._updatable = true;
  27438. }
  27439. }
  27440. serializationObject.indices = this.toNumberArray(this.getIndices());
  27441. return serializationObject;
  27442. };
  27443. // Statics
  27444. Geometry.ExtractFromMesh = function (mesh, id) {
  27445. var geometry = mesh._geometry;
  27446. if (!geometry) {
  27447. return null;
  27448. }
  27449. return geometry.copy(id);
  27450. };
  27451. /**
  27452. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27453. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27454. * Be aware Math.random() could cause collisions, but:
  27455. * "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"
  27456. */
  27457. Geometry.RandomId = function () {
  27458. return BABYLON.Tools.RandomId();
  27459. };
  27460. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27461. var scene = mesh.getScene();
  27462. // Geometry
  27463. var geometryId = parsedGeometry.geometryId;
  27464. if (geometryId) {
  27465. var geometry = scene.getGeometryByID(geometryId);
  27466. if (geometry) {
  27467. geometry.applyToMesh(mesh);
  27468. }
  27469. }
  27470. else if (parsedGeometry instanceof ArrayBuffer) {
  27471. var binaryInfo = mesh._binaryInfo;
  27472. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27473. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27474. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27475. }
  27476. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27477. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27478. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27479. }
  27480. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27481. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27482. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27483. }
  27484. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27485. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27486. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27487. }
  27488. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27489. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27490. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27491. }
  27492. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27493. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27494. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27495. }
  27496. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27497. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27498. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27499. }
  27500. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27501. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27502. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27503. }
  27504. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27505. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27506. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27507. }
  27508. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27509. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27510. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27511. }
  27512. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27513. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27514. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27515. }
  27516. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27517. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27518. mesh.setIndices(indicesData);
  27519. }
  27520. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27521. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27522. mesh.subMeshes = [];
  27523. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27524. var materialIndex = subMeshesData[(i * 5) + 0];
  27525. var verticesStart = subMeshesData[(i * 5) + 1];
  27526. var verticesCount = subMeshesData[(i * 5) + 2];
  27527. var indexStart = subMeshesData[(i * 5) + 3];
  27528. var indexCount = subMeshesData[(i * 5) + 4];
  27529. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27530. }
  27531. }
  27532. }
  27533. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27534. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27535. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27536. if (parsedGeometry.uvs) {
  27537. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27538. }
  27539. if (parsedGeometry.uvs2) {
  27540. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27541. }
  27542. if (parsedGeometry.uvs3) {
  27543. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27544. }
  27545. if (parsedGeometry.uvs4) {
  27546. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27547. }
  27548. if (parsedGeometry.uvs5) {
  27549. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27550. }
  27551. if (parsedGeometry.uvs6) {
  27552. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27553. }
  27554. if (parsedGeometry.colors) {
  27555. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27556. }
  27557. if (parsedGeometry.matricesIndices) {
  27558. if (!parsedGeometry.matricesIndices._isExpanded) {
  27559. var floatIndices = [];
  27560. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27561. var matricesIndex = parsedGeometry.matricesIndices[i];
  27562. floatIndices.push(matricesIndex & 0x000000FF);
  27563. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27564. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27565. floatIndices.push(matricesIndex >> 24);
  27566. }
  27567. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27568. }
  27569. else {
  27570. delete parsedGeometry.matricesIndices._isExpanded;
  27571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27572. }
  27573. }
  27574. if (parsedGeometry.matricesIndicesExtra) {
  27575. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27576. var floatIndices = [];
  27577. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27578. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27579. floatIndices.push(matricesIndex & 0x000000FF);
  27580. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27581. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27582. floatIndices.push(matricesIndex >> 24);
  27583. }
  27584. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27585. }
  27586. else {
  27587. delete parsedGeometry.matricesIndices._isExpanded;
  27588. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27589. }
  27590. }
  27591. if (parsedGeometry.matricesWeights) {
  27592. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27593. }
  27594. if (parsedGeometry.matricesWeightsExtra) {
  27595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27596. }
  27597. mesh.setIndices(parsedGeometry.indices);
  27598. }
  27599. // SubMeshes
  27600. if (parsedGeometry.subMeshes) {
  27601. mesh.subMeshes = [];
  27602. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27603. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27604. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27605. }
  27606. }
  27607. // Flat shading
  27608. if (mesh._shouldGenerateFlatShading) {
  27609. mesh.convertToFlatShadedMesh();
  27610. delete mesh._shouldGenerateFlatShading;
  27611. }
  27612. // Update
  27613. mesh.computeWorldMatrix(true);
  27614. // Octree
  27615. if (scene['_selectionOctree']) {
  27616. scene['_selectionOctree'].addMesh(mesh);
  27617. }
  27618. };
  27619. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27620. if (scene.getGeometryByID(parsedVertexData.id)) {
  27621. return null; // null since geometry could be something else than a box...
  27622. }
  27623. var geometry = new Geometry(parsedVertexData.id, scene);
  27624. if (BABYLON.Tags) {
  27625. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27626. }
  27627. if (parsedVertexData.delayLoadingFile) {
  27628. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27629. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27630. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27631. geometry._delayInfo = [];
  27632. if (parsedVertexData.hasUVs) {
  27633. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27634. }
  27635. if (parsedVertexData.hasUVs2) {
  27636. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27637. }
  27638. if (parsedVertexData.hasUVs3) {
  27639. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27640. }
  27641. if (parsedVertexData.hasUVs4) {
  27642. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27643. }
  27644. if (parsedVertexData.hasUVs5) {
  27645. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27646. }
  27647. if (parsedVertexData.hasUVs6) {
  27648. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27649. }
  27650. if (parsedVertexData.hasColors) {
  27651. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27652. }
  27653. if (parsedVertexData.hasMatricesIndices) {
  27654. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27655. }
  27656. if (parsedVertexData.hasMatricesWeights) {
  27657. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27658. }
  27659. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27660. }
  27661. else {
  27662. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27663. }
  27664. scene.pushGeometry(geometry, true);
  27665. return geometry;
  27666. };
  27667. return Geometry;
  27668. }());
  27669. BABYLON.Geometry = Geometry;
  27670. /////// Primitives //////////////////////////////////////////////
  27671. (function (Geometry) {
  27672. var Primitives;
  27673. (function (Primitives) {
  27674. /// Abstract class
  27675. var _Primitive = (function (_super) {
  27676. __extends(_Primitive, _super);
  27677. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27678. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27679. _this._canBeRegenerated = _canBeRegenerated;
  27680. _this._beingRegenerated = true;
  27681. _this.regenerate();
  27682. _this._beingRegenerated = false;
  27683. return _this;
  27684. }
  27685. _Primitive.prototype.canBeRegenerated = function () {
  27686. return this._canBeRegenerated;
  27687. };
  27688. _Primitive.prototype.regenerate = function () {
  27689. if (!this._canBeRegenerated) {
  27690. return;
  27691. }
  27692. this._beingRegenerated = true;
  27693. this.setAllVerticesData(this._regenerateVertexData(), false);
  27694. this._beingRegenerated = false;
  27695. };
  27696. _Primitive.prototype.asNewGeometry = function (id) {
  27697. return _super.prototype.copy.call(this, id);
  27698. };
  27699. // overrides
  27700. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27701. if (!this._beingRegenerated) {
  27702. return;
  27703. }
  27704. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27705. };
  27706. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27707. if (!this._beingRegenerated) {
  27708. return;
  27709. }
  27710. _super.prototype.setVerticesData.call(this, kind, data, false);
  27711. };
  27712. // to override
  27713. // protected
  27714. _Primitive.prototype._regenerateVertexData = function () {
  27715. throw new Error("Abstract method");
  27716. };
  27717. _Primitive.prototype.copy = function (id) {
  27718. throw new Error("Must be overriden in sub-classes.");
  27719. };
  27720. _Primitive.prototype.serialize = function () {
  27721. var serializationObject = _super.prototype.serialize.call(this);
  27722. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27723. return serializationObject;
  27724. };
  27725. return _Primitive;
  27726. }(Geometry));
  27727. Primitives._Primitive = _Primitive;
  27728. var Ribbon = (function (_super) {
  27729. __extends(Ribbon, _super);
  27730. // Members
  27731. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27732. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27733. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27734. _this.pathArray = pathArray;
  27735. _this.closeArray = closeArray;
  27736. _this.closePath = closePath;
  27737. _this.offset = offset;
  27738. _this.side = side;
  27739. return _this;
  27740. }
  27741. Ribbon.prototype._regenerateVertexData = function () {
  27742. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27743. };
  27744. Ribbon.prototype.copy = function (id) {
  27745. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27746. };
  27747. return Ribbon;
  27748. }(_Primitive));
  27749. Primitives.Ribbon = Ribbon;
  27750. var Box = (function (_super) {
  27751. __extends(Box, _super);
  27752. // Members
  27753. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27755. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27756. _this.size = size;
  27757. _this.side = side;
  27758. return _this;
  27759. }
  27760. Box.prototype._regenerateVertexData = function () {
  27761. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27762. };
  27763. Box.prototype.copy = function (id) {
  27764. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27765. };
  27766. Box.prototype.serialize = function () {
  27767. var serializationObject = _super.prototype.serialize.call(this);
  27768. serializationObject.size = this.size;
  27769. return serializationObject;
  27770. };
  27771. Box.Parse = function (parsedBox, scene) {
  27772. if (scene.getGeometryByID(parsedBox.id)) {
  27773. return null; // null since geometry could be something else than a box...
  27774. }
  27775. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27776. if (BABYLON.Tags) {
  27777. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27778. }
  27779. scene.pushGeometry(box, true);
  27780. return box;
  27781. };
  27782. return Box;
  27783. }(_Primitive));
  27784. Primitives.Box = Box;
  27785. var Sphere = (function (_super) {
  27786. __extends(Sphere, _super);
  27787. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27788. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27789. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27790. _this.segments = segments;
  27791. _this.diameter = diameter;
  27792. _this.side = side;
  27793. return _this;
  27794. }
  27795. Sphere.prototype._regenerateVertexData = function () {
  27796. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27797. };
  27798. Sphere.prototype.copy = function (id) {
  27799. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27800. };
  27801. Sphere.prototype.serialize = function () {
  27802. var serializationObject = _super.prototype.serialize.call(this);
  27803. serializationObject.segments = this.segments;
  27804. serializationObject.diameter = this.diameter;
  27805. return serializationObject;
  27806. };
  27807. Sphere.Parse = function (parsedSphere, scene) {
  27808. if (scene.getGeometryByID(parsedSphere.id)) {
  27809. return null; // null since geometry could be something else than a sphere...
  27810. }
  27811. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27812. if (BABYLON.Tags) {
  27813. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27814. }
  27815. scene.pushGeometry(sphere, true);
  27816. return sphere;
  27817. };
  27818. return Sphere;
  27819. }(_Primitive));
  27820. Primitives.Sphere = Sphere;
  27821. var Disc = (function (_super) {
  27822. __extends(Disc, _super);
  27823. // Members
  27824. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27825. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27826. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27827. _this.radius = radius;
  27828. _this.tessellation = tessellation;
  27829. _this.side = side;
  27830. return _this;
  27831. }
  27832. Disc.prototype._regenerateVertexData = function () {
  27833. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27834. };
  27835. Disc.prototype.copy = function (id) {
  27836. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27837. };
  27838. return Disc;
  27839. }(_Primitive));
  27840. Primitives.Disc = Disc;
  27841. var Cylinder = (function (_super) {
  27842. __extends(Cylinder, _super);
  27843. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27844. if (subdivisions === void 0) { subdivisions = 1; }
  27845. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27846. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27847. _this.height = height;
  27848. _this.diameterTop = diameterTop;
  27849. _this.diameterBottom = diameterBottom;
  27850. _this.tessellation = tessellation;
  27851. _this.subdivisions = subdivisions;
  27852. _this.side = side;
  27853. return _this;
  27854. }
  27855. Cylinder.prototype._regenerateVertexData = function () {
  27856. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27857. };
  27858. Cylinder.prototype.copy = function (id) {
  27859. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27860. };
  27861. Cylinder.prototype.serialize = function () {
  27862. var serializationObject = _super.prototype.serialize.call(this);
  27863. serializationObject.height = this.height;
  27864. serializationObject.diameterTop = this.diameterTop;
  27865. serializationObject.diameterBottom = this.diameterBottom;
  27866. serializationObject.tessellation = this.tessellation;
  27867. return serializationObject;
  27868. };
  27869. Cylinder.Parse = function (parsedCylinder, scene) {
  27870. if (scene.getGeometryByID(parsedCylinder.id)) {
  27871. return null; // null since geometry could be something else than a cylinder...
  27872. }
  27873. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27874. if (BABYLON.Tags) {
  27875. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27876. }
  27877. scene.pushGeometry(cylinder, true);
  27878. return cylinder;
  27879. };
  27880. return Cylinder;
  27881. }(_Primitive));
  27882. Primitives.Cylinder = Cylinder;
  27883. var Torus = (function (_super) {
  27884. __extends(Torus, _super);
  27885. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27886. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27887. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27888. _this.diameter = diameter;
  27889. _this.thickness = thickness;
  27890. _this.tessellation = tessellation;
  27891. _this.side = side;
  27892. return _this;
  27893. }
  27894. Torus.prototype._regenerateVertexData = function () {
  27895. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27896. };
  27897. Torus.prototype.copy = function (id) {
  27898. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27899. };
  27900. Torus.prototype.serialize = function () {
  27901. var serializationObject = _super.prototype.serialize.call(this);
  27902. serializationObject.diameter = this.diameter;
  27903. serializationObject.thickness = this.thickness;
  27904. serializationObject.tessellation = this.tessellation;
  27905. return serializationObject;
  27906. };
  27907. Torus.Parse = function (parsedTorus, scene) {
  27908. if (scene.getGeometryByID(parsedTorus.id)) {
  27909. return null; // null since geometry could be something else than a torus...
  27910. }
  27911. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27912. if (BABYLON.Tags) {
  27913. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27914. }
  27915. scene.pushGeometry(torus, true);
  27916. return torus;
  27917. };
  27918. return Torus;
  27919. }(_Primitive));
  27920. Primitives.Torus = Torus;
  27921. var Ground = (function (_super) {
  27922. __extends(Ground, _super);
  27923. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27924. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27925. _this.width = width;
  27926. _this.height = height;
  27927. _this.subdivisions = subdivisions;
  27928. return _this;
  27929. }
  27930. Ground.prototype._regenerateVertexData = function () {
  27931. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27932. };
  27933. Ground.prototype.copy = function (id) {
  27934. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27935. };
  27936. Ground.prototype.serialize = function () {
  27937. var serializationObject = _super.prototype.serialize.call(this);
  27938. serializationObject.width = this.width;
  27939. serializationObject.height = this.height;
  27940. serializationObject.subdivisions = this.subdivisions;
  27941. return serializationObject;
  27942. };
  27943. Ground.Parse = function (parsedGround, scene) {
  27944. if (scene.getGeometryByID(parsedGround.id)) {
  27945. return null; // null since geometry could be something else than a ground...
  27946. }
  27947. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27948. if (BABYLON.Tags) {
  27949. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27950. }
  27951. scene.pushGeometry(ground, true);
  27952. return ground;
  27953. };
  27954. return Ground;
  27955. }(_Primitive));
  27956. Primitives.Ground = Ground;
  27957. var TiledGround = (function (_super) {
  27958. __extends(TiledGround, _super);
  27959. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27961. _this.xmin = xmin;
  27962. _this.zmin = zmin;
  27963. _this.xmax = xmax;
  27964. _this.zmax = zmax;
  27965. _this.subdivisions = subdivisions;
  27966. _this.precision = precision;
  27967. return _this;
  27968. }
  27969. TiledGround.prototype._regenerateVertexData = function () {
  27970. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27971. };
  27972. TiledGround.prototype.copy = function (id) {
  27973. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27974. };
  27975. return TiledGround;
  27976. }(_Primitive));
  27977. Primitives.TiledGround = TiledGround;
  27978. var Plane = (function (_super) {
  27979. __extends(Plane, _super);
  27980. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27981. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27982. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27983. _this.size = size;
  27984. _this.side = side;
  27985. return _this;
  27986. }
  27987. Plane.prototype._regenerateVertexData = function () {
  27988. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27989. };
  27990. Plane.prototype.copy = function (id) {
  27991. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27992. };
  27993. Plane.prototype.serialize = function () {
  27994. var serializationObject = _super.prototype.serialize.call(this);
  27995. serializationObject.size = this.size;
  27996. return serializationObject;
  27997. };
  27998. Plane.Parse = function (parsedPlane, scene) {
  27999. if (scene.getGeometryByID(parsedPlane.id)) {
  28000. return null; // null since geometry could be something else than a ground...
  28001. }
  28002. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28003. if (BABYLON.Tags) {
  28004. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28005. }
  28006. scene.pushGeometry(plane, true);
  28007. return plane;
  28008. };
  28009. return Plane;
  28010. }(_Primitive));
  28011. Primitives.Plane = Plane;
  28012. var TorusKnot = (function (_super) {
  28013. __extends(TorusKnot, _super);
  28014. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28015. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28016. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28017. _this.radius = radius;
  28018. _this.tube = tube;
  28019. _this.radialSegments = radialSegments;
  28020. _this.tubularSegments = tubularSegments;
  28021. _this.p = p;
  28022. _this.q = q;
  28023. _this.side = side;
  28024. return _this;
  28025. }
  28026. TorusKnot.prototype._regenerateVertexData = function () {
  28027. 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 });
  28028. };
  28029. TorusKnot.prototype.copy = function (id) {
  28030. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28031. };
  28032. TorusKnot.prototype.serialize = function () {
  28033. var serializationObject = _super.prototype.serialize.call(this);
  28034. serializationObject.radius = this.radius;
  28035. serializationObject.tube = this.tube;
  28036. serializationObject.radialSegments = this.radialSegments;
  28037. serializationObject.tubularSegments = this.tubularSegments;
  28038. serializationObject.p = this.p;
  28039. serializationObject.q = this.q;
  28040. return serializationObject;
  28041. };
  28042. ;
  28043. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28044. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28045. return null; // null since geometry could be something else than a ground...
  28046. }
  28047. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28048. if (BABYLON.Tags) {
  28049. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28050. }
  28051. scene.pushGeometry(torusKnot, true);
  28052. return torusKnot;
  28053. };
  28054. return TorusKnot;
  28055. }(_Primitive));
  28056. Primitives.TorusKnot = TorusKnot;
  28057. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28058. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28059. })(BABYLON || (BABYLON = {}));
  28060. //# sourceMappingURL=babylon.geometry.js.map
  28061. var BABYLON;
  28062. (function (BABYLON) {
  28063. var PostProcessManager = (function () {
  28064. function PostProcessManager(scene) {
  28065. this._vertexBuffers = {};
  28066. this._scene = scene;
  28067. }
  28068. PostProcessManager.prototype._prepareBuffers = function () {
  28069. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28070. return;
  28071. }
  28072. // VBO
  28073. var vertices = [];
  28074. vertices.push(1, 1);
  28075. vertices.push(-1, 1);
  28076. vertices.push(-1, -1);
  28077. vertices.push(1, -1);
  28078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28079. // Indices
  28080. var indices = [];
  28081. indices.push(0);
  28082. indices.push(1);
  28083. indices.push(2);
  28084. indices.push(0);
  28085. indices.push(2);
  28086. indices.push(3);
  28087. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28088. };
  28089. // Methods
  28090. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28091. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28092. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28093. return false;
  28094. }
  28095. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28096. return true;
  28097. };
  28098. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28099. var engine = this._scene.getEngine();
  28100. for (var index = 0; index < postProcesses.length; index++) {
  28101. if (index < postProcesses.length - 1) {
  28102. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28103. }
  28104. else {
  28105. if (targetTexture) {
  28106. engine.bindFramebuffer(targetTexture);
  28107. }
  28108. else {
  28109. engine.restoreDefaultFramebuffer();
  28110. }
  28111. }
  28112. var pp = postProcesses[index];
  28113. var effect = pp.apply();
  28114. if (effect) {
  28115. pp.onBeforeRenderObservable.notifyObservers(effect);
  28116. // VBOs
  28117. this._prepareBuffers();
  28118. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28119. // Draw order
  28120. engine.draw(true, 0, 6);
  28121. pp.onAfterRenderObservable.notifyObservers(effect);
  28122. }
  28123. }
  28124. // Restore depth buffer
  28125. engine.setDepthBuffer(true);
  28126. engine.setDepthWrite(true);
  28127. };
  28128. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28129. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28130. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28131. return;
  28132. }
  28133. var engine = this._scene.getEngine();
  28134. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28135. if (index < len - 1) {
  28136. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28137. }
  28138. else {
  28139. if (targetTexture) {
  28140. engine.bindFramebuffer(targetTexture, faceIndex);
  28141. }
  28142. else {
  28143. engine.restoreDefaultFramebuffer();
  28144. }
  28145. }
  28146. if (doNotPresent) {
  28147. break;
  28148. }
  28149. var pp = postProcesses[index];
  28150. var effect = pp.apply();
  28151. if (effect) {
  28152. pp.onBeforeRenderObservable.notifyObservers(effect);
  28153. // VBOs
  28154. this._prepareBuffers();
  28155. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28156. // Draw order
  28157. engine.draw(true, 0, 6);
  28158. pp.onAfterRenderObservable.notifyObservers(effect);
  28159. }
  28160. }
  28161. // Restore states
  28162. engine.setDepthBuffer(true);
  28163. engine.setDepthWrite(true);
  28164. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28165. };
  28166. PostProcessManager.prototype.dispose = function () {
  28167. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28168. if (buffer) {
  28169. buffer.dispose();
  28170. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28171. }
  28172. if (this._indexBuffer) {
  28173. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28174. this._indexBuffer = null;
  28175. }
  28176. };
  28177. return PostProcessManager;
  28178. }());
  28179. BABYLON.PostProcessManager = PostProcessManager;
  28180. })(BABYLON || (BABYLON = {}));
  28181. //# sourceMappingURL=babylon.postProcessManager.js.map
  28182. var BABYLON;
  28183. (function (BABYLON) {
  28184. var ShaderMaterial = (function (_super) {
  28185. __extends(ShaderMaterial, _super);
  28186. function ShaderMaterial(name, scene, shaderPath, options) {
  28187. var _this = _super.call(this, name, scene) || this;
  28188. _this._textures = {};
  28189. _this._textureArrays = {};
  28190. _this._floats = {};
  28191. _this._floatsArrays = {};
  28192. _this._colors3 = {};
  28193. _this._colors4 = {};
  28194. _this._vectors2 = {};
  28195. _this._vectors3 = {};
  28196. _this._vectors4 = {};
  28197. _this._matrices = {};
  28198. _this._matrices3x3 = {};
  28199. _this._matrices2x2 = {};
  28200. _this._vectors3Arrays = {};
  28201. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28202. _this._shaderPath = shaderPath;
  28203. options.needAlphaBlending = options.needAlphaBlending || false;
  28204. options.needAlphaTesting = options.needAlphaTesting || false;
  28205. options.attributes = options.attributes || ["position", "normal", "uv"];
  28206. options.uniforms = options.uniforms || ["worldViewProjection"];
  28207. options.uniformBuffers = options.uniformBuffers || [];
  28208. options.samplers = options.samplers || [];
  28209. options.defines = options.defines || [];
  28210. _this._options = options;
  28211. return _this;
  28212. }
  28213. ShaderMaterial.prototype.getClassName = function () {
  28214. return "ShaderMaterial";
  28215. };
  28216. ShaderMaterial.prototype.needAlphaBlending = function () {
  28217. return this._options.needAlphaBlending;
  28218. };
  28219. ShaderMaterial.prototype.needAlphaTesting = function () {
  28220. return this._options.needAlphaTesting;
  28221. };
  28222. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28223. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28224. this._options.uniforms.push(uniformName);
  28225. }
  28226. };
  28227. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28228. if (this._options.samplers.indexOf(name) === -1) {
  28229. this._options.samplers.push(name);
  28230. }
  28231. this._textures[name] = texture;
  28232. return this;
  28233. };
  28234. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  28235. if (this._options.samplers.indexOf(name) === -1) {
  28236. this._options.samplers.push(name);
  28237. }
  28238. this._checkUniform(name);
  28239. this._textureArrays[name] = textures;
  28240. return this;
  28241. };
  28242. ShaderMaterial.prototype.setFloat = function (name, value) {
  28243. this._checkUniform(name);
  28244. this._floats[name] = value;
  28245. return this;
  28246. };
  28247. ShaderMaterial.prototype.setFloats = function (name, value) {
  28248. this._checkUniform(name);
  28249. this._floatsArrays[name] = value;
  28250. return this;
  28251. };
  28252. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28253. this._checkUniform(name);
  28254. this._colors3[name] = value;
  28255. return this;
  28256. };
  28257. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28258. this._checkUniform(name);
  28259. this._colors4[name] = value;
  28260. return this;
  28261. };
  28262. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28263. this._checkUniform(name);
  28264. this._vectors2[name] = value;
  28265. return this;
  28266. };
  28267. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28268. this._checkUniform(name);
  28269. this._vectors3[name] = value;
  28270. return this;
  28271. };
  28272. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28273. this._checkUniform(name);
  28274. this._vectors4[name] = value;
  28275. return this;
  28276. };
  28277. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28278. this._checkUniform(name);
  28279. this._matrices[name] = value;
  28280. return this;
  28281. };
  28282. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28283. this._checkUniform(name);
  28284. this._matrices3x3[name] = value;
  28285. return this;
  28286. };
  28287. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28288. this._checkUniform(name);
  28289. this._matrices2x2[name] = value;
  28290. return this;
  28291. };
  28292. ShaderMaterial.prototype.setArray3 = function (name, value) {
  28293. this._checkUniform(name);
  28294. this._vectors3Arrays[name] = value;
  28295. return this;
  28296. };
  28297. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28298. if (!mesh) {
  28299. return true;
  28300. }
  28301. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  28302. return false;
  28303. }
  28304. return false;
  28305. };
  28306. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28307. var scene = this.getScene();
  28308. var engine = scene.getEngine();
  28309. if (!this.checkReadyOnEveryCall) {
  28310. if (this._renderId === scene.getRenderId()) {
  28311. if (this._checkCache(scene, mesh, useInstances)) {
  28312. return true;
  28313. }
  28314. }
  28315. }
  28316. // Instances
  28317. var defines = [];
  28318. var attribs = [];
  28319. var fallbacks = new BABYLON.EffectFallbacks();
  28320. if (useInstances) {
  28321. defines.push("#define INSTANCES");
  28322. }
  28323. for (var index = 0; index < this._options.defines.length; index++) {
  28324. defines.push(this._options.defines[index]);
  28325. }
  28326. for (var index = 0; index < this._options.attributes.length; index++) {
  28327. attribs.push(this._options.attributes[index]);
  28328. }
  28329. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28330. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28331. defines.push("#define VERTEXCOLOR");
  28332. }
  28333. // Bones
  28334. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28337. if (mesh.numBoneInfluencers > 4) {
  28338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28340. }
  28341. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28342. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28343. fallbacks.addCPUSkinningFallback(0, mesh);
  28344. }
  28345. else {
  28346. defines.push("#define NUM_BONE_INFLUENCERS 0");
  28347. }
  28348. // Textures
  28349. for (var name in this._textures) {
  28350. if (!this._textures[name].isReady()) {
  28351. return false;
  28352. }
  28353. }
  28354. // Alpha test
  28355. if (engine.getAlphaTesting()) {
  28356. defines.push("#define ALPHATEST");
  28357. }
  28358. var previousEffect = this._effect;
  28359. var join = defines.join("\n");
  28360. this._effect = engine.createEffect(this._shaderPath, {
  28361. attributes: attribs,
  28362. uniformsNames: this._options.uniforms,
  28363. uniformBuffersNames: this._options.uniformBuffers,
  28364. samplers: this._options.samplers,
  28365. defines: join,
  28366. fallbacks: fallbacks,
  28367. onCompiled: this.onCompiled,
  28368. onError: this.onError
  28369. }, engine);
  28370. if (!this._effect.isReady()) {
  28371. return false;
  28372. }
  28373. if (previousEffect !== this._effect) {
  28374. scene.resetCachedMaterial();
  28375. }
  28376. this._renderId = scene.getRenderId();
  28377. return true;
  28378. };
  28379. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28380. var scene = this.getScene();
  28381. if (this._options.uniforms.indexOf("world") !== -1) {
  28382. this._effect.setMatrix("world", world);
  28383. }
  28384. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28385. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28386. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28387. }
  28388. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28389. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28390. }
  28391. };
  28392. ShaderMaterial.prototype.bind = function (world, mesh) {
  28393. // Std values
  28394. this.bindOnlyWorldMatrix(world);
  28395. if (this.getScene().getCachedMaterial() !== this) {
  28396. if (this._options.uniforms.indexOf("view") !== -1) {
  28397. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28398. }
  28399. if (this._options.uniforms.indexOf("projection") !== -1) {
  28400. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28401. }
  28402. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28403. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28404. }
  28405. // Bones
  28406. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28407. var name;
  28408. // Texture
  28409. for (name in this._textures) {
  28410. this._effect.setTexture(name, this._textures[name]);
  28411. }
  28412. // Texture arrays
  28413. for (name in this._textureArrays) {
  28414. this._effect.setTextureArray(name, this._textureArrays[name]);
  28415. }
  28416. // Float
  28417. for (name in this._floats) {
  28418. this._effect.setFloat(name, this._floats[name]);
  28419. }
  28420. // Float s
  28421. for (name in this._floatsArrays) {
  28422. this._effect.setArray(name, this._floatsArrays[name]);
  28423. }
  28424. // Color3
  28425. for (name in this._colors3) {
  28426. this._effect.setColor3(name, this._colors3[name]);
  28427. }
  28428. // Color4
  28429. for (name in this._colors4) {
  28430. var color = this._colors4[name];
  28431. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28432. }
  28433. // Vector2
  28434. for (name in this._vectors2) {
  28435. this._effect.setVector2(name, this._vectors2[name]);
  28436. }
  28437. // Vector3
  28438. for (name in this._vectors3) {
  28439. this._effect.setVector3(name, this._vectors3[name]);
  28440. }
  28441. // Vector4
  28442. for (name in this._vectors4) {
  28443. this._effect.setVector4(name, this._vectors4[name]);
  28444. }
  28445. // Matrix
  28446. for (name in this._matrices) {
  28447. this._effect.setMatrix(name, this._matrices[name]);
  28448. }
  28449. // Matrix 3x3
  28450. for (name in this._matrices3x3) {
  28451. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28452. }
  28453. // Matrix 2x2
  28454. for (name in this._matrices2x2) {
  28455. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28456. }
  28457. // Vector3Array
  28458. for (name in this._vectors3Arrays) {
  28459. this._effect.setArray3(name, this._vectors3Arrays[name]);
  28460. }
  28461. }
  28462. this._afterBind(mesh);
  28463. };
  28464. ShaderMaterial.prototype.clone = function (name) {
  28465. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28466. return newShaderMaterial;
  28467. };
  28468. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28469. if (forceDisposeTextures) {
  28470. var name;
  28471. for (name in this._textures) {
  28472. this._textures[name].dispose();
  28473. }
  28474. for (name in this._textureArrays) {
  28475. var array = this._textureArrays[name];
  28476. for (var index = 0; index < array.length; index++) {
  28477. array[index].dispose();
  28478. }
  28479. }
  28480. }
  28481. this._textures = {};
  28482. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28483. };
  28484. ShaderMaterial.prototype.serialize = function () {
  28485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28486. serializationObject.customType = "BABYLON.ShaderMaterial";
  28487. serializationObject.options = this._options;
  28488. serializationObject.shaderPath = this._shaderPath;
  28489. var name;
  28490. // Texture
  28491. serializationObject.textures = {};
  28492. for (name in this._textures) {
  28493. serializationObject.textures[name] = this._textures[name].serialize();
  28494. }
  28495. // Texture arrays
  28496. serializationObject.textureArrays = {};
  28497. for (name in this._textureArrays) {
  28498. serializationObject.textureArrays[name] = [];
  28499. var array = this._textureArrays[name];
  28500. for (var index = 0; index < array.length; index++) {
  28501. serializationObject.textureArrays[name].push(array[index].serialize());
  28502. }
  28503. }
  28504. // Float
  28505. serializationObject.floats = {};
  28506. for (name in this._floats) {
  28507. serializationObject.floats[name] = this._floats[name];
  28508. }
  28509. // Float s
  28510. serializationObject.floatArrays = {};
  28511. for (name in this._floatsArrays) {
  28512. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28513. }
  28514. // Color3
  28515. serializationObject.colors3 = {};
  28516. for (name in this._colors3) {
  28517. serializationObject.colors3[name] = this._colors3[name].asArray();
  28518. }
  28519. // Color4
  28520. serializationObject.colors4 = {};
  28521. for (name in this._colors4) {
  28522. serializationObject.colors4[name] = this._colors4[name].asArray();
  28523. }
  28524. // Vector2
  28525. serializationObject.vectors2 = {};
  28526. for (name in this._vectors2) {
  28527. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28528. }
  28529. // Vector3
  28530. serializationObject.vectors3 = {};
  28531. for (name in this._vectors3) {
  28532. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28533. }
  28534. // Vector4
  28535. serializationObject.vectors4 = {};
  28536. for (name in this._vectors4) {
  28537. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28538. }
  28539. // Matrix
  28540. serializationObject.matrices = {};
  28541. for (name in this._matrices) {
  28542. serializationObject.matrices[name] = this._matrices[name].asArray();
  28543. }
  28544. // Matrix 3x3
  28545. serializationObject.matrices3x3 = {};
  28546. for (name in this._matrices3x3) {
  28547. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28548. }
  28549. // Matrix 2x2
  28550. serializationObject.matrices2x2 = {};
  28551. for (name in this._matrices2x2) {
  28552. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28553. }
  28554. // Vector3Array
  28555. serializationObject.vectors3Arrays = {};
  28556. for (name in this._vectors3Arrays) {
  28557. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  28558. }
  28559. return serializationObject;
  28560. };
  28561. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28562. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  28563. var name;
  28564. // Texture
  28565. for (name in source.textures) {
  28566. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28567. }
  28568. // Texture arrays
  28569. for (name in source.textureArrays) {
  28570. var array = source.textureArrays[name];
  28571. var textureArray = new Array();
  28572. for (var index = 0; index < array.length; index++) {
  28573. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  28574. }
  28575. material.setTextureArray(name, textureArray);
  28576. }
  28577. // Float
  28578. for (name in source.floats) {
  28579. material.setFloat(name, source.floats[name]);
  28580. }
  28581. // Float s
  28582. for (name in source.floatsArrays) {
  28583. material.setFloats(name, source.floatsArrays[name]);
  28584. }
  28585. // Color3
  28586. for (name in source.colors3) {
  28587. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28588. }
  28589. // Color4
  28590. for (name in source.colors4) {
  28591. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28592. }
  28593. // Vector2
  28594. for (name in source.vectors2) {
  28595. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28596. }
  28597. // Vector3
  28598. for (name in source.vectors3) {
  28599. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28600. }
  28601. // Vector4
  28602. for (name in source.vectors4) {
  28603. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28604. }
  28605. // Matrix
  28606. for (name in source.matrices) {
  28607. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28608. }
  28609. // Matrix 3x3
  28610. for (name in source.matrices3x3) {
  28611. material.setMatrix3x3(name, source.matrices3x3[name]);
  28612. }
  28613. // Matrix 2x2
  28614. for (name in source.matrices2x2) {
  28615. material.setMatrix2x2(name, source.matrices2x2[name]);
  28616. }
  28617. // Vector3Array
  28618. for (name in source.vectors3Arrays) {
  28619. material.setArray3(name, source.vectors3Arrays[name]);
  28620. }
  28621. return material;
  28622. };
  28623. return ShaderMaterial;
  28624. }(BABYLON.Material));
  28625. BABYLON.ShaderMaterial = ShaderMaterial;
  28626. })(BABYLON || (BABYLON = {}));
  28627. //# sourceMappingURL=babylon.shaderMaterial.js.map
  28628. var BABYLON;
  28629. (function (BABYLON) {
  28630. var MeshBuilder = (function () {
  28631. function MeshBuilder() {
  28632. }
  28633. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  28634. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  28635. return BABYLON.Mesh.DOUBLESIDE;
  28636. }
  28637. if (orientation === undefined || orientation === null) {
  28638. return BABYLON.Mesh.FRONTSIDE;
  28639. }
  28640. return orientation;
  28641. };
  28642. /**
  28643. * Creates a box mesh.
  28644. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  28645. * The parameter `size` sets the size (float) of each box side (default 1).
  28646. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  28647. * 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).
  28648. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  28649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28650. * 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).
  28651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28653. */
  28654. MeshBuilder.CreateBox = function (name, options, scene) {
  28655. var box = new BABYLON.Mesh(name, scene);
  28656. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28657. box.sideOrientation = options.sideOrientation;
  28658. var vertexData = BABYLON.VertexData.CreateBox(options);
  28659. vertexData.applyToMesh(box, options.updatable);
  28660. return box;
  28661. };
  28662. /**
  28663. * Creates a sphere mesh.
  28664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  28665. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28666. * 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`).
  28667. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28668. * 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
  28669. * 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).
  28670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28671. * 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).
  28672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28674. */
  28675. MeshBuilder.CreateSphere = function (name, options, scene) {
  28676. var sphere = new BABYLON.Mesh(name, scene);
  28677. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28678. sphere.sideOrientation = options.sideOrientation;
  28679. var vertexData = BABYLON.VertexData.CreateSphere(options);
  28680. vertexData.applyToMesh(sphere, options.updatable);
  28681. return sphere;
  28682. };
  28683. /**
  28684. * Creates a plane polygonal mesh. By default, this is a disc.
  28685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  28686. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28687. * 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.
  28688. * 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
  28689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28690. * 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).
  28691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28693. */
  28694. MeshBuilder.CreateDisc = function (name, options, scene) {
  28695. var disc = new BABYLON.Mesh(name, scene);
  28696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28697. disc.sideOrientation = options.sideOrientation;
  28698. var vertexData = BABYLON.VertexData.CreateDisc(options);
  28699. vertexData.applyToMesh(disc, options.updatable);
  28700. return disc;
  28701. };
  28702. /**
  28703. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  28705. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28706. * 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`).
  28707. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28708. * 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.
  28709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28710. * 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).
  28711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28713. */
  28714. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  28715. var sphere = new BABYLON.Mesh(name, scene);
  28716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28717. sphere.sideOrientation = options.sideOrientation;
  28718. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  28719. vertexData.applyToMesh(sphere, options.updatable);
  28720. return sphere;
  28721. };
  28722. ;
  28723. /**
  28724. * Creates a ribbon mesh.
  28725. * 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.
  28726. *
  28727. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28728. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28729. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28730. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28731. * 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.
  28732. * 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.
  28733. * 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
  28734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28735. * 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).
  28736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28737. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  28738. * 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.
  28739. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  28740. * 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
  28741. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  28742. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  28743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28744. */
  28745. MeshBuilder.CreateRibbon = function (name, options, scene) {
  28746. var pathArray = options.pathArray;
  28747. var closeArray = options.closeArray;
  28748. var closePath = options.closePath;
  28749. var offset = options.offset;
  28750. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28751. var instance = options.instance;
  28752. var updatable = options.updatable;
  28753. if (instance) {
  28754. // positionFunction : ribbon case
  28755. // only pathArray and sideOrientation parameters are taken into account for positions update
  28756. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  28757. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  28758. var positionFunction = function (positions) {
  28759. var minlg = pathArray[0].length;
  28760. var i = 0;
  28761. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  28762. for (var si = 1; si <= ns; si++) {
  28763. for (var p = 0; p < pathArray.length; p++) {
  28764. var path = pathArray[p];
  28765. var l = path.length;
  28766. minlg = (minlg < l) ? minlg : l;
  28767. var j = 0;
  28768. while (j < minlg) {
  28769. positions[i] = path[j].x;
  28770. positions[i + 1] = path[j].y;
  28771. positions[i + 2] = path[j].z;
  28772. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  28773. BABYLON.Tmp.Vector3[0].x = path[j].x;
  28774. }
  28775. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  28776. BABYLON.Tmp.Vector3[1].x = path[j].x;
  28777. }
  28778. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  28779. BABYLON.Tmp.Vector3[0].y = path[j].y;
  28780. }
  28781. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  28782. BABYLON.Tmp.Vector3[1].y = path[j].y;
  28783. }
  28784. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  28785. BABYLON.Tmp.Vector3[0].z = path[j].z;
  28786. }
  28787. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  28788. BABYLON.Tmp.Vector3[1].z = path[j].z;
  28789. }
  28790. j++;
  28791. i += 3;
  28792. }
  28793. if (instance._closePath) {
  28794. positions[i] = path[0].x;
  28795. positions[i + 1] = path[0].y;
  28796. positions[i + 2] = path[0].z;
  28797. i += 3;
  28798. }
  28799. }
  28800. }
  28801. };
  28802. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28803. positionFunction(positions);
  28804. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  28805. instance._boundingInfo.update(instance._worldMatrix);
  28806. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28807. if (options.colors) {
  28808. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28809. for (var c = 0; c < options.colors.length; c++) {
  28810. colors[c * 4] = options.colors[c].r;
  28811. colors[c * 4 + 1] = options.colors[c].g;
  28812. colors[c * 4 + 2] = options.colors[c].b;
  28813. colors[c * 4 + 3] = options.colors[c].a;
  28814. }
  28815. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  28816. }
  28817. if (options.uvs) {
  28818. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28819. for (var i = 0; i < options.uvs.length; i++) {
  28820. uvs[i * 2] = options.uvs[i].x;
  28821. uvs[i * 2 + 1] = options.uvs[i].y;
  28822. }
  28823. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  28824. }
  28825. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  28826. var indices = instance.getIndices();
  28827. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28828. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  28829. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  28830. if (instance._closePath) {
  28831. var indexFirst = 0;
  28832. var indexLast = 0;
  28833. for (var p = 0; p < pathArray.length; p++) {
  28834. indexFirst = instance._idx[p] * 3;
  28835. if (p + 1 < pathArray.length) {
  28836. indexLast = (instance._idx[p + 1] - 1) * 3;
  28837. }
  28838. else {
  28839. indexLast = normals.length - 3;
  28840. }
  28841. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28842. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28843. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28844. normals[indexLast] = normals[indexFirst];
  28845. normals[indexLast + 1] = normals[indexFirst + 1];
  28846. normals[indexLast + 2] = normals[indexFirst + 2];
  28847. }
  28848. }
  28849. if (!(instance.areNormalsFrozen)) {
  28850. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28851. }
  28852. }
  28853. return instance;
  28854. }
  28855. else {
  28856. var ribbon = new BABYLON.Mesh(name, scene);
  28857. ribbon.sideOrientation = sideOrientation;
  28858. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  28859. if (closePath) {
  28860. ribbon._idx = vertexData._idx;
  28861. }
  28862. ribbon._closePath = closePath;
  28863. ribbon._closeArray = closeArray;
  28864. vertexData.applyToMesh(ribbon, updatable);
  28865. return ribbon;
  28866. }
  28867. };
  28868. /**
  28869. * Creates a cylinder or a cone mesh.
  28870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  28871. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28872. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28873. * 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.
  28874. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28875. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28876. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  28877. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  28878. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  28879. * 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).
  28880. * 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
  28881. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  28882. * 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
  28883. * 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.
  28884. * If `enclose` is false, a ring surface is one element.
  28885. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  28886. * 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
  28887. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28888. * 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).
  28889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28891. */
  28892. MeshBuilder.CreateCylinder = function (name, options, scene) {
  28893. var cylinder = new BABYLON.Mesh(name, scene);
  28894. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28895. cylinder.sideOrientation = options.sideOrientation;
  28896. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  28897. vertexData.applyToMesh(cylinder, options.updatable);
  28898. return cylinder;
  28899. };
  28900. /**
  28901. * Creates a torus mesh.
  28902. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  28903. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28904. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28905. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28907. * 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).
  28908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28910. */
  28911. MeshBuilder.CreateTorus = function (name, options, scene) {
  28912. var torus = new BABYLON.Mesh(name, scene);
  28913. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28914. torus.sideOrientation = options.sideOrientation;
  28915. var vertexData = BABYLON.VertexData.CreateTorus(options);
  28916. vertexData.applyToMesh(torus, options.updatable);
  28917. return torus;
  28918. };
  28919. /**
  28920. * Creates a torus knot mesh.
  28921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  28922. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28923. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28924. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28925. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28927. * 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).
  28928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28930. */
  28931. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  28932. var torusKnot = new BABYLON.Mesh(name, scene);
  28933. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28934. torusKnot.sideOrientation = options.sideOrientation;
  28935. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  28936. vertexData.applyToMesh(torusKnot, options.updatable);
  28937. return torusKnot;
  28938. };
  28939. /**
  28940. * Creates a line system mesh.
  28941. * A line system is a pool of many lines gathered in a single mesh.
  28942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  28943. * 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.
  28944. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  28945. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  28946. * 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
  28947. * 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
  28948. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  28949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28950. */
  28951. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  28952. var instance = options.instance;
  28953. var lines = options.lines;
  28954. if (instance) {
  28955. var positionFunction = function (positions) {
  28956. var i = 0;
  28957. for (var l = 0; l < lines.length; l++) {
  28958. var points = lines[l];
  28959. for (var p = 0; p < points.length; p++) {
  28960. positions[i] = points[p].x;
  28961. positions[i + 1] = points[p].y;
  28962. positions[i + 2] = points[p].z;
  28963. i += 3;
  28964. }
  28965. }
  28966. };
  28967. instance.updateMeshPositions(positionFunction, false);
  28968. return instance;
  28969. }
  28970. // line system creation
  28971. var lineSystem = new BABYLON.LinesMesh(name, scene);
  28972. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  28973. vertexData.applyToMesh(lineSystem, options.updatable);
  28974. return lineSystem;
  28975. };
  28976. /**
  28977. * Creates a line mesh.
  28978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  28979. * 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.
  28980. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28981. * The parameter `points` is an array successive Vector3.
  28982. * 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
  28983. * When updating an instance, remember that only point positions can change, not the number of points.
  28984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28985. */
  28986. MeshBuilder.CreateLines = function (name, options, scene) {
  28987. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  28988. return lines;
  28989. };
  28990. /**
  28991. * Creates a dashed line mesh.
  28992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  28993. * 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.
  28994. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28995. * The parameter `points` is an array successive Vector3.
  28996. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28997. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28998. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28999. * 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
  29000. * When updating an instance, remember that only point positions can change, not the number of points.
  29001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29002. */
  29003. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  29004. var points = options.points;
  29005. var instance = options.instance;
  29006. var gapSize = options.gapSize;
  29007. var dashNb = options.dashNb;
  29008. var dashSize = options.dashSize;
  29009. if (instance) {
  29010. var positionFunction = function (positions) {
  29011. var curvect = BABYLON.Vector3.Zero();
  29012. var nbSeg = positions.length / 6;
  29013. var lg = 0;
  29014. var nb = 0;
  29015. var shft = 0;
  29016. var dashshft = 0;
  29017. var curshft = 0;
  29018. var p = 0;
  29019. var i = 0;
  29020. var j = 0;
  29021. for (i = 0; i < points.length - 1; i++) {
  29022. points[i + 1].subtractToRef(points[i], curvect);
  29023. lg += curvect.length();
  29024. }
  29025. shft = lg / nbSeg;
  29026. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  29027. for (i = 0; i < points.length - 1; i++) {
  29028. points[i + 1].subtractToRef(points[i], curvect);
  29029. nb = Math.floor(curvect.length() / shft);
  29030. curvect.normalize();
  29031. j = 0;
  29032. while (j < nb && p < positions.length) {
  29033. curshft = shft * j;
  29034. positions[p] = points[i].x + curshft * curvect.x;
  29035. positions[p + 1] = points[i].y + curshft * curvect.y;
  29036. positions[p + 2] = points[i].z + curshft * curvect.z;
  29037. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  29038. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  29039. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  29040. p += 6;
  29041. j++;
  29042. }
  29043. }
  29044. while (p < positions.length) {
  29045. positions[p] = points[i].x;
  29046. positions[p + 1] = points[i].y;
  29047. positions[p + 2] = points[i].z;
  29048. p += 3;
  29049. }
  29050. };
  29051. instance.updateMeshPositions(positionFunction, false);
  29052. return instance;
  29053. }
  29054. // dashed lines creation
  29055. var dashedLines = new BABYLON.LinesMesh(name, scene);
  29056. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  29057. vertexData.applyToMesh(dashedLines, options.updatable);
  29058. dashedLines.dashSize = dashSize;
  29059. dashedLines.gapSize = gapSize;
  29060. return dashedLines;
  29061. };
  29062. /**
  29063. * Creates an extruded shape mesh.
  29064. * 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.
  29065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  29066. *
  29067. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29068. * 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
  29069. * extruded along the Z axis.
  29070. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29071. * 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.
  29072. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29073. * 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
  29074. * 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
  29075. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29077. * 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).
  29078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29079. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29081. */
  29082. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  29083. var path = options.path;
  29084. var shape = options.shape;
  29085. var scale = options.scale || 1;
  29086. var rotation = options.rotation || 0;
  29087. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29088. var updatable = options.updatable;
  29089. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29090. var instance = options.instance;
  29091. var invertUV = options.invertUV || false;
  29092. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29093. };
  29094. /**
  29095. * Creates an custom extruded shape mesh.
  29096. * 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.
  29097. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  29098. *
  29099. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29100. * 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
  29101. * extruded along the Z axis.
  29102. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29103. * 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
  29104. * and the distance of this point from the begining of the path :
  29105. * ```javascript
  29106. * var rotationFunction = function(i, distance) {
  29107. * // do things
  29108. * return rotationValue; }
  29109. * ```
  29110. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29111. * 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
  29112. * and the distance of this point from the begining of the path :
  29113. * ```javascript
  29114. * var scaleFunction = function(i, distance) {
  29115. * // do things
  29116. * return scaleValue;}
  29117. * ```
  29118. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29119. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29120. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29121. * 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
  29122. * 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
  29123. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29125. * 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).
  29126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29127. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29129. */
  29130. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  29131. var path = options.path;
  29132. var shape = options.shape;
  29133. var scaleFunction = options.scaleFunction || (function () { return 1; });
  29134. var rotationFunction = options.rotationFunction || (function () { return 0; });
  29135. var ribbonCloseArray = options.ribbonCloseArray || false;
  29136. var ribbonClosePath = options.ribbonClosePath || false;
  29137. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29138. var updatable = options.updatable;
  29139. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29140. var instance = options.instance;
  29141. var invertUV = options.invertUV || false;
  29142. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29143. };
  29144. /**
  29145. * Creates lathe mesh.
  29146. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29147. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  29148. *
  29149. * 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
  29150. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29151. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29152. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29153. * 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.
  29154. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  29155. * 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
  29156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29157. * 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).
  29158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29159. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29161. */
  29162. MeshBuilder.CreateLathe = function (name, options, scene) {
  29163. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  29164. var closed = (options.closed === undefined) ? true : options.closed;
  29165. var shape = options.shape;
  29166. var radius = options.radius || 1;
  29167. var tessellation = options.tessellation || 64;
  29168. var updatable = options.updatable;
  29169. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29170. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29171. var pi2 = Math.PI * 2;
  29172. var paths = new Array();
  29173. var invertUV = options.invertUV || false;
  29174. var i = 0;
  29175. var p = 0;
  29176. var step = pi2 / tessellation * arc;
  29177. var rotated;
  29178. var path = new Array();
  29179. ;
  29180. for (i = 0; i <= tessellation; i++) {
  29181. var path = [];
  29182. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  29183. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  29184. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  29185. }
  29186. for (p = 0; p < shape.length; p++) {
  29187. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  29188. path.push(rotated);
  29189. }
  29190. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  29191. 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));
  29192. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  29193. }
  29194. paths.push(path);
  29195. }
  29196. // lathe ribbon
  29197. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29198. return lathe;
  29199. };
  29200. /**
  29201. * Creates a plane mesh.
  29202. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29203. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29204. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  29205. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  29206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29207. * 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).
  29208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29210. */
  29211. MeshBuilder.CreatePlane = function (name, options, scene) {
  29212. var plane = new BABYLON.Mesh(name, scene);
  29213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29214. plane.sideOrientation = options.sideOrientation;
  29215. var vertexData = BABYLON.VertexData.CreatePlane(options);
  29216. vertexData.applyToMesh(plane, options.updatable);
  29217. if (options.sourcePlane) {
  29218. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  29219. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  29220. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  29221. plane.rotate(vectorProduct, product);
  29222. }
  29223. return plane;
  29224. };
  29225. /**
  29226. * Creates a ground mesh.
  29227. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29228. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29229. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29231. */
  29232. MeshBuilder.CreateGround = function (name, options, scene) {
  29233. var ground = new BABYLON.GroundMesh(name, scene);
  29234. ground._setReady(false);
  29235. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29236. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29237. ground._width = options.width || 1;
  29238. ground._height = options.height || 1;
  29239. ground._maxX = ground._width / 2;
  29240. ground._maxZ = ground._height / 2;
  29241. ground._minX = -ground._maxX;
  29242. ground._minZ = -ground._maxZ;
  29243. var vertexData = BABYLON.VertexData.CreateGround(options);
  29244. vertexData.applyToMesh(ground, options.updatable);
  29245. ground._setReady(true);
  29246. return ground;
  29247. };
  29248. /**
  29249. * Creates a tiled ground mesh.
  29250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  29251. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29252. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29253. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29254. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29255. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29256. * numbers of subdivisions on the ground width and height of each tile.
  29257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29258. */
  29259. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  29260. var tiledGround = new BABYLON.Mesh(name, scene);
  29261. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  29262. vertexData.applyToMesh(tiledGround, options.updatable);
  29263. return tiledGround;
  29264. };
  29265. /**
  29266. * Creates a ground mesh from a height map.
  29267. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29268. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  29269. * The parameter `url` sets the URL of the height map image resource.
  29270. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29271. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29272. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29273. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29274. * 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.
  29275. * 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).
  29276. * This function is passed the newly built mesh :
  29277. * ```javascript
  29278. * function(mesh) { // do things
  29279. * return; }
  29280. * ```
  29281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29282. */
  29283. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  29284. var width = options.width || 10.0;
  29285. var height = options.height || 10.0;
  29286. var subdivisions = options.subdivisions || 1 | 0;
  29287. var minHeight = options.minHeight || 0.0;
  29288. var maxHeight = options.maxHeight || 10.0;
  29289. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29290. var updatable = options.updatable;
  29291. var onReady = options.onReady;
  29292. var ground = new BABYLON.GroundMesh(name, scene);
  29293. ground._subdivisionsX = subdivisions;
  29294. ground._subdivisionsY = subdivisions;
  29295. ground._width = width;
  29296. ground._height = height;
  29297. ground._maxX = ground._width / 2.0;
  29298. ground._maxZ = ground._height / 2.0;
  29299. ground._minX = -ground._maxX;
  29300. ground._minZ = -ground._maxZ;
  29301. ground._setReady(false);
  29302. var onload = function (img) {
  29303. // Getting height map data
  29304. var canvas = document.createElement("canvas");
  29305. var context = canvas.getContext("2d");
  29306. var bufferWidth = img.width;
  29307. var bufferHeight = img.height;
  29308. canvas.width = bufferWidth;
  29309. canvas.height = bufferHeight;
  29310. context.drawImage(img, 0, 0);
  29311. // Create VertexData from map data
  29312. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29313. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  29314. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  29315. width: width, height: height,
  29316. subdivisions: subdivisions,
  29317. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  29318. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  29319. });
  29320. vertexData.applyToMesh(ground, updatable);
  29321. ground._setReady(true);
  29322. //execute ready callback, if set
  29323. if (onReady) {
  29324. onReady(ground);
  29325. }
  29326. };
  29327. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29328. return ground;
  29329. };
  29330. /**
  29331. * Creates a polygon mesh.
  29332. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29333. * 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.
  29334. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29336. * 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).
  29337. * Remember you can only change the shape positions, not their number when updating a polygon.
  29338. */
  29339. MeshBuilder.CreatePolygon = function (name, options, scene) {
  29340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29341. var shape = options.shape;
  29342. var holes = options.holes || [];
  29343. var depth = options.depth || 0;
  29344. var contours = [];
  29345. var hole = [];
  29346. for (var i = 0; i < shape.length; i++) {
  29347. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  29348. }
  29349. var epsilon = 0.00000001;
  29350. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  29351. contours.pop();
  29352. }
  29353. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  29354. for (var hNb = 0; hNb < holes.length; hNb++) {
  29355. hole = [];
  29356. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  29357. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  29358. }
  29359. polygonTriangulation.addHole(hole);
  29360. }
  29361. var polygon = polygonTriangulation.build(options.updatable, depth);
  29362. polygon.sideOrientation = options.sideOrientation;
  29363. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  29364. vertexData.applyToMesh(polygon, options.updatable);
  29365. return polygon;
  29366. };
  29367. ;
  29368. /**
  29369. * Creates an extruded polygon mesh, with depth in the Y direction.
  29370. * 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).
  29371. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  29372. */
  29373. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  29374. return MeshBuilder.CreatePolygon(name, options, scene);
  29375. };
  29376. ;
  29377. /**
  29378. * Creates a tube mesh.
  29379. * 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.
  29380. *
  29381. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  29382. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29383. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29384. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29385. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29386. * 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.
  29387. * It must return a radius value (positive float) :
  29388. * ```javascript
  29389. * var radiusFunction = function(i, distance) {
  29390. * // do things
  29391. * return radius; }
  29392. * ```
  29393. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  29394. * 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
  29395. * 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
  29396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29397. * 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).
  29398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29399. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29401. */
  29402. MeshBuilder.CreateTube = function (name, options, scene) {
  29403. var path = options.path;
  29404. var radius = options.radius || 1.0;
  29405. var tessellation = options.tessellation || 64 | 0;
  29406. var radiusFunction = options.radiusFunction;
  29407. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29408. var invertUV = options.invertUV || false;
  29409. var updatable = options.updatable;
  29410. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29411. var instance = options.instance;
  29412. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  29413. // tube geometry
  29414. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  29415. var tangents = path3D.getTangents();
  29416. var normals = path3D.getNormals();
  29417. var distances = path3D.getDistances();
  29418. var pi2 = Math.PI * 2;
  29419. var step = pi2 / tessellation * arc;
  29420. var returnRadius = function () { return radius; };
  29421. var radiusFunctionFinal = radiusFunction || returnRadius;
  29422. var circlePath;
  29423. var rad;
  29424. var normal;
  29425. var rotated;
  29426. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29427. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29428. for (var i = 0; i < path.length; i++) {
  29429. rad = radiusFunctionFinal(i, distances[i]); // current radius
  29430. circlePath = Array(); // current circle array
  29431. normal = normals[i]; // current normal
  29432. for (var t = 0; t < tessellation; t++) {
  29433. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  29434. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  29435. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  29436. rotated.scaleInPlace(rad).addInPlace(path[i]);
  29437. circlePath[t] = rotated;
  29438. }
  29439. circlePaths[index] = circlePath;
  29440. index++;
  29441. }
  29442. // cap
  29443. var capPath = function (nbPoints, pathIndex) {
  29444. var pointCap = Array();
  29445. for (var i = 0; i < nbPoints; i++) {
  29446. pointCap.push(path[pathIndex]);
  29447. }
  29448. return pointCap;
  29449. };
  29450. switch (cap) {
  29451. case BABYLON.Mesh.NO_CAP:
  29452. break;
  29453. case BABYLON.Mesh.CAP_START:
  29454. circlePaths[0] = capPath(tessellation, 0);
  29455. circlePaths[1] = circlePaths[2].slice(0);
  29456. break;
  29457. case BABYLON.Mesh.CAP_END:
  29458. circlePaths[index] = circlePaths[index - 1].slice(0);
  29459. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29460. break;
  29461. case BABYLON.Mesh.CAP_ALL:
  29462. circlePaths[0] = capPath(tessellation, 0);
  29463. circlePaths[1] = circlePaths[2].slice(0);
  29464. circlePaths[index] = circlePaths[index - 1].slice(0);
  29465. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29466. break;
  29467. default:
  29468. break;
  29469. }
  29470. return circlePaths;
  29471. };
  29472. var path3D;
  29473. var pathArray;
  29474. if (instance) {
  29475. var arc = options.arc || instance.arc;
  29476. path3D = (instance.path3D).update(path);
  29477. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  29478. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  29479. instance.path3D = path3D;
  29480. instance.pathArray = pathArray;
  29481. instance.arc = arc;
  29482. return instance;
  29483. }
  29484. // tube creation
  29485. path3D = new BABYLON.Path3D(path);
  29486. var newPathArray = new Array();
  29487. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29488. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  29489. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29490. tube.pathArray = pathArray;
  29491. tube.path3D = path3D;
  29492. tube.tessellation = tessellation;
  29493. tube.cap = cap;
  29494. tube.arc = options.arc;
  29495. return tube;
  29496. };
  29497. /**
  29498. * Creates a polyhedron mesh.
  29499. *
  29500. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  29501. * 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
  29502. * to choose the wanted type.
  29503. * The parameter `size` (positive float, default 1) sets the polygon size.
  29504. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29505. * 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`.
  29506. * 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
  29507. * 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)`).
  29508. * 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
  29509. * 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.
  29510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29511. * 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).
  29512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29514. */
  29515. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  29516. var polyhedron = new BABYLON.Mesh(name, scene);
  29517. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29518. polyhedron.sideOrientation = options.sideOrientation;
  29519. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  29520. vertexData.applyToMesh(polyhedron, options.updatable);
  29521. return polyhedron;
  29522. };
  29523. /**
  29524. * Creates a decal mesh.
  29525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  29526. * 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.
  29527. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29528. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29529. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29530. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29531. */
  29532. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  29533. var indices = sourceMesh.getIndices();
  29534. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29535. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29536. var position = options.position || BABYLON.Vector3.Zero();
  29537. var normal = options.normal || BABYLON.Vector3.Up();
  29538. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  29539. var angle = options.angle || 0;
  29540. // Getting correct rotation
  29541. if (!normal) {
  29542. var target = new BABYLON.Vector3(0, 0, 1);
  29543. var camera = sourceMesh.getScene().activeCamera;
  29544. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  29545. normal = camera.globalPosition.subtract(cameraWorldTarget);
  29546. }
  29547. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  29548. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  29549. var pitch = Math.atan2(normal.y, len);
  29550. // Matrix
  29551. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  29552. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  29553. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  29554. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  29555. var vertexData = new BABYLON.VertexData();
  29556. vertexData.indices = [];
  29557. vertexData.positions = [];
  29558. vertexData.normals = [];
  29559. vertexData.uvs = [];
  29560. var currentVertexDataIndex = 0;
  29561. var extractDecalVector3 = function (indexId) {
  29562. var vertexId = indices[indexId];
  29563. var result = new BABYLON.PositionNormalVertex();
  29564. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  29565. // Send vector to decal local world
  29566. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  29567. // Get normal
  29568. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  29569. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  29570. return result;
  29571. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  29572. var clip = function (vertices, axis) {
  29573. if (vertices.length === 0) {
  29574. return vertices;
  29575. }
  29576. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  29577. var clipVertices = function (v0, v1) {
  29578. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  29579. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  29580. };
  29581. var result = new Array();
  29582. for (var index = 0; index < vertices.length; index += 3) {
  29583. var v1Out;
  29584. var v2Out;
  29585. var v3Out;
  29586. var total = 0;
  29587. var nV1, nV2, nV3, nV4;
  29588. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  29589. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  29590. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  29591. v1Out = d1 > 0;
  29592. v2Out = d2 > 0;
  29593. v3Out = d3 > 0;
  29594. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  29595. switch (total) {
  29596. case 0:
  29597. result.push(vertices[index]);
  29598. result.push(vertices[index + 1]);
  29599. result.push(vertices[index + 2]);
  29600. break;
  29601. case 1:
  29602. if (v1Out) {
  29603. nV1 = vertices[index + 1];
  29604. nV2 = vertices[index + 2];
  29605. nV3 = clipVertices(vertices[index], nV1);
  29606. nV4 = clipVertices(vertices[index], nV2);
  29607. }
  29608. if (v2Out) {
  29609. nV1 = vertices[index];
  29610. nV2 = vertices[index + 2];
  29611. nV3 = clipVertices(vertices[index + 1], nV1);
  29612. nV4 = clipVertices(vertices[index + 1], nV2);
  29613. result.push(nV3);
  29614. result.push(nV2.clone());
  29615. result.push(nV1.clone());
  29616. result.push(nV2.clone());
  29617. result.push(nV3.clone());
  29618. result.push(nV4);
  29619. break;
  29620. }
  29621. if (v3Out) {
  29622. nV1 = vertices[index];
  29623. nV2 = vertices[index + 1];
  29624. nV3 = clipVertices(vertices[index + 2], nV1);
  29625. nV4 = clipVertices(vertices[index + 2], nV2);
  29626. }
  29627. result.push(nV1.clone());
  29628. result.push(nV2.clone());
  29629. result.push(nV3);
  29630. result.push(nV4);
  29631. result.push(nV3.clone());
  29632. result.push(nV2.clone());
  29633. break;
  29634. case 2:
  29635. if (!v1Out) {
  29636. nV1 = vertices[index].clone();
  29637. nV2 = clipVertices(nV1, vertices[index + 1]);
  29638. nV3 = clipVertices(nV1, vertices[index + 2]);
  29639. result.push(nV1);
  29640. result.push(nV2);
  29641. result.push(nV3);
  29642. }
  29643. if (!v2Out) {
  29644. nV1 = vertices[index + 1].clone();
  29645. nV2 = clipVertices(nV1, vertices[index + 2]);
  29646. nV3 = clipVertices(nV1, vertices[index]);
  29647. result.push(nV1);
  29648. result.push(nV2);
  29649. result.push(nV3);
  29650. }
  29651. if (!v3Out) {
  29652. nV1 = vertices[index + 2].clone();
  29653. nV2 = clipVertices(nV1, vertices[index]);
  29654. nV3 = clipVertices(nV1, vertices[index + 1]);
  29655. result.push(nV1);
  29656. result.push(nV2);
  29657. result.push(nV3);
  29658. }
  29659. break;
  29660. case 3:
  29661. break;
  29662. }
  29663. }
  29664. return result;
  29665. };
  29666. for (var index = 0; index < indices.length; index += 3) {
  29667. var faceVertices = new Array();
  29668. faceVertices.push(extractDecalVector3(index));
  29669. faceVertices.push(extractDecalVector3(index + 1));
  29670. faceVertices.push(extractDecalVector3(index + 2));
  29671. // Clip
  29672. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  29673. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  29674. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  29675. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  29676. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  29677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  29678. if (faceVertices.length === 0) {
  29679. continue;
  29680. }
  29681. // Add UVs and get back to world
  29682. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  29683. var vertex = faceVertices[vIndex];
  29684. //TODO check for Int32Array | Uint32Array | Uint16Array
  29685. vertexData.indices.push(currentVertexDataIndex);
  29686. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  29687. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  29688. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  29689. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  29690. currentVertexDataIndex++;
  29691. }
  29692. }
  29693. // Return mesh
  29694. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  29695. vertexData.applyToMesh(decal);
  29696. decal.position = position.clone();
  29697. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  29698. return decal;
  29699. };
  29700. // Privates
  29701. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  29702. // extrusion geometry
  29703. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  29704. var tangents = path3D.getTangents();
  29705. var normals = path3D.getNormals();
  29706. var binormals = path3D.getBinormals();
  29707. var distances = path3D.getDistances();
  29708. var angle = 0;
  29709. var returnScale = function () { return scale; };
  29710. var returnRotation = function () { return rotation; };
  29711. var rotate = custom ? rotateFunction : returnRotation;
  29712. var scl = custom ? scaleFunction : returnScale;
  29713. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29714. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29715. for (var i = 0; i < curve.length; i++) {
  29716. var shapePath = new Array();
  29717. var angleStep = rotate(i, distances[i]);
  29718. var scaleRatio = scl(i, distances[i]);
  29719. for (var p = 0; p < shape.length; p++) {
  29720. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  29721. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  29722. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  29723. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  29724. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  29725. shapePath[p] = rotated;
  29726. }
  29727. shapePaths[index] = shapePath;
  29728. angle += angleStep;
  29729. index++;
  29730. }
  29731. // cap
  29732. var capPath = function (shapePath) {
  29733. var pointCap = Array();
  29734. var barycenter = BABYLON.Vector3.Zero();
  29735. var i;
  29736. for (i = 0; i < shapePath.length; i++) {
  29737. barycenter.addInPlace(shapePath[i]);
  29738. }
  29739. barycenter.scaleInPlace(1.0 / shapePath.length);
  29740. for (i = 0; i < shapePath.length; i++) {
  29741. pointCap.push(barycenter);
  29742. }
  29743. return pointCap;
  29744. };
  29745. switch (cap) {
  29746. case BABYLON.Mesh.NO_CAP:
  29747. break;
  29748. case BABYLON.Mesh.CAP_START:
  29749. shapePaths[0] = capPath(shapePaths[2]);
  29750. shapePaths[1] = shapePaths[2];
  29751. break;
  29752. case BABYLON.Mesh.CAP_END:
  29753. shapePaths[index] = shapePaths[index - 1];
  29754. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29755. break;
  29756. case BABYLON.Mesh.CAP_ALL:
  29757. shapePaths[0] = capPath(shapePaths[2]);
  29758. shapePaths[1] = shapePaths[2];
  29759. shapePaths[index] = shapePaths[index - 1];
  29760. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29761. break;
  29762. default:
  29763. break;
  29764. }
  29765. return shapePaths;
  29766. };
  29767. var path3D;
  29768. var pathArray;
  29769. if (instance) {
  29770. path3D = (instance.path3D).update(curve);
  29771. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  29772. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  29773. return instance;
  29774. }
  29775. // extruded shape creation
  29776. path3D = new BABYLON.Path3D(curve);
  29777. var newShapePaths = new Array();
  29778. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29779. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  29780. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  29781. extrudedGeneric.pathArray = pathArray;
  29782. extrudedGeneric.path3D = path3D;
  29783. extrudedGeneric.cap = cap;
  29784. return extrudedGeneric;
  29785. };
  29786. return MeshBuilder;
  29787. }());
  29788. BABYLON.MeshBuilder = MeshBuilder;
  29789. })(BABYLON || (BABYLON = {}));
  29790. //# sourceMappingURL=babylon.meshBuilder.js.map
  29791. var BABYLON;
  29792. (function (BABYLON) {
  29793. var AnimationRange = (function () {
  29794. function AnimationRange(name, from, to) {
  29795. this.name = name;
  29796. this.from = from;
  29797. this.to = to;
  29798. }
  29799. AnimationRange.prototype.clone = function () {
  29800. return new AnimationRange(this.name, this.from, this.to);
  29801. };
  29802. return AnimationRange;
  29803. }());
  29804. BABYLON.AnimationRange = AnimationRange;
  29805. /**
  29806. * Composed of a frame, and an action function
  29807. */
  29808. var AnimationEvent = (function () {
  29809. function AnimationEvent(frame, action, onlyOnce) {
  29810. this.frame = frame;
  29811. this.action = action;
  29812. this.onlyOnce = onlyOnce;
  29813. this.isDone = false;
  29814. }
  29815. return AnimationEvent;
  29816. }());
  29817. BABYLON.AnimationEvent = AnimationEvent;
  29818. var PathCursor = (function () {
  29819. function PathCursor(path) {
  29820. this.path = path;
  29821. this._onchange = new Array();
  29822. this.value = 0;
  29823. this.animations = new Array();
  29824. }
  29825. PathCursor.prototype.getPoint = function () {
  29826. var point = this.path.getPointAtLengthPosition(this.value);
  29827. return new BABYLON.Vector3(point.x, 0, point.y);
  29828. };
  29829. PathCursor.prototype.moveAhead = function (step) {
  29830. if (step === void 0) { step = 0.002; }
  29831. this.move(step);
  29832. return this;
  29833. };
  29834. PathCursor.prototype.moveBack = function (step) {
  29835. if (step === void 0) { step = 0.002; }
  29836. this.move(-step);
  29837. return this;
  29838. };
  29839. PathCursor.prototype.move = function (step) {
  29840. if (Math.abs(step) > 1) {
  29841. throw "step size should be less than 1.";
  29842. }
  29843. this.value += step;
  29844. this.ensureLimits();
  29845. this.raiseOnChange();
  29846. return this;
  29847. };
  29848. PathCursor.prototype.ensureLimits = function () {
  29849. while (this.value > 1) {
  29850. this.value -= 1;
  29851. }
  29852. while (this.value < 0) {
  29853. this.value += 1;
  29854. }
  29855. return this;
  29856. };
  29857. // used by animation engine
  29858. PathCursor.prototype.markAsDirty = function (propertyName) {
  29859. this.ensureLimits();
  29860. this.raiseOnChange();
  29861. return this;
  29862. };
  29863. PathCursor.prototype.raiseOnChange = function () {
  29864. var _this = this;
  29865. this._onchange.forEach(function (f) { return f(_this); });
  29866. return this;
  29867. };
  29868. PathCursor.prototype.onchange = function (f) {
  29869. this._onchange.push(f);
  29870. return this;
  29871. };
  29872. return PathCursor;
  29873. }());
  29874. BABYLON.PathCursor = PathCursor;
  29875. var Animation = (function () {
  29876. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29877. this.name = name;
  29878. this.targetProperty = targetProperty;
  29879. this.framePerSecond = framePerSecond;
  29880. this.dataType = dataType;
  29881. this.loopMode = loopMode;
  29882. this.enableBlending = enableBlending;
  29883. this._offsetsCache = {};
  29884. this._highLimitsCache = {};
  29885. this._stopped = false;
  29886. this._blendingFactor = 0;
  29887. // The set of event that will be linked to this animation
  29888. this._events = new Array();
  29889. this.allowMatricesInterpolation = false;
  29890. this.blendingSpeed = 0.01;
  29891. this._ranges = {};
  29892. this.targetPropertyPath = targetProperty.split(".");
  29893. this.dataType = dataType;
  29894. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29895. }
  29896. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29897. var dataType = undefined;
  29898. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29899. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29900. }
  29901. else if (from instanceof BABYLON.Quaternion) {
  29902. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29903. }
  29904. else if (from instanceof BABYLON.Vector3) {
  29905. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29906. }
  29907. else if (from instanceof BABYLON.Vector2) {
  29908. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29909. }
  29910. else if (from instanceof BABYLON.Color3) {
  29911. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29912. }
  29913. else if (from instanceof BABYLON.Size) {
  29914. dataType = Animation.ANIMATIONTYPE_SIZE;
  29915. }
  29916. if (dataType == undefined) {
  29917. return null;
  29918. }
  29919. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29920. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29921. animation.setKeys(keys);
  29922. if (easingFunction !== undefined) {
  29923. animation.setEasingFunction(easingFunction);
  29924. }
  29925. return animation;
  29926. };
  29927. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29928. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29929. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29930. };
  29931. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29932. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29933. node.animations.push(animation);
  29934. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29935. };
  29936. // Methods
  29937. /**
  29938. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29939. */
  29940. Animation.prototype.toString = function (fullDetails) {
  29941. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29942. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29943. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29944. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29945. if (fullDetails) {
  29946. ret += ", Ranges: {";
  29947. var first = true;
  29948. for (var name in this._ranges) {
  29949. if (first) {
  29950. ret += ", ";
  29951. first = false;
  29952. }
  29953. ret += name;
  29954. }
  29955. ret += "}";
  29956. }
  29957. return ret;
  29958. };
  29959. /**
  29960. * Add an event to this animation.
  29961. */
  29962. Animation.prototype.addEvent = function (event) {
  29963. this._events.push(event);
  29964. };
  29965. /**
  29966. * Remove all events found at the given frame
  29967. * @param frame
  29968. */
  29969. Animation.prototype.removeEvents = function (frame) {
  29970. for (var index = 0; index < this._events.length; index++) {
  29971. if (this._events[index].frame === frame) {
  29972. this._events.splice(index, 1);
  29973. index--;
  29974. }
  29975. }
  29976. };
  29977. Animation.prototype.createRange = function (name, from, to) {
  29978. // check name not already in use; could happen for bones after serialized
  29979. if (!this._ranges[name]) {
  29980. this._ranges[name] = new AnimationRange(name, from, to);
  29981. }
  29982. };
  29983. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29984. if (deleteFrames === void 0) { deleteFrames = true; }
  29985. if (this._ranges[name]) {
  29986. if (deleteFrames) {
  29987. var from = this._ranges[name].from;
  29988. var to = this._ranges[name].to;
  29989. // this loop MUST go high to low for multiple splices to work
  29990. for (var key = this._keys.length - 1; key >= 0; key--) {
  29991. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29992. this._keys.splice(key, 1);
  29993. }
  29994. }
  29995. }
  29996. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29997. }
  29998. };
  29999. Animation.prototype.getRange = function (name) {
  30000. return this._ranges[name];
  30001. };
  30002. Animation.prototype.reset = function () {
  30003. this._offsetsCache = {};
  30004. this._highLimitsCache = {};
  30005. this.currentFrame = 0;
  30006. this._blendingFactor = 0;
  30007. this._originalBlendValue = null;
  30008. };
  30009. Animation.prototype.isStopped = function () {
  30010. return this._stopped;
  30011. };
  30012. Animation.prototype.getKeys = function () {
  30013. return this._keys;
  30014. };
  30015. Animation.prototype.getHighestFrame = function () {
  30016. var ret = 0;
  30017. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30018. if (ret < this._keys[key].frame) {
  30019. ret = this._keys[key].frame;
  30020. }
  30021. }
  30022. return ret;
  30023. };
  30024. Animation.prototype.getEasingFunction = function () {
  30025. return this._easingFunction;
  30026. };
  30027. Animation.prototype.setEasingFunction = function (easingFunction) {
  30028. this._easingFunction = easingFunction;
  30029. };
  30030. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30031. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30032. };
  30033. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30034. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30035. };
  30036. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30037. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30038. };
  30039. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30040. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30041. };
  30042. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30043. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30044. };
  30045. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30046. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30047. };
  30048. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30049. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30050. };
  30051. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30052. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30053. };
  30054. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30055. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30056. };
  30057. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30058. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30059. };
  30060. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30061. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30062. };
  30063. Animation.prototype.clone = function () {
  30064. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30065. clone.enableBlending = this.enableBlending;
  30066. clone.blendingSpeed = this.blendingSpeed;
  30067. if (this._keys) {
  30068. clone.setKeys(this._keys);
  30069. }
  30070. if (this._ranges) {
  30071. clone._ranges = {};
  30072. for (var name in this._ranges) {
  30073. clone._ranges[name] = this._ranges[name].clone();
  30074. }
  30075. }
  30076. return clone;
  30077. };
  30078. Animation.prototype.setKeys = function (values) {
  30079. this._keys = values.slice(0);
  30080. this._offsetsCache = {};
  30081. this._highLimitsCache = {};
  30082. };
  30083. Animation.prototype._getKeyValue = function (value) {
  30084. if (typeof value === "function") {
  30085. return value();
  30086. }
  30087. return value;
  30088. };
  30089. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30090. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30091. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30092. }
  30093. this.currentFrame = currentFrame;
  30094. // Try to get a hash to find the right key
  30095. 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));
  30096. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30097. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30098. startKeyIndex--;
  30099. }
  30100. }
  30101. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30102. var endKey = this._keys[key + 1];
  30103. if (endKey.frame >= currentFrame) {
  30104. var startKey = this._keys[key];
  30105. var startValue = this._getKeyValue(startKey.value);
  30106. var endValue = this._getKeyValue(endKey.value);
  30107. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30108. var frameDelta = endKey.frame - startKey.frame;
  30109. // gradient : percent of currentFrame between the frame inf and the frame sup
  30110. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30111. // check for easingFunction and correction of gradient
  30112. if (this._easingFunction != null) {
  30113. gradient = this._easingFunction.ease(gradient);
  30114. }
  30115. switch (this.dataType) {
  30116. // Float
  30117. case Animation.ANIMATIONTYPE_FLOAT:
  30118. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30119. switch (loopMode) {
  30120. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30121. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30122. return floatValue;
  30123. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30124. return offsetValue * repeatCount + floatValue;
  30125. }
  30126. break;
  30127. // Quaternion
  30128. case Animation.ANIMATIONTYPE_QUATERNION:
  30129. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30130. switch (loopMode) {
  30131. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30132. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30133. return quatValue;
  30134. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30135. return quatValue.add(offsetValue.scale(repeatCount));
  30136. }
  30137. return quatValue;
  30138. // Vector3
  30139. case Animation.ANIMATIONTYPE_VECTOR3:
  30140. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30141. switch (loopMode) {
  30142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30144. return vec3Value;
  30145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30146. return vec3Value.add(offsetValue.scale(repeatCount));
  30147. }
  30148. // Vector2
  30149. case Animation.ANIMATIONTYPE_VECTOR2:
  30150. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30151. switch (loopMode) {
  30152. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30153. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30154. return vec2Value;
  30155. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30156. return vec2Value.add(offsetValue.scale(repeatCount));
  30157. }
  30158. // Size
  30159. case Animation.ANIMATIONTYPE_SIZE:
  30160. switch (loopMode) {
  30161. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30162. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30163. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30164. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30165. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30166. }
  30167. // Color3
  30168. case Animation.ANIMATIONTYPE_COLOR3:
  30169. switch (loopMode) {
  30170. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30171. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30172. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30173. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30174. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30175. }
  30176. // Matrix
  30177. case Animation.ANIMATIONTYPE_MATRIX:
  30178. switch (loopMode) {
  30179. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30180. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30181. if (this.allowMatricesInterpolation) {
  30182. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30183. }
  30184. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30185. return startValue;
  30186. }
  30187. default:
  30188. break;
  30189. }
  30190. break;
  30191. }
  30192. }
  30193. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30194. };
  30195. Animation.prototype.setValue = function (currentValue, blend) {
  30196. if (blend === void 0) { blend = false; }
  30197. // Set value
  30198. var path;
  30199. var destination;
  30200. if (this.targetPropertyPath.length > 1) {
  30201. var property = this._target[this.targetPropertyPath[0]];
  30202. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30203. property = property[this.targetPropertyPath[index]];
  30204. }
  30205. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30206. destination = property;
  30207. }
  30208. else {
  30209. path = this.targetPropertyPath[0];
  30210. destination = this._target;
  30211. }
  30212. // Blending
  30213. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30214. if (!this._originalBlendValue) {
  30215. if (destination[path].clone) {
  30216. this._originalBlendValue = destination[path].clone();
  30217. }
  30218. else {
  30219. this._originalBlendValue = destination[path];
  30220. }
  30221. }
  30222. if (this._originalBlendValue.prototype) {
  30223. if (this._originalBlendValue.prototype.Lerp) {
  30224. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30225. }
  30226. else {
  30227. destination[path] = currentValue;
  30228. }
  30229. }
  30230. else if (this._originalBlendValue.m) {
  30231. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30232. }
  30233. else {
  30234. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30235. }
  30236. this._blendingFactor += this.blendingSpeed;
  30237. }
  30238. else {
  30239. destination[path] = currentValue;
  30240. }
  30241. if (this._target.markAsDirty) {
  30242. this._target.markAsDirty(this.targetProperty);
  30243. }
  30244. };
  30245. Animation.prototype.goToFrame = function (frame) {
  30246. if (frame < this._keys[0].frame) {
  30247. frame = this._keys[0].frame;
  30248. }
  30249. else if (frame > this._keys[this._keys.length - 1].frame) {
  30250. frame = this._keys[this._keys.length - 1].frame;
  30251. }
  30252. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30253. this.setValue(currentValue);
  30254. };
  30255. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30256. if (blend === void 0) { blend = false; }
  30257. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30258. this._stopped = true;
  30259. return false;
  30260. }
  30261. var returnValue = true;
  30262. // Adding a start key at frame 0 if missing
  30263. if (this._keys[0].frame !== 0) {
  30264. var newKey = { frame: 0, value: this._keys[0].value };
  30265. this._keys.splice(0, 0, newKey);
  30266. }
  30267. // Check limits
  30268. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30269. from = this._keys[0].frame;
  30270. }
  30271. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30272. to = this._keys[this._keys.length - 1].frame;
  30273. }
  30274. //to and from cannot be the same key
  30275. if (from === to) {
  30276. from++;
  30277. }
  30278. // Compute ratio
  30279. var range = to - from;
  30280. var offsetValue;
  30281. // ratio represents the frame delta between from and to
  30282. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30283. var highLimitValue = 0;
  30284. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  30285. returnValue = false;
  30286. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30287. }
  30288. else {
  30289. // Get max value if required
  30290. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30291. var keyOffset = to.toString() + from.toString();
  30292. if (!this._offsetsCache[keyOffset]) {
  30293. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30294. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30295. switch (this.dataType) {
  30296. // Float
  30297. case Animation.ANIMATIONTYPE_FLOAT:
  30298. this._offsetsCache[keyOffset] = toValue - fromValue;
  30299. break;
  30300. // Quaternion
  30301. case Animation.ANIMATIONTYPE_QUATERNION:
  30302. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30303. break;
  30304. // Vector3
  30305. case Animation.ANIMATIONTYPE_VECTOR3:
  30306. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30307. // Vector2
  30308. case Animation.ANIMATIONTYPE_VECTOR2:
  30309. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30310. // Size
  30311. case Animation.ANIMATIONTYPE_SIZE:
  30312. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30313. // Color3
  30314. case Animation.ANIMATIONTYPE_COLOR3:
  30315. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30316. default:
  30317. break;
  30318. }
  30319. this._highLimitsCache[keyOffset] = toValue;
  30320. }
  30321. highLimitValue = this._highLimitsCache[keyOffset];
  30322. offsetValue = this._offsetsCache[keyOffset];
  30323. }
  30324. }
  30325. if (offsetValue === undefined) {
  30326. switch (this.dataType) {
  30327. // Float
  30328. case Animation.ANIMATIONTYPE_FLOAT:
  30329. offsetValue = 0;
  30330. break;
  30331. // Quaternion
  30332. case Animation.ANIMATIONTYPE_QUATERNION:
  30333. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30334. break;
  30335. // Vector3
  30336. case Animation.ANIMATIONTYPE_VECTOR3:
  30337. offsetValue = BABYLON.Vector3.Zero();
  30338. break;
  30339. // Vector2
  30340. case Animation.ANIMATIONTYPE_VECTOR2:
  30341. offsetValue = BABYLON.Vector2.Zero();
  30342. break;
  30343. // Size
  30344. case Animation.ANIMATIONTYPE_SIZE:
  30345. offsetValue = BABYLON.Size.Zero();
  30346. break;
  30347. // Color3
  30348. case Animation.ANIMATIONTYPE_COLOR3:
  30349. offsetValue = BABYLON.Color3.Black();
  30350. }
  30351. }
  30352. // Compute value
  30353. var repeatCount = (ratio / range) >> 0;
  30354. var currentFrame = returnValue ? from + ratio % range : to;
  30355. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30356. // Set value
  30357. this.setValue(currentValue);
  30358. // Check events
  30359. for (var index = 0; index < this._events.length; index++) {
  30360. if (currentFrame >= this._events[index].frame) {
  30361. var event = this._events[index];
  30362. if (!event.isDone) {
  30363. // If event should be done only once, remove it.
  30364. if (event.onlyOnce) {
  30365. this._events.splice(index, 1);
  30366. index--;
  30367. }
  30368. event.isDone = true;
  30369. event.action();
  30370. } // Don't do anything if the event has already be done.
  30371. }
  30372. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30373. // reset event, the animation is looping
  30374. this._events[index].isDone = false;
  30375. }
  30376. }
  30377. if (!returnValue) {
  30378. this._stopped = true;
  30379. }
  30380. return returnValue;
  30381. };
  30382. Animation.prototype.serialize = function () {
  30383. var serializationObject = {};
  30384. serializationObject.name = this.name;
  30385. serializationObject.property = this.targetProperty;
  30386. serializationObject.framePerSecond = this.framePerSecond;
  30387. serializationObject.dataType = this.dataType;
  30388. serializationObject.loopBehavior = this.loopMode;
  30389. serializationObject.enableBlending = this.enableBlending;
  30390. serializationObject.blendingSpeed = this.blendingSpeed;
  30391. var dataType = this.dataType;
  30392. serializationObject.keys = [];
  30393. var keys = this.getKeys();
  30394. for (var index = 0; index < keys.length; index++) {
  30395. var animationKey = keys[index];
  30396. var key = {};
  30397. key.frame = animationKey.frame;
  30398. switch (dataType) {
  30399. case Animation.ANIMATIONTYPE_FLOAT:
  30400. key.values = [animationKey.value];
  30401. break;
  30402. case Animation.ANIMATIONTYPE_QUATERNION:
  30403. case Animation.ANIMATIONTYPE_MATRIX:
  30404. case Animation.ANIMATIONTYPE_VECTOR3:
  30405. case Animation.ANIMATIONTYPE_COLOR3:
  30406. key.values = animationKey.value.asArray();
  30407. break;
  30408. }
  30409. serializationObject.keys.push(key);
  30410. }
  30411. serializationObject.ranges = [];
  30412. for (var name in this._ranges) {
  30413. var range = {};
  30414. range.name = name;
  30415. range.from = this._ranges[name].from;
  30416. range.to = this._ranges[name].to;
  30417. serializationObject.ranges.push(range);
  30418. }
  30419. return serializationObject;
  30420. };
  30421. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30422. get: function () {
  30423. return Animation._ANIMATIONTYPE_FLOAT;
  30424. },
  30425. enumerable: true,
  30426. configurable: true
  30427. });
  30428. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30429. get: function () {
  30430. return Animation._ANIMATIONTYPE_VECTOR3;
  30431. },
  30432. enumerable: true,
  30433. configurable: true
  30434. });
  30435. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30436. get: function () {
  30437. return Animation._ANIMATIONTYPE_VECTOR2;
  30438. },
  30439. enumerable: true,
  30440. configurable: true
  30441. });
  30442. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30443. get: function () {
  30444. return Animation._ANIMATIONTYPE_SIZE;
  30445. },
  30446. enumerable: true,
  30447. configurable: true
  30448. });
  30449. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30450. get: function () {
  30451. return Animation._ANIMATIONTYPE_QUATERNION;
  30452. },
  30453. enumerable: true,
  30454. configurable: true
  30455. });
  30456. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30457. get: function () {
  30458. return Animation._ANIMATIONTYPE_MATRIX;
  30459. },
  30460. enumerable: true,
  30461. configurable: true
  30462. });
  30463. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30464. get: function () {
  30465. return Animation._ANIMATIONTYPE_COLOR3;
  30466. },
  30467. enumerable: true,
  30468. configurable: true
  30469. });
  30470. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30471. get: function () {
  30472. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30478. get: function () {
  30479. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30480. },
  30481. enumerable: true,
  30482. configurable: true
  30483. });
  30484. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30485. get: function () {
  30486. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30487. },
  30488. enumerable: true,
  30489. configurable: true
  30490. });
  30491. Animation.Parse = function (parsedAnimation) {
  30492. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30493. var dataType = parsedAnimation.dataType;
  30494. var keys = [];
  30495. var data;
  30496. var index;
  30497. if (parsedAnimation.enableBlending) {
  30498. animation.enableBlending = parsedAnimation.enableBlending;
  30499. }
  30500. if (parsedAnimation.blendingSpeed) {
  30501. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30502. }
  30503. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30504. var key = parsedAnimation.keys[index];
  30505. switch (dataType) {
  30506. case Animation.ANIMATIONTYPE_FLOAT:
  30507. data = key.values[0];
  30508. break;
  30509. case Animation.ANIMATIONTYPE_QUATERNION:
  30510. data = BABYLON.Quaternion.FromArray(key.values);
  30511. break;
  30512. case Animation.ANIMATIONTYPE_MATRIX:
  30513. data = BABYLON.Matrix.FromArray(key.values);
  30514. break;
  30515. case Animation.ANIMATIONTYPE_COLOR3:
  30516. data = BABYLON.Color3.FromArray(key.values);
  30517. break;
  30518. case Animation.ANIMATIONTYPE_VECTOR3:
  30519. default:
  30520. data = BABYLON.Vector3.FromArray(key.values);
  30521. break;
  30522. }
  30523. keys.push({
  30524. frame: key.frame,
  30525. value: data
  30526. });
  30527. }
  30528. animation.setKeys(keys);
  30529. if (parsedAnimation.ranges) {
  30530. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30531. data = parsedAnimation.ranges[index];
  30532. animation.createRange(data.name, data.from, data.to);
  30533. }
  30534. }
  30535. return animation;
  30536. };
  30537. Animation.AppendSerializedAnimations = function (source, destination) {
  30538. if (source.animations) {
  30539. destination.animations = [];
  30540. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30541. var animation = source.animations[animationIndex];
  30542. destination.animations.push(animation.serialize());
  30543. }
  30544. }
  30545. };
  30546. return Animation;
  30547. }());
  30548. // Statics
  30549. Animation._ANIMATIONTYPE_FLOAT = 0;
  30550. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30551. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30552. Animation._ANIMATIONTYPE_MATRIX = 3;
  30553. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30554. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30555. Animation._ANIMATIONTYPE_SIZE = 6;
  30556. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30557. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30558. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30559. BABYLON.Animation = Animation;
  30560. })(BABYLON || (BABYLON = {}));
  30561. //# sourceMappingURL=babylon.animation.js.map
  30562. var BABYLON;
  30563. (function (BABYLON) {
  30564. var Animatable = (function () {
  30565. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30566. if (fromFrame === void 0) { fromFrame = 0; }
  30567. if (toFrame === void 0) { toFrame = 100; }
  30568. if (loopAnimation === void 0) { loopAnimation = false; }
  30569. if (speedRatio === void 0) { speedRatio = 1.0; }
  30570. this.target = target;
  30571. this.fromFrame = fromFrame;
  30572. this.toFrame = toFrame;
  30573. this.loopAnimation = loopAnimation;
  30574. this.speedRatio = speedRatio;
  30575. this.onAnimationEnd = onAnimationEnd;
  30576. this._localDelayOffset = null;
  30577. this._pausedDelay = null;
  30578. this._animations = new Array();
  30579. this._paused = false;
  30580. this.animationStarted = false;
  30581. if (animations) {
  30582. this.appendAnimations(target, animations);
  30583. }
  30584. this._scene = scene;
  30585. scene._activeAnimatables.push(this);
  30586. }
  30587. // Methods
  30588. Animatable.prototype.getAnimations = function () {
  30589. return this._animations;
  30590. };
  30591. Animatable.prototype.appendAnimations = function (target, animations) {
  30592. for (var index = 0; index < animations.length; index++) {
  30593. var animation = animations[index];
  30594. animation._target = target;
  30595. this._animations.push(animation);
  30596. }
  30597. };
  30598. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30599. var animations = this._animations;
  30600. for (var index = 0; index < animations.length; index++) {
  30601. if (animations[index].targetProperty === property) {
  30602. return animations[index];
  30603. }
  30604. }
  30605. return null;
  30606. };
  30607. Animatable.prototype.reset = function () {
  30608. var animations = this._animations;
  30609. for (var index = 0; index < animations.length; index++) {
  30610. animations[index].reset();
  30611. }
  30612. this._localDelayOffset = null;
  30613. this._pausedDelay = null;
  30614. };
  30615. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30616. var animations = this._animations;
  30617. for (var index = 0; index < animations.length; index++) {
  30618. animations[index].enableBlending = true;
  30619. animations[index].blendingSpeed = blendingSpeed;
  30620. }
  30621. };
  30622. Animatable.prototype.disableBlending = function () {
  30623. var animations = this._animations;
  30624. for (var index = 0; index < animations.length; index++) {
  30625. animations[index].enableBlending = false;
  30626. }
  30627. };
  30628. Animatable.prototype.goToFrame = function (frame) {
  30629. var animations = this._animations;
  30630. if (animations[0]) {
  30631. var fps = animations[0].framePerSecond;
  30632. var currentFrame = animations[0].currentFrame;
  30633. var adjustTime = frame - currentFrame;
  30634. var delay = adjustTime * 1000 / fps;
  30635. this._localDelayOffset -= delay;
  30636. }
  30637. for (var index = 0; index < animations.length; index++) {
  30638. animations[index].goToFrame(frame);
  30639. }
  30640. };
  30641. Animatable.prototype.pause = function () {
  30642. if (this._paused) {
  30643. return;
  30644. }
  30645. this._paused = true;
  30646. };
  30647. Animatable.prototype.restart = function () {
  30648. this._paused = false;
  30649. };
  30650. Animatable.prototype.stop = function (animationName) {
  30651. if (animationName) {
  30652. var idx = this._scene._activeAnimatables.indexOf(this);
  30653. if (idx > -1) {
  30654. var animations = this._animations;
  30655. for (var index = animations.length - 1; index >= 0; index--) {
  30656. if (typeof animationName === "string" && animations[index].name != animationName) {
  30657. continue;
  30658. }
  30659. animations[index].reset();
  30660. animations.splice(index, 1);
  30661. }
  30662. if (animations.length == 0) {
  30663. this._scene._activeAnimatables.splice(idx, 1);
  30664. if (this.onAnimationEnd) {
  30665. this.onAnimationEnd();
  30666. }
  30667. }
  30668. }
  30669. }
  30670. else {
  30671. var index = this._scene._activeAnimatables.indexOf(this);
  30672. if (index > -1) {
  30673. this._scene._activeAnimatables.splice(index, 1);
  30674. var animations = this._animations;
  30675. for (var index = 0; index < animations.length; index++) {
  30676. animations[index].reset();
  30677. }
  30678. if (this.onAnimationEnd) {
  30679. this.onAnimationEnd();
  30680. }
  30681. }
  30682. }
  30683. };
  30684. Animatable.prototype._animate = function (delay) {
  30685. if (this._paused) {
  30686. this.animationStarted = false;
  30687. if (this._pausedDelay === null) {
  30688. this._pausedDelay = delay;
  30689. }
  30690. return true;
  30691. }
  30692. if (this._localDelayOffset === null) {
  30693. this._localDelayOffset = delay;
  30694. }
  30695. else if (this._pausedDelay !== null) {
  30696. this._localDelayOffset += delay - this._pausedDelay;
  30697. this._pausedDelay = null;
  30698. }
  30699. // Animating
  30700. var running = false;
  30701. var animations = this._animations;
  30702. var index;
  30703. for (index = 0; index < animations.length; index++) {
  30704. var animation = animations[index];
  30705. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30706. running = running || isRunning;
  30707. }
  30708. this.animationStarted = running;
  30709. if (!running) {
  30710. // Remove from active animatables
  30711. index = this._scene._activeAnimatables.indexOf(this);
  30712. this._scene._activeAnimatables.splice(index, 1);
  30713. }
  30714. if (!running && this.onAnimationEnd) {
  30715. this.onAnimationEnd();
  30716. this.onAnimationEnd = null;
  30717. }
  30718. return running;
  30719. };
  30720. return Animatable;
  30721. }());
  30722. BABYLON.Animatable = Animatable;
  30723. })(BABYLON || (BABYLON = {}));
  30724. //# sourceMappingURL=babylon.animatable.js.map
  30725. var BABYLON;
  30726. (function (BABYLON) {
  30727. var EasingFunction = (function () {
  30728. function EasingFunction() {
  30729. // Properties
  30730. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30731. }
  30732. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30733. get: function () {
  30734. return EasingFunction._EASINGMODE_EASEIN;
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30740. get: function () {
  30741. return EasingFunction._EASINGMODE_EASEOUT;
  30742. },
  30743. enumerable: true,
  30744. configurable: true
  30745. });
  30746. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30747. get: function () {
  30748. return EasingFunction._EASINGMODE_EASEINOUT;
  30749. },
  30750. enumerable: true,
  30751. configurable: true
  30752. });
  30753. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30754. var n = Math.min(Math.max(easingMode, 0), 2);
  30755. this._easingMode = n;
  30756. };
  30757. EasingFunction.prototype.getEasingMode = function () {
  30758. return this._easingMode;
  30759. };
  30760. EasingFunction.prototype.easeInCore = function (gradient) {
  30761. throw new Error('You must implement this method');
  30762. };
  30763. EasingFunction.prototype.ease = function (gradient) {
  30764. switch (this._easingMode) {
  30765. case EasingFunction.EASINGMODE_EASEIN:
  30766. return this.easeInCore(gradient);
  30767. case EasingFunction.EASINGMODE_EASEOUT:
  30768. return (1 - this.easeInCore(1 - gradient));
  30769. }
  30770. if (gradient >= 0.5) {
  30771. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30772. }
  30773. return (this.easeInCore(gradient * 2) * 0.5);
  30774. };
  30775. return EasingFunction;
  30776. }());
  30777. //Statics
  30778. EasingFunction._EASINGMODE_EASEIN = 0;
  30779. EasingFunction._EASINGMODE_EASEOUT = 1;
  30780. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30781. BABYLON.EasingFunction = EasingFunction;
  30782. var CircleEase = (function (_super) {
  30783. __extends(CircleEase, _super);
  30784. function CircleEase() {
  30785. return _super !== null && _super.apply(this, arguments) || this;
  30786. }
  30787. CircleEase.prototype.easeInCore = function (gradient) {
  30788. gradient = Math.max(0, Math.min(1, gradient));
  30789. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30790. };
  30791. return CircleEase;
  30792. }(EasingFunction));
  30793. BABYLON.CircleEase = CircleEase;
  30794. var BackEase = (function (_super) {
  30795. __extends(BackEase, _super);
  30796. function BackEase(amplitude) {
  30797. if (amplitude === void 0) { amplitude = 1; }
  30798. var _this = _super.call(this) || this;
  30799. _this.amplitude = amplitude;
  30800. return _this;
  30801. }
  30802. BackEase.prototype.easeInCore = function (gradient) {
  30803. var num = Math.max(0, this.amplitude);
  30804. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30805. };
  30806. return BackEase;
  30807. }(EasingFunction));
  30808. BABYLON.BackEase = BackEase;
  30809. var BounceEase = (function (_super) {
  30810. __extends(BounceEase, _super);
  30811. function BounceEase(bounces, bounciness) {
  30812. if (bounces === void 0) { bounces = 3; }
  30813. if (bounciness === void 0) { bounciness = 2; }
  30814. var _this = _super.call(this) || this;
  30815. _this.bounces = bounces;
  30816. _this.bounciness = bounciness;
  30817. return _this;
  30818. }
  30819. BounceEase.prototype.easeInCore = function (gradient) {
  30820. var y = Math.max(0.0, this.bounces);
  30821. var bounciness = this.bounciness;
  30822. if (bounciness <= 1.0) {
  30823. bounciness = 1.001;
  30824. }
  30825. var num9 = Math.pow(bounciness, y);
  30826. var num5 = 1.0 - bounciness;
  30827. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30828. var num15 = gradient * num4;
  30829. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30830. var num3 = Math.floor(num65);
  30831. var num13 = num3 + 1.0;
  30832. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30833. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30834. var num7 = (num8 + num12) * 0.5;
  30835. var num6 = gradient - num7;
  30836. var num2 = num7 - num8;
  30837. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30838. };
  30839. return BounceEase;
  30840. }(EasingFunction));
  30841. BABYLON.BounceEase = BounceEase;
  30842. var CubicEase = (function (_super) {
  30843. __extends(CubicEase, _super);
  30844. function CubicEase() {
  30845. return _super !== null && _super.apply(this, arguments) || this;
  30846. }
  30847. CubicEase.prototype.easeInCore = function (gradient) {
  30848. return (gradient * gradient * gradient);
  30849. };
  30850. return CubicEase;
  30851. }(EasingFunction));
  30852. BABYLON.CubicEase = CubicEase;
  30853. var ElasticEase = (function (_super) {
  30854. __extends(ElasticEase, _super);
  30855. function ElasticEase(oscillations, springiness) {
  30856. if (oscillations === void 0) { oscillations = 3; }
  30857. if (springiness === void 0) { springiness = 3; }
  30858. var _this = _super.call(this) || this;
  30859. _this.oscillations = oscillations;
  30860. _this.springiness = springiness;
  30861. return _this;
  30862. }
  30863. ElasticEase.prototype.easeInCore = function (gradient) {
  30864. var num2;
  30865. var num3 = Math.max(0.0, this.oscillations);
  30866. var num = Math.max(0.0, this.springiness);
  30867. if (num == 0) {
  30868. num2 = gradient;
  30869. }
  30870. else {
  30871. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30872. }
  30873. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30874. };
  30875. return ElasticEase;
  30876. }(EasingFunction));
  30877. BABYLON.ElasticEase = ElasticEase;
  30878. var ExponentialEase = (function (_super) {
  30879. __extends(ExponentialEase, _super);
  30880. function ExponentialEase(exponent) {
  30881. if (exponent === void 0) { exponent = 2; }
  30882. var _this = _super.call(this) || this;
  30883. _this.exponent = exponent;
  30884. return _this;
  30885. }
  30886. ExponentialEase.prototype.easeInCore = function (gradient) {
  30887. if (this.exponent <= 0) {
  30888. return gradient;
  30889. }
  30890. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30891. };
  30892. return ExponentialEase;
  30893. }(EasingFunction));
  30894. BABYLON.ExponentialEase = ExponentialEase;
  30895. var PowerEase = (function (_super) {
  30896. __extends(PowerEase, _super);
  30897. function PowerEase(power) {
  30898. if (power === void 0) { power = 2; }
  30899. var _this = _super.call(this) || this;
  30900. _this.power = power;
  30901. return _this;
  30902. }
  30903. PowerEase.prototype.easeInCore = function (gradient) {
  30904. var y = Math.max(0.0, this.power);
  30905. return Math.pow(gradient, y);
  30906. };
  30907. return PowerEase;
  30908. }(EasingFunction));
  30909. BABYLON.PowerEase = PowerEase;
  30910. var QuadraticEase = (function (_super) {
  30911. __extends(QuadraticEase, _super);
  30912. function QuadraticEase() {
  30913. return _super !== null && _super.apply(this, arguments) || this;
  30914. }
  30915. QuadraticEase.prototype.easeInCore = function (gradient) {
  30916. return (gradient * gradient);
  30917. };
  30918. return QuadraticEase;
  30919. }(EasingFunction));
  30920. BABYLON.QuadraticEase = QuadraticEase;
  30921. var QuarticEase = (function (_super) {
  30922. __extends(QuarticEase, _super);
  30923. function QuarticEase() {
  30924. return _super !== null && _super.apply(this, arguments) || this;
  30925. }
  30926. QuarticEase.prototype.easeInCore = function (gradient) {
  30927. return (gradient * gradient * gradient * gradient);
  30928. };
  30929. return QuarticEase;
  30930. }(EasingFunction));
  30931. BABYLON.QuarticEase = QuarticEase;
  30932. var QuinticEase = (function (_super) {
  30933. __extends(QuinticEase, _super);
  30934. function QuinticEase() {
  30935. return _super !== null && _super.apply(this, arguments) || this;
  30936. }
  30937. QuinticEase.prototype.easeInCore = function (gradient) {
  30938. return (gradient * gradient * gradient * gradient * gradient);
  30939. };
  30940. return QuinticEase;
  30941. }(EasingFunction));
  30942. BABYLON.QuinticEase = QuinticEase;
  30943. var SineEase = (function (_super) {
  30944. __extends(SineEase, _super);
  30945. function SineEase() {
  30946. return _super !== null && _super.apply(this, arguments) || this;
  30947. }
  30948. SineEase.prototype.easeInCore = function (gradient) {
  30949. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30950. };
  30951. return SineEase;
  30952. }(EasingFunction));
  30953. BABYLON.SineEase = SineEase;
  30954. var BezierCurveEase = (function (_super) {
  30955. __extends(BezierCurveEase, _super);
  30956. function BezierCurveEase(x1, y1, x2, y2) {
  30957. if (x1 === void 0) { x1 = 0; }
  30958. if (y1 === void 0) { y1 = 0; }
  30959. if (x2 === void 0) { x2 = 1; }
  30960. if (y2 === void 0) { y2 = 1; }
  30961. var _this = _super.call(this) || this;
  30962. _this.x1 = x1;
  30963. _this.y1 = y1;
  30964. _this.x2 = x2;
  30965. _this.y2 = y2;
  30966. return _this;
  30967. }
  30968. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30969. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30970. };
  30971. return BezierCurveEase;
  30972. }(EasingFunction));
  30973. BABYLON.BezierCurveEase = BezierCurveEase;
  30974. })(BABYLON || (BABYLON = {}));
  30975. //# sourceMappingURL=babylon.easing.js.map
  30976. var BABYLON;
  30977. (function (BABYLON) {
  30978. BABYLON.CameraInputTypes = {};
  30979. var CameraInputsManager = (function () {
  30980. function CameraInputsManager(camera) {
  30981. this.attached = {};
  30982. this.camera = camera;
  30983. this.checkInputs = function () { };
  30984. }
  30985. CameraInputsManager.prototype.add = function (input) {
  30986. var type = input.getSimpleName();
  30987. if (this.attached[type]) {
  30988. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  30989. return;
  30990. }
  30991. this.attached[type] = input;
  30992. input.camera = this.camera;
  30993. //for checkInputs, we are dynamically creating a function
  30994. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  30995. if (input.checkInputs) {
  30996. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30997. }
  30998. if (this.attachedElement) {
  30999. input.attachControl(this.attachedElement);
  31000. }
  31001. };
  31002. CameraInputsManager.prototype.remove = function (inputToRemove) {
  31003. for (var cam in this.attached) {
  31004. var input = this.attached[cam];
  31005. if (input === inputToRemove) {
  31006. input.detachControl(this.attachedElement);
  31007. delete this.attached[cam];
  31008. this.rebuildInputCheck();
  31009. }
  31010. }
  31011. };
  31012. CameraInputsManager.prototype.removeByType = function (inputType) {
  31013. for (var cam in this.attached) {
  31014. var input = this.attached[cam];
  31015. if (input.getTypeName() === inputType) {
  31016. input.detachControl(this.attachedElement);
  31017. delete this.attached[cam];
  31018. this.rebuildInputCheck();
  31019. }
  31020. }
  31021. };
  31022. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  31023. var current = this.checkInputs;
  31024. return function () {
  31025. current();
  31026. fn();
  31027. };
  31028. };
  31029. CameraInputsManager.prototype.attachInput = function (input) {
  31030. input.attachControl(this.attachedElement, this.noPreventDefault);
  31031. };
  31032. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31033. if (this.attachedElement) {
  31034. return;
  31035. }
  31036. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31037. this.attachedElement = element;
  31038. this.noPreventDefault = noPreventDefault;
  31039. for (var cam in this.attached) {
  31040. var input = this.attached[cam];
  31041. this.attached[cam].attachControl(element, noPreventDefault);
  31042. }
  31043. };
  31044. CameraInputsManager.prototype.detachElement = function (element) {
  31045. if (this.attachedElement !== element) {
  31046. return;
  31047. }
  31048. for (var cam in this.attached) {
  31049. var input = this.attached[cam];
  31050. this.attached[cam].detachControl(element);
  31051. }
  31052. this.attachedElement = null;
  31053. };
  31054. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31055. this.checkInputs = function () { };
  31056. for (var cam in this.attached) {
  31057. var input = this.attached[cam];
  31058. if (input.checkInputs) {
  31059. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31060. }
  31061. }
  31062. };
  31063. CameraInputsManager.prototype.clear = function () {
  31064. if (this.attachedElement) {
  31065. this.detachElement(this.attachedElement);
  31066. }
  31067. this.attached = {};
  31068. this.attachedElement = null;
  31069. this.checkInputs = function () { };
  31070. };
  31071. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31072. var inputs = {};
  31073. for (var cam in this.attached) {
  31074. var input = this.attached[cam];
  31075. var res = BABYLON.SerializationHelper.Serialize(input);
  31076. inputs[input.getTypeName()] = res;
  31077. }
  31078. serializedCamera.inputsmgr = inputs;
  31079. };
  31080. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31081. var parsedInputs = parsedCamera.inputsmgr;
  31082. if (parsedInputs) {
  31083. this.clear();
  31084. for (var n in parsedInputs) {
  31085. var construct = BABYLON.CameraInputTypes[n];
  31086. if (construct) {
  31087. var parsedinput = parsedInputs[n];
  31088. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31089. this.add(input);
  31090. }
  31091. }
  31092. }
  31093. else {
  31094. //2016-03-08 this part is for managing backward compatibility
  31095. for (var n in this.attached) {
  31096. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31097. if (construct) {
  31098. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31099. this.remove(this.attached[n]);
  31100. this.add(input);
  31101. }
  31102. }
  31103. }
  31104. };
  31105. return CameraInputsManager;
  31106. }());
  31107. BABYLON.CameraInputsManager = CameraInputsManager;
  31108. })(BABYLON || (BABYLON = {}));
  31109. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31110. /// <reference path="babylon.camera.ts" />
  31111. var BABYLON;
  31112. (function (BABYLON) {
  31113. var TargetCamera = (function (_super) {
  31114. __extends(TargetCamera, _super);
  31115. function TargetCamera(name, position, scene) {
  31116. var _this = _super.call(this, name, position, scene) || this;
  31117. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31118. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31119. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31120. _this.speed = 2.0;
  31121. _this.noRotationConstraint = false;
  31122. _this.lockedTarget = null;
  31123. _this._currentTarget = BABYLON.Vector3.Zero();
  31124. _this._viewMatrix = BABYLON.Matrix.Zero();
  31125. _this._camMatrix = BABYLON.Matrix.Zero();
  31126. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31127. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31128. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31129. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31130. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31131. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31132. _this._tempMatrix = BABYLON.Matrix.Zero();
  31133. return _this;
  31134. }
  31135. TargetCamera.prototype.getFrontPosition = function (distance) {
  31136. var direction = this.getTarget().subtract(this.position);
  31137. direction.normalize();
  31138. direction.scaleInPlace(distance);
  31139. return this.globalPosition.add(direction);
  31140. };
  31141. TargetCamera.prototype._getLockedTargetPosition = function () {
  31142. if (!this.lockedTarget) {
  31143. return null;
  31144. }
  31145. if (this.lockedTarget.absolutePosition) {
  31146. this.lockedTarget.computeWorldMatrix();
  31147. }
  31148. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31149. };
  31150. // Cache
  31151. TargetCamera.prototype._initCache = function () {
  31152. _super.prototype._initCache.call(this);
  31153. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31154. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31155. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31156. };
  31157. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31158. if (!ignoreParentClass) {
  31159. _super.prototype._updateCache.call(this);
  31160. }
  31161. var lockedTargetPosition = this._getLockedTargetPosition();
  31162. if (!lockedTargetPosition) {
  31163. this._cache.lockedTarget = null;
  31164. }
  31165. else {
  31166. if (!this._cache.lockedTarget) {
  31167. this._cache.lockedTarget = lockedTargetPosition.clone();
  31168. }
  31169. else {
  31170. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31171. }
  31172. }
  31173. this._cache.rotation.copyFrom(this.rotation);
  31174. if (this.rotationQuaternion)
  31175. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31176. };
  31177. // Synchronized
  31178. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31179. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31180. return false;
  31181. }
  31182. var lockedTargetPosition = this._getLockedTargetPosition();
  31183. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31184. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31185. };
  31186. // Methods
  31187. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31188. var engine = this.getEngine();
  31189. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31190. };
  31191. // Target
  31192. TargetCamera.prototype.setTarget = function (target) {
  31193. this.upVector.normalize();
  31194. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31195. this._camMatrix.invert();
  31196. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31197. var vDir = target.subtract(this.position);
  31198. if (vDir.x >= 0.0) {
  31199. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31200. }
  31201. else {
  31202. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31203. }
  31204. this.rotation.z = 0;
  31205. if (isNaN(this.rotation.x)) {
  31206. this.rotation.x = 0;
  31207. }
  31208. if (isNaN(this.rotation.y)) {
  31209. this.rotation.y = 0;
  31210. }
  31211. if (isNaN(this.rotation.z)) {
  31212. this.rotation.z = 0;
  31213. }
  31214. if (this.rotationQuaternion) {
  31215. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31216. }
  31217. };
  31218. /**
  31219. * Return the current target position of the camera. This value is expressed in local space.
  31220. */
  31221. TargetCamera.prototype.getTarget = function () {
  31222. return this._currentTarget;
  31223. };
  31224. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31225. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31226. };
  31227. TargetCamera.prototype._updatePosition = function () {
  31228. if (this.parent) {
  31229. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31230. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31231. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31232. return;
  31233. }
  31234. this.position.addInPlace(this.cameraDirection);
  31235. };
  31236. TargetCamera.prototype._checkInputs = function () {
  31237. var needToMove = this._decideIfNeedsToMove();
  31238. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31239. // Move
  31240. if (needToMove) {
  31241. this._updatePosition();
  31242. }
  31243. // Rotate
  31244. if (needToRotate) {
  31245. this.rotation.x += this.cameraRotation.x;
  31246. this.rotation.y += this.cameraRotation.y;
  31247. //rotate, if quaternion is set and rotation was used
  31248. if (this.rotationQuaternion) {
  31249. var len = this.rotation.lengthSquared();
  31250. if (len) {
  31251. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31252. }
  31253. }
  31254. if (!this.noRotationConstraint) {
  31255. var limit = (Math.PI / 2) * 0.95;
  31256. if (this.rotation.x > limit)
  31257. this.rotation.x = limit;
  31258. if (this.rotation.x < -limit)
  31259. this.rotation.x = -limit;
  31260. }
  31261. }
  31262. // Inertia
  31263. if (needToMove) {
  31264. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31265. this.cameraDirection.x = 0;
  31266. }
  31267. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31268. this.cameraDirection.y = 0;
  31269. }
  31270. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31271. this.cameraDirection.z = 0;
  31272. }
  31273. this.cameraDirection.scaleInPlace(this.inertia);
  31274. }
  31275. if (needToRotate) {
  31276. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31277. this.cameraRotation.x = 0;
  31278. }
  31279. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31280. this.cameraRotation.y = 0;
  31281. }
  31282. this.cameraRotation.scaleInPlace(this.inertia);
  31283. }
  31284. _super.prototype._checkInputs.call(this);
  31285. };
  31286. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31287. if (this.rotationQuaternion) {
  31288. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31289. //update the up vector!
  31290. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31291. }
  31292. else {
  31293. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31294. }
  31295. };
  31296. TargetCamera.prototype._getViewMatrix = function () {
  31297. if (!this.lockedTarget) {
  31298. // Compute
  31299. this._updateCameraRotationMatrix();
  31300. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31301. // Computing target and final matrix
  31302. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31303. }
  31304. else {
  31305. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31306. }
  31307. if (this.getScene().useRightHandedSystem) {
  31308. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31309. }
  31310. else {
  31311. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31312. }
  31313. return this._viewMatrix;
  31314. };
  31315. /**
  31316. * @override
  31317. * Override Camera.createRigCamera
  31318. */
  31319. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31320. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31321. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31322. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31323. if (!this.rotationQuaternion) {
  31324. this.rotationQuaternion = new BABYLON.Quaternion();
  31325. }
  31326. rigCamera._cameraRigParams = {};
  31327. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31328. }
  31329. return rigCamera;
  31330. }
  31331. return null;
  31332. };
  31333. /**
  31334. * @override
  31335. * Override Camera._updateRigCameras
  31336. */
  31337. TargetCamera.prototype._updateRigCameras = function () {
  31338. var camLeft = this._rigCameras[0];
  31339. var camRight = this._rigCameras[1];
  31340. switch (this.cameraRigMode) {
  31341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31342. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31344. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31345. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31346. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31347. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31348. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31349. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31350. camLeft.setTarget(this.getTarget());
  31351. camRight.setTarget(this.getTarget());
  31352. break;
  31353. case BABYLON.Camera.RIG_MODE_VR:
  31354. if (camLeft.rotationQuaternion) {
  31355. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31356. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31357. }
  31358. else {
  31359. camLeft.rotation.copyFrom(this.rotation);
  31360. camRight.rotation.copyFrom(this.rotation);
  31361. }
  31362. camLeft.position.copyFrom(this.position);
  31363. camRight.position.copyFrom(this.position);
  31364. break;
  31365. }
  31366. _super.prototype._updateRigCameras.call(this);
  31367. };
  31368. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31369. if (!this._rigCamTransformMatrix) {
  31370. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31371. }
  31372. var target = this.getTarget();
  31373. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31374. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31375. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31376. };
  31377. TargetCamera.prototype.getClassName = function () {
  31378. return "TargetCamera";
  31379. };
  31380. return TargetCamera;
  31381. }(BABYLON.Camera));
  31382. __decorate([
  31383. BABYLON.serializeAsVector3()
  31384. ], TargetCamera.prototype, "rotation", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], TargetCamera.prototype, "speed", void 0);
  31388. __decorate([
  31389. BABYLON.serializeAsMeshReference("lockedTargetId")
  31390. ], TargetCamera.prototype, "lockedTarget", void 0);
  31391. BABYLON.TargetCamera = TargetCamera;
  31392. })(BABYLON || (BABYLON = {}));
  31393. //# sourceMappingURL=babylon.targetCamera.js.map
  31394. var BABYLON;
  31395. (function (BABYLON) {
  31396. var ArcRotateCameraKeyboardMoveInput = (function () {
  31397. function ArcRotateCameraKeyboardMoveInput() {
  31398. this._keys = [];
  31399. this.keysUp = [38];
  31400. this.keysDown = [40];
  31401. this.keysLeft = [37];
  31402. this.keysRight = [39];
  31403. }
  31404. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31405. var _this = this;
  31406. element.tabIndex = 1;
  31407. this._onKeyDown = function (evt) {
  31408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31411. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31412. var index = _this._keys.indexOf(evt.keyCode);
  31413. if (index === -1) {
  31414. _this._keys.push(evt.keyCode);
  31415. }
  31416. if (evt.preventDefault) {
  31417. if (!noPreventDefault) {
  31418. evt.preventDefault();
  31419. }
  31420. }
  31421. }
  31422. };
  31423. this._onKeyUp = function (evt) {
  31424. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31425. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31426. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31427. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31428. var index = _this._keys.indexOf(evt.keyCode);
  31429. if (index >= 0) {
  31430. _this._keys.splice(index, 1);
  31431. }
  31432. if (evt.preventDefault) {
  31433. if (!noPreventDefault) {
  31434. evt.preventDefault();
  31435. }
  31436. }
  31437. }
  31438. };
  31439. this._onLostFocus = function () {
  31440. _this._keys = [];
  31441. };
  31442. element.addEventListener("keydown", this._onKeyDown, false);
  31443. element.addEventListener("keyup", this._onKeyUp, false);
  31444. BABYLON.Tools.RegisterTopRootEvents([
  31445. { name: "blur", handler: this._onLostFocus }
  31446. ]);
  31447. };
  31448. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31449. if (element) {
  31450. element.removeEventListener("keydown", this._onKeyDown);
  31451. element.removeEventListener("keyup", this._onKeyUp);
  31452. }
  31453. BABYLON.Tools.UnregisterTopRootEvents([
  31454. { name: "blur", handler: this._onLostFocus }
  31455. ]);
  31456. this._keys = [];
  31457. this._onKeyDown = null;
  31458. this._onKeyUp = null;
  31459. this._onLostFocus = null;
  31460. };
  31461. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31462. if (this._onKeyDown) {
  31463. var camera = this.camera;
  31464. for (var index = 0; index < this._keys.length; index++) {
  31465. var keyCode = this._keys[index];
  31466. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31467. camera.inertialAlphaOffset -= 0.01;
  31468. }
  31469. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31470. camera.inertialBetaOffset -= 0.01;
  31471. }
  31472. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31473. camera.inertialAlphaOffset += 0.01;
  31474. }
  31475. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31476. camera.inertialBetaOffset += 0.01;
  31477. }
  31478. }
  31479. }
  31480. };
  31481. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31482. return "ArcRotateCameraKeyboardMoveInput";
  31483. };
  31484. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31485. return "keyboard";
  31486. };
  31487. return ArcRotateCameraKeyboardMoveInput;
  31488. }());
  31489. __decorate([
  31490. BABYLON.serialize()
  31491. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31492. __decorate([
  31493. BABYLON.serialize()
  31494. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31495. __decorate([
  31496. BABYLON.serialize()
  31497. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31498. __decorate([
  31499. BABYLON.serialize()
  31500. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31501. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31502. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31503. })(BABYLON || (BABYLON = {}));
  31504. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31505. var BABYLON;
  31506. (function (BABYLON) {
  31507. var ArcRotateCameraMouseWheelInput = (function () {
  31508. function ArcRotateCameraMouseWheelInput() {
  31509. this.wheelPrecision = 3.0;
  31510. }
  31511. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31512. var _this = this;
  31513. this._wheel = function (p, s) {
  31514. //sanity check - this should be a PointerWheel event.
  31515. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31516. return;
  31517. var event = p.event;
  31518. var delta = 0;
  31519. if (event.wheelDelta) {
  31520. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31521. }
  31522. else if (event.detail) {
  31523. delta = -event.detail / _this.wheelPrecision;
  31524. }
  31525. if (delta)
  31526. _this.camera.inertialRadiusOffset += delta;
  31527. if (event.preventDefault) {
  31528. if (!noPreventDefault) {
  31529. event.preventDefault();
  31530. }
  31531. }
  31532. };
  31533. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31534. };
  31535. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31536. if (this._observer && element) {
  31537. this.camera.getScene().onPointerObservable.remove(this._observer);
  31538. this._observer = null;
  31539. this._wheel = null;
  31540. }
  31541. };
  31542. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  31543. return "ArcRotateCameraMouseWheelInput";
  31544. };
  31545. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31546. return "mousewheel";
  31547. };
  31548. return ArcRotateCameraMouseWheelInput;
  31549. }());
  31550. __decorate([
  31551. BABYLON.serialize()
  31552. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31553. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31554. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31555. })(BABYLON || (BABYLON = {}));
  31556. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31557. var BABYLON;
  31558. (function (BABYLON) {
  31559. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31560. var ArcRotateCameraPointersInput = (function () {
  31561. function ArcRotateCameraPointersInput() {
  31562. this.buttons = [0, 1, 2];
  31563. this.angularSensibilityX = 1000.0;
  31564. this.angularSensibilityY = 1000.0;
  31565. this.pinchPrecision = 6.0;
  31566. this.panningSensibility = 50.0;
  31567. this._isPanClick = false;
  31568. this.pinchInwards = true;
  31569. }
  31570. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31571. var _this = this;
  31572. var engine = this.camera.getEngine();
  31573. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31574. var pointA, pointB;
  31575. var previousPinchDistance = 0;
  31576. this._pointerInput = function (p, s) {
  31577. var evt = p.event;
  31578. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31579. return;
  31580. }
  31581. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31582. try {
  31583. evt.srcElement.setPointerCapture(evt.pointerId);
  31584. }
  31585. catch (e) {
  31586. //Nothing to do with the error. Execution will continue.
  31587. }
  31588. // Manage panning with pan button click
  31589. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31590. // manage pointers
  31591. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31592. if (pointA === undefined) {
  31593. pointA = cacheSoloPointer;
  31594. }
  31595. else if (pointB === undefined) {
  31596. pointB = cacheSoloPointer;
  31597. }
  31598. if (!noPreventDefault) {
  31599. evt.preventDefault();
  31600. element.focus();
  31601. }
  31602. }
  31603. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31604. try {
  31605. evt.srcElement.releasePointerCapture(evt.pointerId);
  31606. }
  31607. catch (e) {
  31608. //Nothing to do with the error.
  31609. }
  31610. cacheSoloPointer = null;
  31611. previousPinchDistance = 0;
  31612. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31613. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31614. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31615. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31616. pointA = pointB = undefined;
  31617. if (!noPreventDefault) {
  31618. evt.preventDefault();
  31619. }
  31620. }
  31621. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31622. if (!noPreventDefault) {
  31623. evt.preventDefault();
  31624. }
  31625. // One button down
  31626. if (pointA && pointB === undefined) {
  31627. if (_this.panningSensibility !== 0 &&
  31628. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31629. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31630. _this.camera
  31631. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31632. _this.camera
  31633. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31634. }
  31635. else {
  31636. var offsetX = evt.clientX - cacheSoloPointer.x;
  31637. var offsetY = evt.clientY - cacheSoloPointer.y;
  31638. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31639. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31640. }
  31641. cacheSoloPointer.x = evt.clientX;
  31642. cacheSoloPointer.y = evt.clientY;
  31643. }
  31644. else if (pointA && pointB) {
  31645. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31646. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31647. ed.x = evt.clientX;
  31648. ed.y = evt.clientY;
  31649. var direction = _this.pinchInwards ? 1 : -1;
  31650. var distX = pointA.x - pointB.x;
  31651. var distY = pointA.y - pointB.y;
  31652. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31653. if (previousPinchDistance === 0) {
  31654. previousPinchDistance = pinchSquaredDistance;
  31655. return;
  31656. }
  31657. if (pinchSquaredDistance !== previousPinchDistance) {
  31658. _this.camera
  31659. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31660. (_this.pinchPrecision *
  31661. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31662. direction);
  31663. previousPinchDistance = pinchSquaredDistance;
  31664. }
  31665. }
  31666. }
  31667. };
  31668. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31669. this._onContextMenu = function (evt) {
  31670. evt.preventDefault();
  31671. };
  31672. if (!this.camera._useCtrlForPanning) {
  31673. element.addEventListener("contextmenu", this._onContextMenu, false);
  31674. }
  31675. this._onLostFocus = function () {
  31676. //this._keys = [];
  31677. pointA = pointB = undefined;
  31678. previousPinchDistance = 0;
  31679. cacheSoloPointer = null;
  31680. };
  31681. this._onMouseMove = function (evt) {
  31682. if (!engine.isPointerLock) {
  31683. return;
  31684. }
  31685. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31686. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31687. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31688. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31689. if (!noPreventDefault) {
  31690. evt.preventDefault();
  31691. }
  31692. };
  31693. this._onGestureStart = function (e) {
  31694. if (window.MSGesture === undefined) {
  31695. return;
  31696. }
  31697. if (!_this._MSGestureHandler) {
  31698. _this._MSGestureHandler = new MSGesture();
  31699. _this._MSGestureHandler.target = element;
  31700. }
  31701. _this._MSGestureHandler.addPointer(e.pointerId);
  31702. };
  31703. this._onGesture = function (e) {
  31704. _this.camera.radius *= e.scale;
  31705. if (e.preventDefault) {
  31706. if (!noPreventDefault) {
  31707. e.stopPropagation();
  31708. e.preventDefault();
  31709. }
  31710. }
  31711. };
  31712. element.addEventListener("mousemove", this._onMouseMove, false);
  31713. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31714. element.addEventListener("MSGestureChange", this._onGesture, false);
  31715. BABYLON.Tools.RegisterTopRootEvents([
  31716. { name: "blur", handler: this._onLostFocus }
  31717. ]);
  31718. };
  31719. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31720. if (element && this._observer) {
  31721. this.camera.getScene().onPointerObservable.remove(this._observer);
  31722. this._observer = null;
  31723. element.removeEventListener("contextmenu", this._onContextMenu);
  31724. element.removeEventListener("mousemove", this._onMouseMove);
  31725. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31726. element.removeEventListener("MSGestureChange", this._onGesture);
  31727. this._isPanClick = false;
  31728. this.pinchInwards = true;
  31729. this._onMouseMove = null;
  31730. this._onGestureStart = null;
  31731. this._onGesture = null;
  31732. this._MSGestureHandler = null;
  31733. this._onLostFocus = null;
  31734. this._onContextMenu = null;
  31735. }
  31736. BABYLON.Tools.UnregisterTopRootEvents([
  31737. { name: "blur", handler: this._onLostFocus }
  31738. ]);
  31739. };
  31740. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31741. return "ArcRotateCameraPointersInput";
  31742. };
  31743. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31744. return "pointers";
  31745. };
  31746. return ArcRotateCameraPointersInput;
  31747. }());
  31748. __decorate([
  31749. BABYLON.serialize()
  31750. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31751. __decorate([
  31752. BABYLON.serialize()
  31753. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31754. __decorate([
  31755. BABYLON.serialize()
  31756. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31757. __decorate([
  31758. BABYLON.serialize()
  31759. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31760. __decorate([
  31761. BABYLON.serialize()
  31762. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31763. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31764. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31765. })(BABYLON || (BABYLON = {}));
  31766. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31767. /// <reference path="babylon.targetCamera.ts" />
  31768. /// <reference path="..\Tools\babylon.tools.ts" />
  31769. var BABYLON;
  31770. (function (BABYLON) {
  31771. var ArcRotateCamera = (function (_super) {
  31772. __extends(ArcRotateCamera, _super);
  31773. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31774. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31775. _this.inertialAlphaOffset = 0;
  31776. _this.inertialBetaOffset = 0;
  31777. _this.inertialRadiusOffset = 0;
  31778. _this.lowerAlphaLimit = null;
  31779. _this.upperAlphaLimit = null;
  31780. _this.lowerBetaLimit = 0.01;
  31781. _this.upperBetaLimit = Math.PI;
  31782. _this.lowerRadiusLimit = null;
  31783. _this.upperRadiusLimit = null;
  31784. _this.inertialPanningX = 0;
  31785. _this.inertialPanningY = 0;
  31786. _this.panningInertia = 0.9;
  31787. //-- end properties for backward compatibility for inputs
  31788. _this.zoomOnFactor = 1;
  31789. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31790. _this.allowUpsideDown = true;
  31791. _this._viewMatrix = new BABYLON.Matrix();
  31792. // Panning
  31793. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31794. _this.checkCollisions = false;
  31795. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31796. _this._previousPosition = BABYLON.Vector3.Zero();
  31797. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31798. _this._newPosition = BABYLON.Vector3.Zero();
  31799. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31800. if (collidedMesh === void 0) { collidedMesh = null; }
  31801. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31802. newPosition.multiplyInPlace(_this._collider.radius);
  31803. }
  31804. if (!collidedMesh) {
  31805. _this._previousPosition.copyFrom(_this.position);
  31806. }
  31807. else {
  31808. _this.setPosition(newPosition);
  31809. if (_this.onCollide) {
  31810. _this.onCollide(collidedMesh);
  31811. }
  31812. }
  31813. // Recompute because of constraints
  31814. var cosa = Math.cos(_this.alpha);
  31815. var sina = Math.sin(_this.alpha);
  31816. var cosb = Math.cos(_this.beta);
  31817. var sinb = Math.sin(_this.beta);
  31818. if (sinb === 0) {
  31819. sinb = 0.0001;
  31820. }
  31821. var target = _this._getTargetPosition();
  31822. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31823. _this.position.copyFrom(_this._newPosition);
  31824. var up = _this.upVector;
  31825. if (_this.allowUpsideDown && _this.beta < 0) {
  31826. up = up.clone();
  31827. up = up.negate();
  31828. }
  31829. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31830. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31831. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31832. _this._collisionTriggered = false;
  31833. };
  31834. _this._target = BABYLON.Vector3.Zero();
  31835. if (target) {
  31836. _this.setTarget(target);
  31837. }
  31838. _this.alpha = alpha;
  31839. _this.beta = beta;
  31840. _this.radius = radius;
  31841. _this.getViewMatrix();
  31842. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31843. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31844. return _this;
  31845. }
  31846. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31847. get: function () {
  31848. return this._target;
  31849. },
  31850. set: function (value) {
  31851. this.setTarget(value);
  31852. },
  31853. enumerable: true,
  31854. configurable: true
  31855. });
  31856. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31857. //-- begin properties for backward compatibility for inputs
  31858. get: function () {
  31859. var pointers = this.inputs.attached["pointers"];
  31860. if (pointers)
  31861. return pointers.angularSensibilityX;
  31862. },
  31863. set: function (value) {
  31864. var pointers = this.inputs.attached["pointers"];
  31865. if (pointers) {
  31866. pointers.angularSensibilityX = value;
  31867. }
  31868. },
  31869. enumerable: true,
  31870. configurable: true
  31871. });
  31872. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31873. get: function () {
  31874. var pointers = this.inputs.attached["pointers"];
  31875. if (pointers)
  31876. return pointers.angularSensibilityY;
  31877. },
  31878. set: function (value) {
  31879. var pointers = this.inputs.attached["pointers"];
  31880. if (pointers) {
  31881. pointers.angularSensibilityY = value;
  31882. }
  31883. },
  31884. enumerable: true,
  31885. configurable: true
  31886. });
  31887. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31888. get: function () {
  31889. var pointers = this.inputs.attached["pointers"];
  31890. if (pointers)
  31891. return pointers.pinchPrecision;
  31892. },
  31893. set: function (value) {
  31894. var pointers = this.inputs.attached["pointers"];
  31895. if (pointers) {
  31896. pointers.pinchPrecision = value;
  31897. }
  31898. },
  31899. enumerable: true,
  31900. configurable: true
  31901. });
  31902. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31903. get: function () {
  31904. var pointers = this.inputs.attached["pointers"];
  31905. if (pointers)
  31906. return pointers.panningSensibility;
  31907. },
  31908. set: function (value) {
  31909. var pointers = this.inputs.attached["pointers"];
  31910. if (pointers) {
  31911. pointers.panningSensibility = value;
  31912. }
  31913. },
  31914. enumerable: true,
  31915. configurable: true
  31916. });
  31917. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31918. get: function () {
  31919. var keyboard = this.inputs.attached["keyboard"];
  31920. if (keyboard)
  31921. return keyboard.keysUp;
  31922. },
  31923. set: function (value) {
  31924. var keyboard = this.inputs.attached["keyboard"];
  31925. if (keyboard)
  31926. keyboard.keysUp = value;
  31927. },
  31928. enumerable: true,
  31929. configurable: true
  31930. });
  31931. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31932. get: function () {
  31933. var keyboard = this.inputs.attached["keyboard"];
  31934. if (keyboard)
  31935. return keyboard.keysDown;
  31936. },
  31937. set: function (value) {
  31938. var keyboard = this.inputs.attached["keyboard"];
  31939. if (keyboard)
  31940. keyboard.keysDown = value;
  31941. },
  31942. enumerable: true,
  31943. configurable: true
  31944. });
  31945. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31946. get: function () {
  31947. var keyboard = this.inputs.attached["keyboard"];
  31948. if (keyboard)
  31949. return keyboard.keysLeft;
  31950. },
  31951. set: function (value) {
  31952. var keyboard = this.inputs.attached["keyboard"];
  31953. if (keyboard)
  31954. keyboard.keysLeft = value;
  31955. },
  31956. enumerable: true,
  31957. configurable: true
  31958. });
  31959. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31960. get: function () {
  31961. var keyboard = this.inputs.attached["keyboard"];
  31962. if (keyboard)
  31963. return keyboard.keysRight;
  31964. },
  31965. set: function (value) {
  31966. var keyboard = this.inputs.attached["keyboard"];
  31967. if (keyboard)
  31968. keyboard.keysRight = value;
  31969. },
  31970. enumerable: true,
  31971. configurable: true
  31972. });
  31973. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31974. get: function () {
  31975. var mousewheel = this.inputs.attached["mousewheel"];
  31976. if (mousewheel)
  31977. return mousewheel.wheelPrecision;
  31978. },
  31979. set: function (value) {
  31980. var mousewheel = this.inputs.attached["mousewheel"];
  31981. if (mousewheel)
  31982. mousewheel.wheelPrecision = value;
  31983. },
  31984. enumerable: true,
  31985. configurable: true
  31986. });
  31987. // Cache
  31988. ArcRotateCamera.prototype._initCache = function () {
  31989. _super.prototype._initCache.call(this);
  31990. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31991. this._cache.alpha = undefined;
  31992. this._cache.beta = undefined;
  31993. this._cache.radius = undefined;
  31994. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31995. };
  31996. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31997. if (!ignoreParentClass) {
  31998. _super.prototype._updateCache.call(this);
  31999. }
  32000. this._cache._target.copyFrom(this._getTargetPosition());
  32001. this._cache.alpha = this.alpha;
  32002. this._cache.beta = this.beta;
  32003. this._cache.radius = this.radius;
  32004. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  32005. };
  32006. ArcRotateCamera.prototype._getTargetPosition = function () {
  32007. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  32008. var pos = this._targetHost.getAbsolutePosition();
  32009. if (this._targetBoundingCenter) {
  32010. pos.addToRef(this._targetBoundingCenter, this._target);
  32011. }
  32012. else {
  32013. this._target.copyFrom(pos);
  32014. }
  32015. }
  32016. return this._target;
  32017. };
  32018. // Synchronized
  32019. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  32020. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  32021. return false;
  32022. return this._cache._target.equals(this._target)
  32023. && this._cache.alpha === this.alpha
  32024. && this._cache.beta === this.beta
  32025. && this._cache.radius === this.radius
  32026. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32027. };
  32028. // Methods
  32029. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32030. var _this = this;
  32031. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32032. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32033. this._useCtrlForPanning = useCtrlForPanning;
  32034. this._panningMouseButton = panningMouseButton;
  32035. this.inputs.attachElement(element, noPreventDefault);
  32036. this._reset = function () {
  32037. _this.inertialAlphaOffset = 0;
  32038. _this.inertialBetaOffset = 0;
  32039. _this.inertialRadiusOffset = 0;
  32040. };
  32041. };
  32042. ArcRotateCamera.prototype.detachControl = function (element) {
  32043. this.inputs.detachElement(element);
  32044. if (this._reset) {
  32045. this._reset();
  32046. }
  32047. };
  32048. ArcRotateCamera.prototype._checkInputs = function () {
  32049. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32050. if (this._collisionTriggered) {
  32051. return;
  32052. }
  32053. this.inputs.checkInputs();
  32054. // Inertia
  32055. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32056. if (this.getScene().useRightHandedSystem) {
  32057. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32058. }
  32059. else {
  32060. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32061. }
  32062. this.beta += this.inertialBetaOffset;
  32063. this.radius -= this.inertialRadiusOffset;
  32064. this.inertialAlphaOffset *= this.inertia;
  32065. this.inertialBetaOffset *= this.inertia;
  32066. this.inertialRadiusOffset *= this.inertia;
  32067. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32068. this.inertialAlphaOffset = 0;
  32069. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32070. this.inertialBetaOffset = 0;
  32071. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32072. this.inertialRadiusOffset = 0;
  32073. }
  32074. // Panning inertia
  32075. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32076. if (!this._localDirection) {
  32077. this._localDirection = BABYLON.Vector3.Zero();
  32078. this._transformedDirection = BABYLON.Vector3.Zero();
  32079. }
  32080. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32081. this._localDirection.multiplyInPlace(this.panningAxis);
  32082. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32083. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32084. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32085. if (!this.panningAxis.y) {
  32086. this._transformedDirection.y = 0;
  32087. }
  32088. if (!this._targetHost) {
  32089. this._target.addInPlace(this._transformedDirection);
  32090. }
  32091. this.inertialPanningX *= this.panningInertia;
  32092. this.inertialPanningY *= this.panningInertia;
  32093. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32094. this.inertialPanningX = 0;
  32095. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32096. this.inertialPanningY = 0;
  32097. }
  32098. // Limits
  32099. this._checkLimits();
  32100. _super.prototype._checkInputs.call(this);
  32101. };
  32102. ArcRotateCamera.prototype._checkLimits = function () {
  32103. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32104. if (this.allowUpsideDown && this.beta > Math.PI) {
  32105. this.beta = this.beta - (2 * Math.PI);
  32106. }
  32107. }
  32108. else {
  32109. if (this.beta < this.lowerBetaLimit) {
  32110. this.beta = this.lowerBetaLimit;
  32111. }
  32112. }
  32113. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32114. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32115. this.beta = this.beta + (2 * Math.PI);
  32116. }
  32117. }
  32118. else {
  32119. if (this.beta > this.upperBetaLimit) {
  32120. this.beta = this.upperBetaLimit;
  32121. }
  32122. }
  32123. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32124. this.alpha = this.lowerAlphaLimit;
  32125. }
  32126. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32127. this.alpha = this.upperAlphaLimit;
  32128. }
  32129. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32130. this.radius = this.lowerRadiusLimit;
  32131. }
  32132. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32133. this.radius = this.upperRadiusLimit;
  32134. }
  32135. };
  32136. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32137. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32138. this.radius = radiusv3.length();
  32139. // Alpha
  32140. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32141. if (radiusv3.z < 0) {
  32142. this.alpha = 2 * Math.PI - this.alpha;
  32143. }
  32144. // Beta
  32145. this.beta = Math.acos(radiusv3.y / this.radius);
  32146. this._checkLimits();
  32147. };
  32148. ArcRotateCamera.prototype.setPosition = function (position) {
  32149. if (this.position.equals(position)) {
  32150. return;
  32151. }
  32152. this.position.copyFrom(position);
  32153. this.rebuildAnglesAndRadius();
  32154. };
  32155. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32156. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32157. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32158. if (target.getBoundingInfo) {
  32159. if (toBoundingCenter) {
  32160. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32161. }
  32162. else {
  32163. this._targetBoundingCenter = null;
  32164. }
  32165. this._targetHost = target;
  32166. this._target = this._getTargetPosition();
  32167. }
  32168. else {
  32169. var newTarget = target;
  32170. var currentTarget = this._getTargetPosition();
  32171. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32172. return;
  32173. }
  32174. this._target = newTarget;
  32175. this._targetBoundingCenter = null;
  32176. }
  32177. this.rebuildAnglesAndRadius();
  32178. };
  32179. ArcRotateCamera.prototype._getViewMatrix = function () {
  32180. // Compute
  32181. var cosa = Math.cos(this.alpha);
  32182. var sina = Math.sin(this.alpha);
  32183. var cosb = Math.cos(this.beta);
  32184. var sinb = Math.sin(this.beta);
  32185. if (sinb === 0) {
  32186. sinb = 0.0001;
  32187. }
  32188. var target = this._getTargetPosition();
  32189. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32190. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32191. if (!this._collider) {
  32192. this._collider = new BABYLON.Collider();
  32193. }
  32194. this._collider.radius = this.collisionRadius;
  32195. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32196. this._collisionTriggered = true;
  32197. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32198. }
  32199. else {
  32200. this.position.copyFrom(this._newPosition);
  32201. var up = this.upVector;
  32202. if (this.allowUpsideDown && sinb < 0) {
  32203. up = up.clone();
  32204. up = up.negate();
  32205. }
  32206. if (this.getScene().useRightHandedSystem) {
  32207. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32208. }
  32209. else {
  32210. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32211. }
  32212. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32213. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32214. }
  32215. this._currentTarget = target;
  32216. return this._viewMatrix;
  32217. };
  32218. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32219. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32220. meshes = meshes || this.getScene().meshes;
  32221. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32222. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32223. this.radius = distance * this.zoomOnFactor;
  32224. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32225. };
  32226. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32227. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32228. var meshesOrMinMaxVector;
  32229. var distance;
  32230. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32231. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32232. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32233. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32234. }
  32235. else {
  32236. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32237. distance = meshesOrMinMaxVectorAndDistance.distance;
  32238. }
  32239. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32240. if (!doNotUpdateMaxZ) {
  32241. this.maxZ = distance * 2;
  32242. }
  32243. };
  32244. /**
  32245. * @override
  32246. * Override Camera.createRigCamera
  32247. */
  32248. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32249. var alphaShift;
  32250. switch (this.cameraRigMode) {
  32251. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32252. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32253. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32254. case BABYLON.Camera.RIG_MODE_VR:
  32255. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32256. break;
  32257. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32258. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32259. break;
  32260. }
  32261. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32262. rigCam._cameraRigParams = {};
  32263. return rigCam;
  32264. };
  32265. /**
  32266. * @override
  32267. * Override Camera._updateRigCameras
  32268. */
  32269. ArcRotateCamera.prototype._updateRigCameras = function () {
  32270. var camLeft = this._rigCameras[0];
  32271. var camRight = this._rigCameras[1];
  32272. camLeft.beta = camRight.beta = this.beta;
  32273. camLeft.radius = camRight.radius = this.radius;
  32274. switch (this.cameraRigMode) {
  32275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32276. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32277. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32278. case BABYLON.Camera.RIG_MODE_VR:
  32279. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32280. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32281. break;
  32282. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32283. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32284. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32285. break;
  32286. }
  32287. _super.prototype._updateRigCameras.call(this);
  32288. };
  32289. ArcRotateCamera.prototype.dispose = function () {
  32290. this.inputs.clear();
  32291. _super.prototype.dispose.call(this);
  32292. };
  32293. ArcRotateCamera.prototype.getClassName = function () {
  32294. return "ArcRotateCamera";
  32295. };
  32296. return ArcRotateCamera;
  32297. }(BABYLON.TargetCamera));
  32298. __decorate([
  32299. BABYLON.serialize()
  32300. ], ArcRotateCamera.prototype, "alpha", void 0);
  32301. __decorate([
  32302. BABYLON.serialize()
  32303. ], ArcRotateCamera.prototype, "beta", void 0);
  32304. __decorate([
  32305. BABYLON.serialize()
  32306. ], ArcRotateCamera.prototype, "radius", void 0);
  32307. __decorate([
  32308. BABYLON.serializeAsVector3("target")
  32309. ], ArcRotateCamera.prototype, "_target", void 0);
  32310. __decorate([
  32311. BABYLON.serialize()
  32312. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32313. __decorate([
  32314. BABYLON.serialize()
  32315. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32316. __decorate([
  32317. BABYLON.serialize()
  32318. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32319. __decorate([
  32320. BABYLON.serialize()
  32321. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32322. __decorate([
  32323. BABYLON.serialize()
  32324. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32325. __decorate([
  32326. BABYLON.serialize()
  32327. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32328. __decorate([
  32329. BABYLON.serialize()
  32330. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32331. __decorate([
  32332. BABYLON.serialize()
  32333. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32334. __decorate([
  32335. BABYLON.serialize()
  32336. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32337. __decorate([
  32338. BABYLON.serialize()
  32339. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32340. __decorate([
  32341. BABYLON.serialize()
  32342. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32343. __decorate([
  32344. BABYLON.serialize()
  32345. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32346. __decorate([
  32347. BABYLON.serialize()
  32348. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32349. __decorate([
  32350. BABYLON.serialize()
  32351. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32352. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32353. })(BABYLON || (BABYLON = {}));
  32354. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32355. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32356. var BABYLON;
  32357. (function (BABYLON) {
  32358. var ArcRotateCameraInputsManager = (function (_super) {
  32359. __extends(ArcRotateCameraInputsManager, _super);
  32360. function ArcRotateCameraInputsManager(camera) {
  32361. return _super.call(this, camera) || this;
  32362. }
  32363. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32364. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32365. return this;
  32366. };
  32367. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32368. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32369. return this;
  32370. };
  32371. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32372. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32373. return this;
  32374. };
  32375. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32376. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32377. return this;
  32378. };
  32379. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32380. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32381. return this;
  32382. };
  32383. return ArcRotateCameraInputsManager;
  32384. }(BABYLON.CameraInputsManager));
  32385. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32386. })(BABYLON || (BABYLON = {}));
  32387. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32388. var BABYLON;
  32389. (function (BABYLON) {
  32390. var CubeTexture = (function (_super) {
  32391. __extends(CubeTexture, _super);
  32392. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  32393. if (onLoad === void 0) { onLoad = null; }
  32394. if (onError === void 0) { onError = null; }
  32395. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32396. var _this = _super.call(this, scene) || this;
  32397. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32398. _this.name = rootUrl;
  32399. _this.url = rootUrl;
  32400. _this._noMipmap = noMipmap;
  32401. _this.hasAlpha = false;
  32402. _this._format = format;
  32403. if (!rootUrl && !files) {
  32404. return _this;
  32405. }
  32406. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32407. if (!files) {
  32408. if (!extensions) {
  32409. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32410. }
  32411. files = [];
  32412. for (var index = 0; index < extensions.length; index++) {
  32413. files.push(rootUrl + extensions[index]);
  32414. }
  32415. _this._extensions = extensions;
  32416. }
  32417. _this._files = files;
  32418. if (!_this._texture) {
  32419. if (!scene.useDelayedTextureLoading) {
  32420. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  32421. }
  32422. else {
  32423. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32424. }
  32425. }
  32426. else if (onLoad) {
  32427. if (_this._texture.isReady) {
  32428. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32429. }
  32430. else {
  32431. _this._texture.onLoadedCallbacks.push(onLoad);
  32432. }
  32433. }
  32434. _this.isCube = true;
  32435. _this._textureMatrix = BABYLON.Matrix.Identity();
  32436. return _this;
  32437. }
  32438. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32439. return new CubeTexture("", scene, null, noMipmap, files);
  32440. };
  32441. // Methods
  32442. CubeTexture.prototype.delayLoad = function () {
  32443. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32444. return;
  32445. }
  32446. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32447. this._texture = this._getFromCache(this.url, this._noMipmap);
  32448. if (!this._texture) {
  32449. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32450. }
  32451. };
  32452. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32453. return this._textureMatrix;
  32454. };
  32455. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32456. var texture = BABYLON.SerializationHelper.Parse(function () {
  32457. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32458. }, parsedTexture, scene);
  32459. // Animations
  32460. if (parsedTexture.animations) {
  32461. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32462. var parsedAnimation = parsedTexture.animations[animationIndex];
  32463. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32464. }
  32465. }
  32466. return texture;
  32467. };
  32468. CubeTexture.prototype.clone = function () {
  32469. var _this = this;
  32470. return BABYLON.SerializationHelper.Clone(function () {
  32471. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32472. }, this);
  32473. };
  32474. return CubeTexture;
  32475. }(BABYLON.BaseTexture));
  32476. BABYLON.CubeTexture = CubeTexture;
  32477. })(BABYLON || (BABYLON = {}));
  32478. //# sourceMappingURL=babylon.cubeTexture.js.map
  32479. var BABYLON;
  32480. (function (BABYLON) {
  32481. var RenderTargetTexture = (function (_super) {
  32482. __extends(RenderTargetTexture, _super);
  32483. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32484. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32485. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32486. if (isCube === void 0) { isCube = false; }
  32487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32488. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32489. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32490. if (isMulti === void 0) { isMulti = false; }
  32491. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32492. _this.isCube = isCube;
  32493. /**
  32494. * Use this list to define the list of mesh you want to render.
  32495. */
  32496. _this.renderList = new Array();
  32497. _this.renderParticles = true;
  32498. _this.renderSprites = false;
  32499. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32500. // Events
  32501. /**
  32502. * An event triggered when the texture is unbind.
  32503. * @type {BABYLON.Observable}
  32504. */
  32505. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32506. /**
  32507. * An event triggered before rendering the texture
  32508. * @type {BABYLON.Observable}
  32509. */
  32510. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32511. /**
  32512. * An event triggered after rendering the texture
  32513. * @type {BABYLON.Observable}
  32514. */
  32515. _this.onAfterRenderObservable = new BABYLON.Observable();
  32516. /**
  32517. * An event triggered after the texture clear
  32518. * @type {BABYLON.Observable}
  32519. */
  32520. _this.onClearObservable = new BABYLON.Observable();
  32521. _this._currentRefreshId = -1;
  32522. _this._refreshRate = 1;
  32523. _this._samples = 1;
  32524. _this.name = name;
  32525. _this.isRenderTarget = true;
  32526. _this._size = size;
  32527. _this._generateMipMaps = generateMipMaps;
  32528. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32529. // Rendering groups
  32530. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32531. if (isMulti) {
  32532. return _this;
  32533. }
  32534. _this._renderTargetOptions = {
  32535. generateMipMaps: generateMipMaps,
  32536. type: type,
  32537. samplingMode: samplingMode,
  32538. generateDepthBuffer: generateDepthBuffer,
  32539. generateStencilBuffer: generateStencilBuffer
  32540. };
  32541. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32542. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32543. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32544. }
  32545. if (isCube) {
  32546. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32547. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32548. _this._textureMatrix = BABYLON.Matrix.Identity();
  32549. }
  32550. else {
  32551. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32552. }
  32553. return _this;
  32554. }
  32555. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32556. get: function () {
  32557. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32558. },
  32559. enumerable: true,
  32560. configurable: true
  32561. });
  32562. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32563. get: function () {
  32564. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32565. },
  32566. enumerable: true,
  32567. configurable: true
  32568. });
  32569. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32570. get: function () {
  32571. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32572. },
  32573. enumerable: true,
  32574. configurable: true
  32575. });
  32576. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32577. set: function (callback) {
  32578. if (this._onAfterUnbindObserver) {
  32579. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32580. }
  32581. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32582. },
  32583. enumerable: true,
  32584. configurable: true
  32585. });
  32586. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32587. set: function (callback) {
  32588. if (this._onBeforeRenderObserver) {
  32589. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32590. }
  32591. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32597. set: function (callback) {
  32598. if (this._onAfterRenderObserver) {
  32599. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32600. }
  32601. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32602. },
  32603. enumerable: true,
  32604. configurable: true
  32605. });
  32606. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32607. set: function (callback) {
  32608. if (this._onClearObserver) {
  32609. this.onClearObservable.remove(this._onClearObserver);
  32610. }
  32611. this._onClearObserver = this.onClearObservable.add(callback);
  32612. },
  32613. enumerable: true,
  32614. configurable: true
  32615. });
  32616. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32617. get: function () {
  32618. return this._renderTargetOptions;
  32619. },
  32620. enumerable: true,
  32621. configurable: true
  32622. });
  32623. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32624. get: function () {
  32625. return this._samples;
  32626. },
  32627. set: function (value) {
  32628. if (this._samples === value) {
  32629. return;
  32630. }
  32631. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32632. },
  32633. enumerable: true,
  32634. configurable: true
  32635. });
  32636. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32637. this._currentRefreshId = -1;
  32638. };
  32639. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32640. get: function () {
  32641. return this._refreshRate;
  32642. },
  32643. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32644. set: function (value) {
  32645. this._refreshRate = value;
  32646. this.resetRefreshCounter();
  32647. },
  32648. enumerable: true,
  32649. configurable: true
  32650. });
  32651. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  32652. if (!this._postProcessManager) {
  32653. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  32654. this._postProcesses = new Array();
  32655. }
  32656. this._postProcesses.push(postProcess);
  32657. this._postProcesses[0].autoClear = false;
  32658. };
  32659. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  32660. if (!this._postProcesses) {
  32661. return;
  32662. }
  32663. if (dispose) {
  32664. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  32665. var postProcess = _a[_i];
  32666. postProcess.dispose();
  32667. postProcess = null;
  32668. }
  32669. }
  32670. this._postProcesses = [];
  32671. };
  32672. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  32673. if (!this._postProcesses) {
  32674. return;
  32675. }
  32676. var index = this._postProcesses.indexOf(postProcess);
  32677. if (index === -1) {
  32678. return;
  32679. }
  32680. this._postProcesses.splice(index, 1);
  32681. if (this._postProcesses.length > 0) {
  32682. this._postProcesses[0].autoClear = false;
  32683. }
  32684. };
  32685. RenderTargetTexture.prototype._shouldRender = function () {
  32686. if (this._currentRefreshId === -1) {
  32687. this._currentRefreshId = 1;
  32688. return true;
  32689. }
  32690. if (this.refreshRate === this._currentRefreshId) {
  32691. this._currentRefreshId = 1;
  32692. return true;
  32693. }
  32694. this._currentRefreshId++;
  32695. return false;
  32696. };
  32697. RenderTargetTexture.prototype.isReady = function () {
  32698. if (!this.getScene().renderTargetsEnabled) {
  32699. return false;
  32700. }
  32701. return _super.prototype.isReady.call(this);
  32702. };
  32703. RenderTargetTexture.prototype.getRenderSize = function () {
  32704. return this._size;
  32705. };
  32706. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  32707. get: function () {
  32708. return true;
  32709. },
  32710. enumerable: true,
  32711. configurable: true
  32712. });
  32713. RenderTargetTexture.prototype.scale = function (ratio) {
  32714. var newSize = this._size * ratio;
  32715. this.resize(newSize);
  32716. };
  32717. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  32718. if (this.isCube) {
  32719. return this._textureMatrix;
  32720. }
  32721. return _super.prototype.getReflectionTextureMatrix.call(this);
  32722. };
  32723. RenderTargetTexture.prototype.resize = function (size) {
  32724. this.releaseInternalTexture();
  32725. if (this.isCube) {
  32726. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  32727. }
  32728. else {
  32729. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  32730. }
  32731. };
  32732. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  32733. var scene = this.getScene();
  32734. var engine = scene.getEngine();
  32735. if (this.useCameraPostProcesses !== undefined) {
  32736. useCameraPostProcess = this.useCameraPostProcesses;
  32737. }
  32738. if (this._waitingRenderList) {
  32739. this.renderList = [];
  32740. for (var index = 0; index < this._waitingRenderList.length; index++) {
  32741. var id = this._waitingRenderList[index];
  32742. this.renderList.push(scene.getMeshByID(id));
  32743. }
  32744. delete this._waitingRenderList;
  32745. }
  32746. // Is predicate defined?
  32747. if (this.renderListPredicate) {
  32748. this.renderList.splice(0); // Clear previous renderList
  32749. var sceneMeshes = this.getScene().meshes;
  32750. for (var index = 0; index < sceneMeshes.length; index++) {
  32751. var mesh = sceneMeshes[index];
  32752. if (this.renderListPredicate(mesh)) {
  32753. this.renderList.push(mesh);
  32754. }
  32755. }
  32756. }
  32757. if (this.renderList && this.renderList.length === 0) {
  32758. return;
  32759. }
  32760. // Set custom projection.
  32761. // Needs to be before binding to prevent changing the aspect ratio.
  32762. var camera;
  32763. if (this.activeCamera) {
  32764. camera = this.activeCamera;
  32765. engine.setViewport(this.activeCamera.viewport);
  32766. if (this.activeCamera !== scene.activeCamera) {
  32767. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  32768. }
  32769. }
  32770. else {
  32771. camera = scene.activeCamera;
  32772. engine.setViewport(scene.activeCamera.viewport);
  32773. }
  32774. // Prepare renderingManager
  32775. this._renderingManager.reset();
  32776. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  32777. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  32778. var sceneRenderId = scene.getRenderId();
  32779. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  32780. var mesh = currentRenderList[meshIndex];
  32781. if (mesh) {
  32782. if (!mesh.isReady()) {
  32783. // Reset _currentRefreshId
  32784. this.resetRefreshCounter();
  32785. continue;
  32786. }
  32787. mesh._preActivateForIntermediateRendering(sceneRenderId);
  32788. var isMasked = void 0;
  32789. if (!this.renderList) {
  32790. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  32791. }
  32792. else {
  32793. isMasked = false;
  32794. }
  32795. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  32796. mesh._activate(sceneRenderId);
  32797. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32798. var subMesh = mesh.subMeshes[subIndex];
  32799. scene._activeIndices.addCount(subMesh.indexCount, false);
  32800. this._renderingManager.dispatch(subMesh);
  32801. }
  32802. }
  32803. }
  32804. }
  32805. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  32806. var particleSystem = scene.particleSystems[particleIndex];
  32807. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  32808. continue;
  32809. }
  32810. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  32811. this._renderingManager.dispatchParticles(particleSystem);
  32812. }
  32813. }
  32814. if (this.isCube) {
  32815. for (var face = 0; face < 6; face++) {
  32816. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32817. scene.incrementRenderId();
  32818. scene.resetCachedMaterial();
  32819. }
  32820. }
  32821. else {
  32822. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32823. }
  32824. this.onAfterUnbindObservable.notifyObservers(this);
  32825. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  32826. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  32827. }
  32828. engine.setViewport(scene.activeCamera.viewport);
  32829. scene.resetCachedMaterial();
  32830. };
  32831. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  32832. var _this = this;
  32833. var scene = this.getScene();
  32834. var engine = scene.getEngine();
  32835. // Bind
  32836. if (this._postProcessManager) {
  32837. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  32838. }
  32839. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  32840. if (this.isCube) {
  32841. engine.bindFramebuffer(this._texture, faceIndex);
  32842. }
  32843. else {
  32844. engine.bindFramebuffer(this._texture);
  32845. }
  32846. }
  32847. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  32848. // Clear
  32849. if (this.onClearObservable.hasObservers()) {
  32850. this.onClearObservable.notifyObservers(engine);
  32851. }
  32852. else {
  32853. engine.clear(scene.clearColor, true, true, true);
  32854. }
  32855. if (!this._doNotChangeAspectRatio) {
  32856. scene.updateTransformMatrix(true);
  32857. }
  32858. // Render
  32859. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  32860. if (this._postProcessManager) {
  32861. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  32862. }
  32863. else if (useCameraPostProcess) {
  32864. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  32865. }
  32866. if (!this._doNotChangeAspectRatio) {
  32867. scene.updateTransformMatrix(true);
  32868. }
  32869. // Dump ?
  32870. if (dumpForDebug) {
  32871. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  32872. }
  32873. // Unbind
  32874. if (!this.isCube || faceIndex === 5) {
  32875. if (this.isCube) {
  32876. if (faceIndex === 5) {
  32877. engine.generateMipMapsForCubemap(this._texture);
  32878. }
  32879. }
  32880. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  32881. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  32882. });
  32883. }
  32884. else {
  32885. this.onAfterRenderObservable.notifyObservers(faceIndex);
  32886. }
  32887. };
  32888. /**
  32889. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  32890. * This allowed control for front to back rendering or reversly depending of the special needs.
  32891. *
  32892. * @param renderingGroupId The rendering group id corresponding to its index
  32893. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  32894. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  32895. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  32896. */
  32897. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  32898. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  32899. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  32900. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  32901. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  32902. };
  32903. /**
  32904. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  32905. *
  32906. * @param renderingGroupId The rendering group id corresponding to its index
  32907. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  32908. */
  32909. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  32910. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  32911. };
  32912. RenderTargetTexture.prototype.clone = function () {
  32913. var textureSize = this.getSize();
  32914. 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);
  32915. // Base texture
  32916. newTexture.hasAlpha = this.hasAlpha;
  32917. newTexture.level = this.level;
  32918. // RenderTarget Texture
  32919. newTexture.coordinatesMode = this.coordinatesMode;
  32920. newTexture.renderList = this.renderList.slice(0);
  32921. return newTexture;
  32922. };
  32923. RenderTargetTexture.prototype.serialize = function () {
  32924. if (!this.name) {
  32925. return null;
  32926. }
  32927. var serializationObject = _super.prototype.serialize.call(this);
  32928. serializationObject.renderTargetSize = this.getRenderSize();
  32929. serializationObject.renderList = [];
  32930. for (var index = 0; index < this.renderList.length; index++) {
  32931. serializationObject.renderList.push(this.renderList[index].id);
  32932. }
  32933. return serializationObject;
  32934. };
  32935. RenderTargetTexture.prototype.dispose = function () {
  32936. if (this._postProcessManager) {
  32937. this._postProcessManager.dispose();
  32938. this._postProcessManager = null;
  32939. }
  32940. this.clearPostProcesses(true);
  32941. _super.prototype.dispose.call(this);
  32942. };
  32943. return RenderTargetTexture;
  32944. }(BABYLON.Texture));
  32945. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  32946. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  32947. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  32948. BABYLON.RenderTargetTexture = RenderTargetTexture;
  32949. })(BABYLON || (BABYLON = {}));
  32950. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  32951. var BABYLON;
  32952. (function (BABYLON) {
  32953. ;
  32954. var MultiRenderTarget = (function (_super) {
  32955. __extends(MultiRenderTarget, _super);
  32956. function MultiRenderTarget(name, size, count, scene, options) {
  32957. var _this = this;
  32958. options = options || {};
  32959. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  32960. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  32961. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  32962. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  32963. if (!_this.isSupported) {
  32964. _this.dispose();
  32965. return;
  32966. }
  32967. var types = [];
  32968. var samplingModes = [];
  32969. for (var i = 0; i < count; i++) {
  32970. if (options.types && options.types[i]) {
  32971. types.push(options.types[i]);
  32972. }
  32973. else {
  32974. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  32975. }
  32976. if (options.samplingModes && options.samplingModes[i]) {
  32977. samplingModes.push(options.samplingModes[i]);
  32978. }
  32979. else {
  32980. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32981. }
  32982. }
  32983. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  32984. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  32985. _this._count = count;
  32986. _this._size = size;
  32987. _this._multiRenderTargetOptions = {
  32988. samplingModes: samplingModes,
  32989. generateMipMaps: generateMipMaps,
  32990. generateDepthBuffer: generateDepthBuffer,
  32991. generateStencilBuffer: generateStencilBuffer,
  32992. generateDepthTexture: generateDepthTexture,
  32993. types: types,
  32994. textureCount: count
  32995. };
  32996. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  32997. _this._createInternalTextures();
  32998. return _this;
  32999. }
  33000. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  33001. get: function () {
  33002. var engine = this.getScene().getEngine();
  33003. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  33004. },
  33005. enumerable: true,
  33006. configurable: true
  33007. });
  33008. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  33009. get: function () {
  33010. return this._textures;
  33011. },
  33012. enumerable: true,
  33013. configurable: true
  33014. });
  33015. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  33016. get: function () {
  33017. return this._textures[this._textures.length - 1];
  33018. },
  33019. enumerable: true,
  33020. configurable: true
  33021. });
  33022. MultiRenderTarget.prototype._createInternalTextures = function () {
  33023. this._textures = [];
  33024. for (var i = 0; i < this._webGLTextures.length; i++) {
  33025. var texture = new BABYLON.Texture(null, this.getScene());
  33026. texture._texture = this._webGLTextures[i];
  33027. this._textures.push(texture);
  33028. }
  33029. // Keeps references to frame buffer and stencil/depth buffer
  33030. this._texture = this._webGLTextures[0];
  33031. };
  33032. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  33033. get: function () {
  33034. return this._samples;
  33035. },
  33036. set: function (value) {
  33037. if (this._samples === value) {
  33038. return;
  33039. }
  33040. for (var i = 0; i < this._webGLTextures.length; i++) {
  33041. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  33042. }
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. MultiRenderTarget.prototype.resize = function (size) {
  33048. this.releaseInternalTextures();
  33049. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  33050. this._createInternalTextures();
  33051. };
  33052. MultiRenderTarget.prototype.dispose = function () {
  33053. this.releaseInternalTextures();
  33054. _super.prototype.dispose.call(this);
  33055. };
  33056. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  33057. if (!this._webGLTextures) {
  33058. return;
  33059. }
  33060. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  33061. if (this._webGLTextures[i] !== undefined) {
  33062. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  33063. this._webGLTextures.splice(i, 1);
  33064. }
  33065. }
  33066. };
  33067. return MultiRenderTarget;
  33068. }(BABYLON.RenderTargetTexture));
  33069. BABYLON.MultiRenderTarget = MultiRenderTarget;
  33070. })(BABYLON || (BABYLON = {}));
  33071. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  33072. /// <reference path="babylon.renderTargetTexture.ts" />
  33073. var BABYLON;
  33074. (function (BABYLON) {
  33075. var MirrorTexture = (function (_super) {
  33076. __extends(MirrorTexture, _super);
  33077. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  33078. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33079. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  33080. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  33081. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33082. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33083. _this._transformMatrix = BABYLON.Matrix.Zero();
  33084. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33085. _this._blurKernel = 0;
  33086. _this._blurRatio = 0.6;
  33087. _this.onBeforeRenderObservable.add(function () {
  33088. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33089. _this._savedViewMatrix = scene.getViewMatrix();
  33090. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33091. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33092. scene.clipPlane = _this.mirrorPlane;
  33093. scene.getEngine().cullBackFaces = false;
  33094. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  33095. });
  33096. _this.onAfterRenderObservable.add(function () {
  33097. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33098. scene.getEngine().cullBackFaces = true;
  33099. scene._mirroredCameraPosition = null;
  33100. delete scene.clipPlane;
  33101. });
  33102. return _this;
  33103. }
  33104. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  33105. get: function () {
  33106. return this._blurRatio;
  33107. },
  33108. set: function (value) {
  33109. if (this._blurRatio === value) {
  33110. return;
  33111. }
  33112. this._blurRatio = value;
  33113. this._preparePostProcesses();
  33114. },
  33115. enumerable: true,
  33116. configurable: true
  33117. });
  33118. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  33119. get: function () {
  33120. return this._blurKernel;
  33121. },
  33122. set: function (value) {
  33123. if (this._blurKernel === value) {
  33124. return;
  33125. }
  33126. this._blurKernel = value;
  33127. this._preparePostProcesses();
  33128. },
  33129. enumerable: true,
  33130. configurable: true
  33131. });
  33132. MirrorTexture.prototype._preparePostProcesses = function () {
  33133. this.clearPostProcesses(true);
  33134. if (this._blurKernel) {
  33135. var engine = this.getScene().getEngine();
  33136. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33137. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernel, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  33138. this._blurX.autoClear = false;
  33139. this._blurX.alwaysForcePOT = false;
  33140. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernel, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  33141. this._blurY.autoClear = false;
  33142. this._blurY.alwaysForcePOT = true;
  33143. this.addPostProcess(this._blurX);
  33144. this.addPostProcess(this._blurY);
  33145. }
  33146. };
  33147. MirrorTexture.prototype.clone = function () {
  33148. var textureSize = this.getSize();
  33149. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33150. // Base texture
  33151. newTexture.hasAlpha = this.hasAlpha;
  33152. newTexture.level = this.level;
  33153. // Mirror Texture
  33154. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33155. newTexture.renderList = this.renderList.slice(0);
  33156. return newTexture;
  33157. };
  33158. MirrorTexture.prototype.serialize = function () {
  33159. if (!this.name) {
  33160. return null;
  33161. }
  33162. var serializationObject = _super.prototype.serialize.call(this);
  33163. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33164. return serializationObject;
  33165. };
  33166. return MirrorTexture;
  33167. }(BABYLON.RenderTargetTexture));
  33168. BABYLON.MirrorTexture = MirrorTexture;
  33169. })(BABYLON || (BABYLON = {}));
  33170. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33171. /// <reference path="babylon.renderTargetTexture.ts" />
  33172. var BABYLON;
  33173. (function (BABYLON) {
  33174. /**
  33175. * Creates a refraction texture used by refraction channel of the standard material.
  33176. * @param name the texture name
  33177. * @param size size of the underlying texture
  33178. * @param scene root scene
  33179. */
  33180. var RefractionTexture = (function (_super) {
  33181. __extends(RefractionTexture, _super);
  33182. function RefractionTexture(name, size, scene, generateMipMaps) {
  33183. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33184. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33185. _this.depth = 2.0;
  33186. _this.onBeforeRenderObservable.add(function () {
  33187. scene.clipPlane = _this.refractionPlane;
  33188. });
  33189. _this.onAfterRenderObservable.add(function () {
  33190. delete scene.clipPlane;
  33191. });
  33192. return _this;
  33193. }
  33194. RefractionTexture.prototype.clone = function () {
  33195. var textureSize = this.getSize();
  33196. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33197. // Base texture
  33198. newTexture.hasAlpha = this.hasAlpha;
  33199. newTexture.level = this.level;
  33200. // Refraction Texture
  33201. newTexture.refractionPlane = this.refractionPlane.clone();
  33202. newTexture.renderList = this.renderList.slice(0);
  33203. newTexture.depth = this.depth;
  33204. return newTexture;
  33205. };
  33206. RefractionTexture.prototype.serialize = function () {
  33207. if (!this.name) {
  33208. return null;
  33209. }
  33210. var serializationObject = _super.prototype.serialize.call(this);
  33211. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33212. serializationObject.depth = this.depth;
  33213. return serializationObject;
  33214. };
  33215. return RefractionTexture;
  33216. }(BABYLON.RenderTargetTexture));
  33217. BABYLON.RefractionTexture = RefractionTexture;
  33218. })(BABYLON || (BABYLON = {}));
  33219. //# sourceMappingURL=babylon.refractionTexture.js.map
  33220. /// <reference path="babylon.texture.ts" />
  33221. var BABYLON;
  33222. (function (BABYLON) {
  33223. var DynamicTexture = (function (_super) {
  33224. __extends(DynamicTexture, _super);
  33225. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33227. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33228. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33229. _this.name = name;
  33230. var engine = _this.getScene().getEngine();
  33231. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33232. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33233. _this._generateMipMaps = generateMipMaps;
  33234. if (options.getContext) {
  33235. _this._canvas = options;
  33236. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33237. }
  33238. else {
  33239. _this._canvas = document.createElement("canvas");
  33240. if (options.width) {
  33241. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33242. }
  33243. else {
  33244. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33245. }
  33246. }
  33247. var textureSize = _this.getSize();
  33248. _this._canvas.width = textureSize.width;
  33249. _this._canvas.height = textureSize.height;
  33250. _this._context = _this._canvas.getContext("2d");
  33251. return _this;
  33252. }
  33253. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33254. get: function () {
  33255. return true;
  33256. },
  33257. enumerable: true,
  33258. configurable: true
  33259. });
  33260. DynamicTexture.prototype._recreate = function (textureSize) {
  33261. this._canvas.width = textureSize.width;
  33262. this._canvas.height = textureSize.height;
  33263. this.releaseInternalTexture();
  33264. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33265. };
  33266. DynamicTexture.prototype.scale = function (ratio) {
  33267. var textureSize = this.getSize();
  33268. textureSize.width *= ratio;
  33269. textureSize.height *= ratio;
  33270. this._recreate(textureSize);
  33271. };
  33272. DynamicTexture.prototype.scaleTo = function (width, height) {
  33273. var textureSize = this.getSize();
  33274. textureSize.width = width;
  33275. textureSize.height = height;
  33276. this._recreate(textureSize);
  33277. };
  33278. DynamicTexture.prototype.getContext = function () {
  33279. return this._context;
  33280. };
  33281. DynamicTexture.prototype.clear = function () {
  33282. var size = this.getSize();
  33283. this._context.fillRect(0, 0, size.width, size.height);
  33284. };
  33285. DynamicTexture.prototype.update = function (invertY) {
  33286. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33287. };
  33288. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33289. if (update === void 0) { update = true; }
  33290. var size = this.getSize();
  33291. if (clearColor) {
  33292. this._context.fillStyle = clearColor;
  33293. this._context.fillRect(0, 0, size.width, size.height);
  33294. }
  33295. this._context.font = font;
  33296. if (x === null || x === undefined) {
  33297. var textSize = this._context.measureText(text);
  33298. x = (size.width - textSize.width) / 2;
  33299. }
  33300. if (y === null || y === undefined) {
  33301. var fontSize = parseInt((font.replace(/\D/g, '')));
  33302. ;
  33303. y = (size.height / 2) + (fontSize / 3.65);
  33304. }
  33305. this._context.fillStyle = color;
  33306. this._context.fillText(text, x, y);
  33307. if (update) {
  33308. this.update(invertY);
  33309. }
  33310. };
  33311. DynamicTexture.prototype.clone = function () {
  33312. var textureSize = this.getSize();
  33313. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33314. // Base texture
  33315. newTexture.hasAlpha = this.hasAlpha;
  33316. newTexture.level = this.level;
  33317. // Dynamic Texture
  33318. newTexture.wrapU = this.wrapU;
  33319. newTexture.wrapV = this.wrapV;
  33320. return newTexture;
  33321. };
  33322. return DynamicTexture;
  33323. }(BABYLON.Texture));
  33324. BABYLON.DynamicTexture = DynamicTexture;
  33325. })(BABYLON || (BABYLON = {}));
  33326. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33327. var BABYLON;
  33328. (function (BABYLON) {
  33329. var VideoTexture = (function (_super) {
  33330. __extends(VideoTexture, _super);
  33331. /**
  33332. * Creates a video texture.
  33333. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33334. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33335. * @param {BABYLON.Scene} scene is obviously the current scene.
  33336. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33337. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33338. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33339. */
  33340. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33341. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33342. if (invertY === void 0) { invertY = false; }
  33343. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33344. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33345. _this._autoLaunch = true;
  33346. var urls;
  33347. _this.name = name;
  33348. if (urlsOrVideo instanceof HTMLVideoElement) {
  33349. _this.video = urlsOrVideo;
  33350. }
  33351. else {
  33352. urls = urlsOrVideo;
  33353. _this.video = document.createElement("video");
  33354. _this.video.autoplay = false;
  33355. _this.video.loop = true;
  33356. }
  33357. _this._generateMipMaps = generateMipMaps;
  33358. _this._samplingMode = samplingMode;
  33359. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  33360. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33361. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33362. }
  33363. else {
  33364. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33365. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33366. _this._generateMipMaps = false;
  33367. }
  33368. if (urls) {
  33369. _this.video.addEventListener("canplay", function () {
  33370. _this._createTexture();
  33371. });
  33372. urls.forEach(function (url) {
  33373. var source = document.createElement("source");
  33374. source.src = url;
  33375. _this.video.appendChild(source);
  33376. });
  33377. }
  33378. else {
  33379. _this._createTexture();
  33380. }
  33381. _this._lastUpdate = BABYLON.Tools.Now;
  33382. return _this;
  33383. }
  33384. VideoTexture.prototype.__setTextureReady = function () {
  33385. this._texture.isReady = true;
  33386. };
  33387. VideoTexture.prototype._createTexture = function () {
  33388. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33389. if (this._autoLaunch) {
  33390. this._autoLaunch = false;
  33391. this.video.play();
  33392. }
  33393. this._setTextureReady = this.__setTextureReady.bind(this);
  33394. this.video.addEventListener("playing", this._setTextureReady);
  33395. };
  33396. VideoTexture.prototype.update = function () {
  33397. var now = BABYLON.Tools.Now;
  33398. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33399. return false;
  33400. }
  33401. this._lastUpdate = now;
  33402. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33403. return true;
  33404. };
  33405. VideoTexture.prototype.dispose = function () {
  33406. _super.prototype.dispose.call(this);
  33407. this.video.removeEventListener("playing", this._setTextureReady);
  33408. };
  33409. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33410. var video = document.createElement("video");
  33411. var constraintsDeviceId;
  33412. if (constraints && constraints.deviceId) {
  33413. constraintsDeviceId = {
  33414. exact: constraints.deviceId
  33415. };
  33416. }
  33417. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33418. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33419. if (navigator.getUserMedia) {
  33420. navigator.getUserMedia({
  33421. video: {
  33422. deviceId: constraintsDeviceId,
  33423. width: {
  33424. min: (constraints && constraints.minWidth) || 256,
  33425. max: (constraints && constraints.maxWidth) || 640
  33426. },
  33427. height: {
  33428. min: (constraints && constraints.minHeight) || 256,
  33429. max: (constraints && constraints.maxHeight) || 480
  33430. }
  33431. }
  33432. }, function (stream) {
  33433. if (video.mozSrcObject !== undefined) {
  33434. video.mozSrcObject = stream;
  33435. }
  33436. else {
  33437. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33438. }
  33439. video.play();
  33440. if (onReady) {
  33441. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33442. }
  33443. }, function (e) {
  33444. BABYLON.Tools.Error(e.name);
  33445. });
  33446. }
  33447. };
  33448. return VideoTexture;
  33449. }(BABYLON.Texture));
  33450. BABYLON.VideoTexture = VideoTexture;
  33451. })(BABYLON || (BABYLON = {}));
  33452. //# sourceMappingURL=babylon.videoTexture.js.map
  33453. var BABYLON;
  33454. (function (BABYLON) {
  33455. var RawTexture = (function (_super) {
  33456. __extends(RawTexture, _super);
  33457. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33458. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33459. if (invertY === void 0) { invertY = false; }
  33460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33461. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33462. _this.format = format;
  33463. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33464. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33465. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33466. return _this;
  33467. }
  33468. RawTexture.prototype.update = function (data) {
  33469. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33470. };
  33471. // Statics
  33472. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33473. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33474. if (invertY === void 0) { invertY = false; }
  33475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33476. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33477. };
  33478. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33479. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33480. if (invertY === void 0) { invertY = false; }
  33481. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33482. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33483. };
  33484. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33485. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33486. if (invertY === void 0) { invertY = false; }
  33487. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33488. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33489. };
  33490. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33491. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33492. if (invertY === void 0) { invertY = false; }
  33493. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33495. };
  33496. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33498. if (invertY === void 0) { invertY = false; }
  33499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33500. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33501. };
  33502. return RawTexture;
  33503. }(BABYLON.Texture));
  33504. BABYLON.RawTexture = RawTexture;
  33505. })(BABYLON || (BABYLON = {}));
  33506. //# sourceMappingURL=babylon.rawTexture.js.map
  33507. var BABYLON;
  33508. (function (BABYLON) {
  33509. var Internals;
  33510. (function (Internals) {
  33511. /*
  33512. * Based on jsTGALoader - Javascript loader for TGA file
  33513. * By Vincent Thibault
  33514. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33515. */
  33516. var TGATools = (function () {
  33517. function TGATools() {
  33518. }
  33519. TGATools.GetTGAHeader = function (data) {
  33520. var offset = 0;
  33521. var header = {
  33522. id_length: data[offset++],
  33523. colormap_type: data[offset++],
  33524. image_type: data[offset++],
  33525. colormap_index: data[offset++] | data[offset++] << 8,
  33526. colormap_length: data[offset++] | data[offset++] << 8,
  33527. colormap_size: data[offset++],
  33528. origin: [
  33529. data[offset++] | data[offset++] << 8,
  33530. data[offset++] | data[offset++] << 8
  33531. ],
  33532. width: data[offset++] | data[offset++] << 8,
  33533. height: data[offset++] | data[offset++] << 8,
  33534. pixel_size: data[offset++],
  33535. flags: data[offset++]
  33536. };
  33537. return header;
  33538. };
  33539. TGATools.UploadContent = function (gl, data) {
  33540. // Not enough data to contain header ?
  33541. if (data.length < 19) {
  33542. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33543. return;
  33544. }
  33545. // Read Header
  33546. var offset = 18;
  33547. var header = TGATools.GetTGAHeader(data);
  33548. // Assume it's a valid Targa file.
  33549. if (header.id_length + offset > data.length) {
  33550. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33551. return;
  33552. }
  33553. // Skip not needed data
  33554. offset += header.id_length;
  33555. var use_rle = false;
  33556. var use_pal = false;
  33557. var use_rgb = false;
  33558. var use_grey = false;
  33559. // Get some informations.
  33560. switch (header.image_type) {
  33561. case TGATools._TYPE_RLE_INDEXED:
  33562. use_rle = true;
  33563. case TGATools._TYPE_INDEXED:
  33564. use_pal = true;
  33565. break;
  33566. case TGATools._TYPE_RLE_RGB:
  33567. use_rle = true;
  33568. case TGATools._TYPE_RGB:
  33569. use_rgb = true;
  33570. break;
  33571. case TGATools._TYPE_RLE_GREY:
  33572. use_rle = true;
  33573. case TGATools._TYPE_GREY:
  33574. use_grey = true;
  33575. break;
  33576. }
  33577. var pixel_data;
  33578. var numAlphaBits = header.flags & 0xf;
  33579. var pixel_size = header.pixel_size >> 3;
  33580. var pixel_total = header.width * header.height * pixel_size;
  33581. // Read palettes
  33582. var palettes;
  33583. if (use_pal) {
  33584. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33585. }
  33586. // Read LRE
  33587. if (use_rle) {
  33588. pixel_data = new Uint8Array(pixel_total);
  33589. var c, count, i;
  33590. var localOffset = 0;
  33591. var pixels = new Uint8Array(pixel_size);
  33592. while (offset < pixel_total && localOffset < pixel_total) {
  33593. c = data[offset++];
  33594. count = (c & 0x7f) + 1;
  33595. // RLE pixels
  33596. if (c & 0x80) {
  33597. // Bind pixel tmp array
  33598. for (i = 0; i < pixel_size; ++i) {
  33599. pixels[i] = data[offset++];
  33600. }
  33601. // Copy pixel array
  33602. for (i = 0; i < count; ++i) {
  33603. pixel_data.set(pixels, localOffset + i * pixel_size);
  33604. }
  33605. localOffset += pixel_size * count;
  33606. }
  33607. else {
  33608. count *= pixel_size;
  33609. for (i = 0; i < count; ++i) {
  33610. pixel_data[localOffset + i] = data[offset++];
  33611. }
  33612. localOffset += count;
  33613. }
  33614. }
  33615. }
  33616. else {
  33617. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33618. }
  33619. // Load to texture
  33620. var x_start, y_start, x_step, y_step, y_end, x_end;
  33621. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33622. default:
  33623. case TGATools._ORIGIN_UL:
  33624. x_start = 0;
  33625. x_step = 1;
  33626. x_end = header.width;
  33627. y_start = 0;
  33628. y_step = 1;
  33629. y_end = header.height;
  33630. break;
  33631. case TGATools._ORIGIN_BL:
  33632. x_start = 0;
  33633. x_step = 1;
  33634. x_end = header.width;
  33635. y_start = header.height - 1;
  33636. y_step = -1;
  33637. y_end = -1;
  33638. break;
  33639. case TGATools._ORIGIN_UR:
  33640. x_start = header.width - 1;
  33641. x_step = -1;
  33642. x_end = -1;
  33643. y_start = 0;
  33644. y_step = 1;
  33645. y_end = header.height;
  33646. break;
  33647. case TGATools._ORIGIN_BR:
  33648. x_start = header.width - 1;
  33649. x_step = -1;
  33650. x_end = -1;
  33651. y_start = header.height - 1;
  33652. y_step = -1;
  33653. y_end = -1;
  33654. break;
  33655. }
  33656. // Load the specify method
  33657. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  33658. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  33659. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  33660. };
  33661. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33662. var image = pixel_data, colormap = palettes;
  33663. var width = header.width, height = header.height;
  33664. var color, i = 0, x, y;
  33665. var imageData = new Uint8Array(width * height * 4);
  33666. for (y = y_start; y !== y_end; y += y_step) {
  33667. for (x = x_start; x !== x_end; x += x_step, i++) {
  33668. color = image[i];
  33669. imageData[(x + width * y) * 4 + 3] = 255;
  33670. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  33671. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  33672. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  33673. }
  33674. }
  33675. return imageData;
  33676. };
  33677. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33678. var image = pixel_data;
  33679. var width = header.width, height = header.height;
  33680. var color, i = 0, x, y;
  33681. var imageData = new Uint8Array(width * height * 4);
  33682. for (y = y_start; y !== y_end; y += y_step) {
  33683. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33684. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  33685. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  33686. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  33687. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  33688. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  33689. }
  33690. }
  33691. return imageData;
  33692. };
  33693. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33694. var image = pixel_data;
  33695. var width = header.width, height = header.height;
  33696. var i = 0, x, y;
  33697. var imageData = new Uint8Array(width * height * 4);
  33698. for (y = y_start; y !== y_end; y += y_step) {
  33699. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  33700. imageData[(x + width * y) * 4 + 3] = 255;
  33701. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33702. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33703. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33704. }
  33705. }
  33706. return imageData;
  33707. };
  33708. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33709. var image = pixel_data;
  33710. var width = header.width, height = header.height;
  33711. var i = 0, x, y;
  33712. var imageData = new Uint8Array(width * height * 4);
  33713. for (y = y_start; y !== y_end; y += y_step) {
  33714. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  33715. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33716. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33717. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33718. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  33719. }
  33720. }
  33721. return imageData;
  33722. };
  33723. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33724. var image = pixel_data;
  33725. var width = header.width, height = header.height;
  33726. var color, i = 0, x, y;
  33727. var imageData = new Uint8Array(width * height * 4);
  33728. for (y = y_start; y !== y_end; y += y_step) {
  33729. for (x = x_start; x !== x_end; x += x_step, i++) {
  33730. color = image[i];
  33731. imageData[(x + width * y) * 4 + 0] = color;
  33732. imageData[(x + width * y) * 4 + 1] = color;
  33733. imageData[(x + width * y) * 4 + 2] = color;
  33734. imageData[(x + width * y) * 4 + 3] = 255;
  33735. }
  33736. }
  33737. return imageData;
  33738. };
  33739. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33740. var image = pixel_data;
  33741. var width = header.width, height = header.height;
  33742. var i = 0, x, y;
  33743. var imageData = new Uint8Array(width * height * 4);
  33744. for (y = y_start; y !== y_end; y += y_step) {
  33745. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33746. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  33747. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  33748. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33749. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  33750. }
  33751. }
  33752. return imageData;
  33753. };
  33754. return TGATools;
  33755. }());
  33756. TGATools._TYPE_NO_DATA = 0;
  33757. TGATools._TYPE_INDEXED = 1;
  33758. TGATools._TYPE_RGB = 2;
  33759. TGATools._TYPE_GREY = 3;
  33760. TGATools._TYPE_RLE_INDEXED = 9;
  33761. TGATools._TYPE_RLE_RGB = 10;
  33762. TGATools._TYPE_RLE_GREY = 11;
  33763. TGATools._ORIGIN_MASK = 0x30;
  33764. TGATools._ORIGIN_SHIFT = 0x04;
  33765. TGATools._ORIGIN_BL = 0x00;
  33766. TGATools._ORIGIN_BR = 0x01;
  33767. TGATools._ORIGIN_UL = 0x02;
  33768. TGATools._ORIGIN_UR = 0x03;
  33769. Internals.TGATools = TGATools;
  33770. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33771. })(BABYLON || (BABYLON = {}));
  33772. //# sourceMappingURL=babylon.tga.js.map
  33773. var BABYLON;
  33774. (function (BABYLON) {
  33775. var Internals;
  33776. (function (Internals) {
  33777. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33778. // All values and structures referenced from:
  33779. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33780. var DDS_MAGIC = 0x20534444;
  33781. 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;
  33782. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33783. 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;
  33784. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33785. function FourCCToInt32(value) {
  33786. return value.charCodeAt(0) +
  33787. (value.charCodeAt(1) << 8) +
  33788. (value.charCodeAt(2) << 16) +
  33789. (value.charCodeAt(3) << 24);
  33790. }
  33791. function Int32ToFourCC(value) {
  33792. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33793. }
  33794. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33795. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33796. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33797. var headerLengthInt = 31; // The header length in 32 bit ints
  33798. // Offsets into the header array
  33799. var off_magic = 0;
  33800. var off_size = 1;
  33801. var off_flags = 2;
  33802. var off_height = 3;
  33803. var off_width = 4;
  33804. var off_mipmapCount = 7;
  33805. var off_pfFlags = 20;
  33806. var off_pfFourCC = 21;
  33807. var off_RGBbpp = 22;
  33808. var off_RMask = 23;
  33809. var off_GMask = 24;
  33810. var off_BMask = 25;
  33811. var off_AMask = 26;
  33812. var off_caps1 = 27;
  33813. var off_caps2 = 28;
  33814. ;
  33815. var DDSTools = (function () {
  33816. function DDSTools() {
  33817. }
  33818. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33819. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33820. var mipmapCount = 1;
  33821. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33822. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33823. }
  33824. return {
  33825. width: header[off_width],
  33826. height: header[off_height],
  33827. mipmapCount: mipmapCount,
  33828. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33829. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33830. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33831. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33832. };
  33833. };
  33834. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33835. var byteArray = new Uint8Array(dataLength);
  33836. var srcData = new Uint8Array(arrayBuffer);
  33837. var index = 0;
  33838. for (var y = height - 1; y >= 0; y--) {
  33839. for (var x = 0; x < width; x++) {
  33840. var srcPos = dataOffset + (x + y * width) * 4;
  33841. byteArray[index + 2] = srcData[srcPos];
  33842. byteArray[index + 1] = srcData[srcPos + 1];
  33843. byteArray[index] = srcData[srcPos + 2];
  33844. byteArray[index + 3] = srcData[srcPos + 3];
  33845. index += 4;
  33846. }
  33847. }
  33848. return byteArray;
  33849. };
  33850. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33851. var byteArray = new Uint8Array(dataLength);
  33852. var srcData = new Uint8Array(arrayBuffer);
  33853. var index = 0;
  33854. for (var y = height - 1; y >= 0; y--) {
  33855. for (var x = 0; x < width; x++) {
  33856. var srcPos = dataOffset + (x + y * width) * 3;
  33857. byteArray[index + 2] = srcData[srcPos];
  33858. byteArray[index + 1] = srcData[srcPos + 1];
  33859. byteArray[index] = srcData[srcPos + 2];
  33860. index += 3;
  33861. }
  33862. }
  33863. return byteArray;
  33864. };
  33865. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33866. var byteArray = new Uint8Array(dataLength);
  33867. var srcData = new Uint8Array(arrayBuffer);
  33868. var index = 0;
  33869. for (var y = height - 1; y >= 0; y--) {
  33870. for (var x = 0; x < width; x++) {
  33871. var srcPos = dataOffset + (x + y * width);
  33872. byteArray[index] = srcData[srcPos];
  33873. index++;
  33874. }
  33875. }
  33876. return byteArray;
  33877. };
  33878. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33879. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33880. if (header[off_magic] != DDS_MAGIC) {
  33881. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33882. return;
  33883. }
  33884. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33885. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33886. return;
  33887. }
  33888. if (info.isFourCC) {
  33889. fourCC = header[off_pfFourCC];
  33890. switch (fourCC) {
  33891. case FOURCC_DXT1:
  33892. blockBytes = 8;
  33893. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33894. break;
  33895. case FOURCC_DXT3:
  33896. blockBytes = 16;
  33897. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33898. break;
  33899. case FOURCC_DXT5:
  33900. blockBytes = 16;
  33901. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33902. break;
  33903. default:
  33904. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33905. return;
  33906. }
  33907. }
  33908. mipmapCount = 1;
  33909. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33910. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33911. }
  33912. var bpp = header[off_RGBbpp];
  33913. for (var face = 0; face < faces; face++) {
  33914. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33915. width = header[off_width];
  33916. height = header[off_height];
  33917. dataOffset = header[off_size] + 4;
  33918. for (i = 0; i < mipmapCount; ++i) {
  33919. if (info.isRGB) {
  33920. if (bpp === 24) {
  33921. dataLength = width * height * 3;
  33922. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33923. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33924. }
  33925. else {
  33926. dataLength = width * height * 4;
  33927. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33928. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33929. }
  33930. }
  33931. else if (info.isLuminance) {
  33932. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33933. var unpaddedRowSize = width;
  33934. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33935. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33936. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33937. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33938. }
  33939. else {
  33940. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33941. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33942. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33943. }
  33944. dataOffset += dataLength;
  33945. width *= 0.5;
  33946. height *= 0.5;
  33947. width = Math.max(1.0, width);
  33948. height = Math.max(1.0, height);
  33949. }
  33950. }
  33951. };
  33952. return DDSTools;
  33953. }());
  33954. Internals.DDSTools = DDSTools;
  33955. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33956. })(BABYLON || (BABYLON = {}));
  33957. //# sourceMappingURL=babylon.dds.js.map
  33958. var BABYLON;
  33959. (function (BABYLON) {
  33960. var Internals;
  33961. (function (Internals) {
  33962. /**
  33963. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  33964. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  33965. */
  33966. var KhronosTextureContainer = (function () {
  33967. /**
  33968. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  33969. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  33970. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  33971. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  33972. */
  33973. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  33974. this.arrayBuffer = arrayBuffer;
  33975. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  33976. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  33977. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  33978. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  33979. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  33980. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  33981. BABYLON.Tools.Error("texture missing KTX identifier");
  33982. return;
  33983. }
  33984. // load the reset of the header in native 32 bit int
  33985. var header = new Int32Array(this.arrayBuffer, 12, 13);
  33986. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  33987. var oppositeEndianess = header[0] === 0x01020304;
  33988. // read all the header elements in order they exist in the file, without modification (sans endainness)
  33989. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  33990. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  33991. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  33992. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  33993. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  33994. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  33995. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  33996. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  33997. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  33998. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  33999. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  34000. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  34001. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  34002. if (this.glType !== 0) {
  34003. BABYLON.Tools.Error("only compressed formats currently supported");
  34004. return;
  34005. }
  34006. else {
  34007. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  34008. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  34009. }
  34010. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  34011. BABYLON.Tools.Error("only 2D textures currently supported");
  34012. return;
  34013. }
  34014. if (this.numberOfArrayElements !== 0) {
  34015. BABYLON.Tools.Error("texture arrays not currently supported");
  34016. return;
  34017. }
  34018. if (this.numberOfFaces !== facesExpected) {
  34019. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  34020. return;
  34021. }
  34022. // we now have a completely validated file, so could use existence of loadType as success
  34023. // would need to make this more elaborate & adjust checks above to support more than one load type
  34024. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  34025. }
  34026. // not as fast hardware based, but will probably never need to use
  34027. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  34028. return ((val & 0xFF) << 24)
  34029. | ((val & 0xFF00) << 8)
  34030. | ((val >> 8) & 0xFF00)
  34031. | ((val >> 24) & 0xFF);
  34032. };
  34033. /**
  34034. * It is assumed that the texture has already been created & is currently bound
  34035. */
  34036. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  34037. switch (this.loadType) {
  34038. case KhronosTextureContainer.COMPRESSED_2D:
  34039. this._upload2DCompressedLevels(gl, loadMipmaps);
  34040. break;
  34041. case KhronosTextureContainer.TEX_2D:
  34042. case KhronosTextureContainer.COMPRESSED_3D:
  34043. case KhronosTextureContainer.TEX_3D:
  34044. }
  34045. };
  34046. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  34047. // initialize width & height for level 1
  34048. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  34049. var width = this.pixelWidth;
  34050. var height = this.pixelHeight;
  34051. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  34052. for (var level = 0; level < mipmapCount; level++) {
  34053. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  34054. for (var face = 0; face < this.numberOfFaces; face++) {
  34055. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34056. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  34057. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  34058. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  34059. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  34060. }
  34061. width = Math.max(1.0, width * 0.5);
  34062. height = Math.max(1.0, height * 0.5);
  34063. }
  34064. };
  34065. return KhronosTextureContainer;
  34066. }());
  34067. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  34068. // load types
  34069. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  34070. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  34071. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  34072. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  34073. Internals.KhronosTextureContainer = KhronosTextureContainer;
  34074. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34075. })(BABYLON || (BABYLON = {}));
  34076. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  34077. /// <reference path="babylon.mesh.ts" />
  34078. var BABYLON;
  34079. (function (BABYLON) {
  34080. var GroundMesh = (function (_super) {
  34081. __extends(GroundMesh, _super);
  34082. function GroundMesh(name, scene) {
  34083. var _this = _super.call(this, name, scene) || this;
  34084. _this.generateOctree = false;
  34085. _this._worldInverse = new BABYLON.Matrix();
  34086. return _this;
  34087. }
  34088. GroundMesh.prototype.getClassName = function () {
  34089. return "GroundMesh";
  34090. };
  34091. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34092. get: function () {
  34093. return Math.min(this._subdivisionsX, this._subdivisionsY);
  34094. },
  34095. enumerable: true,
  34096. configurable: true
  34097. });
  34098. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  34099. get: function () {
  34100. return this._subdivisionsX;
  34101. },
  34102. enumerable: true,
  34103. configurable: true
  34104. });
  34105. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  34106. get: function () {
  34107. return this._subdivisionsY;
  34108. },
  34109. enumerable: true,
  34110. configurable: true
  34111. });
  34112. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34113. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34114. this._subdivisionsX = chunksCount;
  34115. this._subdivisionsY = chunksCount;
  34116. this.subdivide(chunksCount);
  34117. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34118. };
  34119. /**
  34120. * Returns a height (y) value in the Worl system :
  34121. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34122. * Returns the ground y position if (x, z) are outside the ground surface.
  34123. */
  34124. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34125. var world = this.getWorldMatrix();
  34126. var invMat = BABYLON.Tmp.Matrix[5];
  34127. world.invertToRef(invMat);
  34128. var tmpVect = BABYLON.Tmp.Vector3[8];
  34129. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  34130. x = tmpVect.x;
  34131. z = tmpVect.z;
  34132. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34133. return this.position.y;
  34134. }
  34135. if (!this._heightQuads || this._heightQuads.length == 0) {
  34136. this._initHeightQuads();
  34137. this._computeHeightQuads();
  34138. }
  34139. var facet = this._getFacetAt(x, z);
  34140. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34141. // return y in the World system
  34142. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  34143. return tmpVect.y;
  34144. };
  34145. /**
  34146. * Returns a normalized vector (Vector3) orthogonal to the ground
  34147. * at the ground coordinates (x, z) expressed in the World system.
  34148. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  34149. */
  34150. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34151. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  34152. this.getNormalAtCoordinatesToRef(x, z, normal);
  34153. return normal;
  34154. };
  34155. /**
  34156. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34157. * at the ground coordinates (x, z) expressed in the World system.
  34158. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34159. * Returns the GroundMesh.
  34160. */
  34161. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34162. var world = this.getWorldMatrix();
  34163. var tmpMat = BABYLON.Tmp.Matrix[5];
  34164. world.invertToRef(tmpMat);
  34165. var tmpVect = BABYLON.Tmp.Vector3[8];
  34166. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  34167. x = tmpVect.x;
  34168. z = tmpVect.z;
  34169. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34170. return this;
  34171. }
  34172. if (!this._heightQuads || this._heightQuads.length == 0) {
  34173. this._initHeightQuads();
  34174. this._computeHeightQuads();
  34175. }
  34176. var facet = this._getFacetAt(x, z);
  34177. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  34178. return this;
  34179. };
  34180. /**
  34181. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34182. * if the ground has been updated.
  34183. * This can be used in the render loop.
  34184. * Returns the GroundMesh.
  34185. */
  34186. GroundMesh.prototype.updateCoordinateHeights = function () {
  34187. if (!this._heightQuads || this._heightQuads.length == 0) {
  34188. this._initHeightQuads();
  34189. }
  34190. this._computeHeightQuads();
  34191. return this;
  34192. };
  34193. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34194. GroundMesh.prototype._getFacetAt = function (x, z) {
  34195. // retrieve col and row from x, z coordinates in the ground local system
  34196. var subdivisionsX = this._subdivisionsX;
  34197. var subdivisionsY = this._subdivisionsY;
  34198. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  34199. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  34200. var quad = this._heightQuads[row * this._subdivisionsX + col];
  34201. var facet;
  34202. if (z < quad.slope.x * x + quad.slope.y) {
  34203. facet = quad.facet1;
  34204. }
  34205. else {
  34206. facet = quad.facet2;
  34207. }
  34208. return facet;
  34209. };
  34210. // Creates and populates the heightMap array with "facet" elements :
  34211. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34212. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34213. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34214. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34215. // Returns the GroundMesh.
  34216. GroundMesh.prototype._initHeightQuads = function () {
  34217. var subdivisionsX = this._subdivisionsX;
  34218. var subdivisionsY = this._subdivisionsY;
  34219. this._heightQuads = new Array();
  34220. for (var row = 0; row < subdivisionsY; row++) {
  34221. for (var col = 0; col < subdivisionsX; col++) {
  34222. 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) };
  34223. this._heightQuads[row * subdivisionsX + col] = quad;
  34224. }
  34225. }
  34226. return this;
  34227. };
  34228. // Compute each quad element values and update the the heightMap array :
  34229. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34230. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34231. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34232. // Returns the GroundMesh.
  34233. GroundMesh.prototype._computeHeightQuads = function () {
  34234. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34235. var v1 = BABYLON.Tmp.Vector3[3];
  34236. var v2 = BABYLON.Tmp.Vector3[2];
  34237. var v3 = BABYLON.Tmp.Vector3[1];
  34238. var v4 = BABYLON.Tmp.Vector3[0];
  34239. var v1v2 = BABYLON.Tmp.Vector3[4];
  34240. var v1v3 = BABYLON.Tmp.Vector3[5];
  34241. var v1v4 = BABYLON.Tmp.Vector3[6];
  34242. var norm1 = BABYLON.Tmp.Vector3[7];
  34243. var norm2 = BABYLON.Tmp.Vector3[8];
  34244. var i = 0;
  34245. var j = 0;
  34246. var k = 0;
  34247. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34248. var h = 0;
  34249. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34250. var d2 = 0;
  34251. var subdivisionsX = this._subdivisionsX;
  34252. var subdivisionsY = this._subdivisionsY;
  34253. for (var row = 0; row < subdivisionsY; row++) {
  34254. for (var col = 0; col < subdivisionsX; col++) {
  34255. i = col * 3;
  34256. j = row * (subdivisionsX + 1) * 3;
  34257. k = (row + 1) * (subdivisionsX + 1) * 3;
  34258. v1.x = positions[j + i];
  34259. v1.y = positions[j + i + 1];
  34260. v1.z = positions[j + i + 2];
  34261. v2.x = positions[j + i + 3];
  34262. v2.y = positions[j + i + 4];
  34263. v2.z = positions[j + i + 5];
  34264. v3.x = positions[k + i];
  34265. v3.y = positions[k + i + 1];
  34266. v3.z = positions[k + i + 2];
  34267. v4.x = positions[k + i + 3];
  34268. v4.y = positions[k + i + 4];
  34269. v4.z = positions[k + i + 5];
  34270. // 2D slope V1V4
  34271. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34272. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34273. // facet equations :
  34274. // we compute each facet normal vector
  34275. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34276. // we compute the value d by applying the equation to v1 which belongs to the plane
  34277. // then we store the facet equation in a Vector4
  34278. v2.subtractToRef(v1, v1v2);
  34279. v3.subtractToRef(v1, v1v3);
  34280. v4.subtractToRef(v1, v1v4);
  34281. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34282. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34283. norm1.normalize();
  34284. norm2.normalize();
  34285. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34286. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34287. var quad = this._heightQuads[row * subdivisionsX + col];
  34288. quad.slope.copyFromFloats(cd, h);
  34289. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34290. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34291. }
  34292. }
  34293. return this;
  34294. };
  34295. GroundMesh.prototype.serialize = function (serializationObject) {
  34296. _super.prototype.serialize.call(this, serializationObject);
  34297. serializationObject.subdivisionsX = this._subdivisionsX;
  34298. serializationObject.subdivisionsY = this._subdivisionsY;
  34299. serializationObject.minX = this._minX;
  34300. serializationObject.maxX = this._maxX;
  34301. serializationObject.minZ = this._minZ;
  34302. serializationObject.maxZ = this._maxZ;
  34303. serializationObject.width = this._width;
  34304. serializationObject.height = this._height;
  34305. };
  34306. GroundMesh.Parse = function (parsedMesh, scene) {
  34307. var result = new GroundMesh(parsedMesh.name, scene);
  34308. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  34309. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  34310. result._minX = parsedMesh.minX;
  34311. result._maxX = parsedMesh.maxX;
  34312. result._minZ = parsedMesh.minZ;
  34313. result._maxZ = parsedMesh.maxZ;
  34314. result._width = parsedMesh.width;
  34315. result._height = parsedMesh.height;
  34316. return result;
  34317. };
  34318. return GroundMesh;
  34319. }(BABYLON.Mesh));
  34320. BABYLON.GroundMesh = GroundMesh;
  34321. })(BABYLON || (BABYLON = {}));
  34322. //# sourceMappingURL=babylon.groundMesh.js.map
  34323. var BABYLON;
  34324. (function (BABYLON) {
  34325. /**
  34326. * Creates an instance based on a source mesh.
  34327. */
  34328. var InstancedMesh = (function (_super) {
  34329. __extends(InstancedMesh, _super);
  34330. function InstancedMesh(name, source) {
  34331. var _this = _super.call(this, name, source.getScene()) || this;
  34332. source.instances.push(_this);
  34333. _this._sourceMesh = source;
  34334. _this.position.copyFrom(source.position);
  34335. _this.rotation.copyFrom(source.rotation);
  34336. _this.scaling.copyFrom(source.scaling);
  34337. if (source.rotationQuaternion) {
  34338. _this.rotationQuaternion = source.rotationQuaternion.clone();
  34339. }
  34340. _this.infiniteDistance = source.infiniteDistance;
  34341. _this.setPivotMatrix(source.getPivotMatrix());
  34342. _this.refreshBoundingInfo();
  34343. _this._syncSubMeshes();
  34344. return _this;
  34345. }
  34346. /**
  34347. * Returns the string "InstancedMesh".
  34348. */
  34349. InstancedMesh.prototype.getClassName = function () {
  34350. return "InstancedMesh";
  34351. };
  34352. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  34353. // Methods
  34354. get: function () {
  34355. return this._sourceMesh.receiveShadows;
  34356. },
  34357. enumerable: true,
  34358. configurable: true
  34359. });
  34360. Object.defineProperty(InstancedMesh.prototype, "material", {
  34361. get: function () {
  34362. return this._sourceMesh.material;
  34363. },
  34364. enumerable: true,
  34365. configurable: true
  34366. });
  34367. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  34368. get: function () {
  34369. return this._sourceMesh.visibility;
  34370. },
  34371. enumerable: true,
  34372. configurable: true
  34373. });
  34374. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  34375. get: function () {
  34376. return this._sourceMesh.skeleton;
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  34382. get: function () {
  34383. return this._sourceMesh.renderingGroupId;
  34384. },
  34385. enumerable: true,
  34386. configurable: true
  34387. });
  34388. /**
  34389. * Returns the total number of vertices (integer).
  34390. */
  34391. InstancedMesh.prototype.getTotalVertices = function () {
  34392. return this._sourceMesh.getTotalVertices();
  34393. };
  34394. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  34395. get: function () {
  34396. return this._sourceMesh;
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. /**
  34402. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  34403. */
  34404. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  34405. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  34406. };
  34407. /**
  34408. * Sets the vertex data of the mesh geometry for the requested `kind`.
  34409. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  34410. * The `data` are either a numeric array either a Float32Array.
  34411. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  34412. * 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).
  34413. * Note that a new underlying VertexBuffer object is created each call.
  34414. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  34415. *
  34416. * Possible `kind` values :
  34417. * - BABYLON.VertexBuffer.PositionKind
  34418. * - BABYLON.VertexBuffer.UVKind
  34419. * - BABYLON.VertexBuffer.UV2Kind
  34420. * - BABYLON.VertexBuffer.UV3Kind
  34421. * - BABYLON.VertexBuffer.UV4Kind
  34422. * - BABYLON.VertexBuffer.UV5Kind
  34423. * - BABYLON.VertexBuffer.UV6Kind
  34424. * - BABYLON.VertexBuffer.ColorKind
  34425. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34426. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34427. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34428. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34429. *
  34430. * Returns the Mesh.
  34431. */
  34432. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34433. if (this.sourceMesh) {
  34434. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  34435. }
  34436. return this.sourceMesh;
  34437. };
  34438. /**
  34439. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  34440. * If the mesh has no geometry, it is simply returned as it is.
  34441. * The `data` are either a numeric array either a Float32Array.
  34442. * No new underlying VertexBuffer object is created.
  34443. * 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.
  34444. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  34445. *
  34446. * Possible `kind` values :
  34447. * - BABYLON.VertexBuffer.PositionKind
  34448. * - BABYLON.VertexBuffer.UVKind
  34449. * - BABYLON.VertexBuffer.UV2Kind
  34450. * - BABYLON.VertexBuffer.UV3Kind
  34451. * - BABYLON.VertexBuffer.UV4Kind
  34452. * - BABYLON.VertexBuffer.UV5Kind
  34453. * - BABYLON.VertexBuffer.UV6Kind
  34454. * - BABYLON.VertexBuffer.ColorKind
  34455. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34456. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34457. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34458. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34459. *
  34460. * Returns the Mesh.
  34461. */
  34462. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  34463. if (this.sourceMesh) {
  34464. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  34465. }
  34466. return this.sourceMesh;
  34467. };
  34468. /**
  34469. * Sets the mesh indices.
  34470. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  34471. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  34472. * This method creates a new index buffer each call.
  34473. * Returns the Mesh.
  34474. */
  34475. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  34476. if (this.sourceMesh) {
  34477. this.sourceMesh.setIndices(indices, totalVertices);
  34478. }
  34479. return this.sourceMesh;
  34480. };
  34481. /**
  34482. * Boolean : True if the mesh owns the requested kind of data.
  34483. */
  34484. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  34485. return this._sourceMesh.isVerticesDataPresent(kind);
  34486. };
  34487. /**
  34488. * Returns an array of indices (IndicesArray).
  34489. */
  34490. InstancedMesh.prototype.getIndices = function () {
  34491. return this._sourceMesh.getIndices();
  34492. };
  34493. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  34494. get: function () {
  34495. return this._sourceMesh._positions;
  34496. },
  34497. enumerable: true,
  34498. configurable: true
  34499. });
  34500. /**
  34501. * Sets a new updated BoundingInfo to the mesh.
  34502. * Returns the mesh.
  34503. */
  34504. InstancedMesh.prototype.refreshBoundingInfo = function () {
  34505. var meshBB = this._sourceMesh.getBoundingInfo();
  34506. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  34507. this._updateBoundingInfo();
  34508. return this;
  34509. };
  34510. InstancedMesh.prototype._preActivate = function () {
  34511. if (this._currentLOD) {
  34512. this._currentLOD._preActivate();
  34513. }
  34514. return this;
  34515. };
  34516. InstancedMesh.prototype._activate = function (renderId) {
  34517. if (this._currentLOD) {
  34518. this._currentLOD._registerInstanceForRenderId(this, renderId);
  34519. }
  34520. return this;
  34521. };
  34522. /**
  34523. * Returns the current associated LOD AbstractMesh.
  34524. */
  34525. InstancedMesh.prototype.getLOD = function (camera) {
  34526. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  34527. if (this._currentLOD === this.sourceMesh) {
  34528. return this;
  34529. }
  34530. return this._currentLOD;
  34531. };
  34532. InstancedMesh.prototype._syncSubMeshes = function () {
  34533. this.releaseSubMeshes();
  34534. if (this._sourceMesh.subMeshes) {
  34535. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  34536. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  34537. }
  34538. }
  34539. return this;
  34540. };
  34541. InstancedMesh.prototype._generatePointsArray = function () {
  34542. return this._sourceMesh._generatePointsArray();
  34543. };
  34544. /**
  34545. * Creates a new InstancedMesh from the current mesh.
  34546. * - name (string) : the cloned mesh name
  34547. * - newParent (optional Node) : the optional Node to parent the clone to.
  34548. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  34549. *
  34550. * Returns the clone.
  34551. */
  34552. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34553. var result = this._sourceMesh.createInstance(name);
  34554. // Deep copy
  34555. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  34556. // Bounding info
  34557. this.refreshBoundingInfo();
  34558. // Parent
  34559. if (newParent) {
  34560. result.parent = newParent;
  34561. }
  34562. if (!doNotCloneChildren) {
  34563. // Children
  34564. for (var index = 0; index < this.getScene().meshes.length; index++) {
  34565. var mesh = this.getScene().meshes[index];
  34566. if (mesh.parent === this) {
  34567. mesh.clone(mesh.name, result);
  34568. }
  34569. }
  34570. }
  34571. result.computeWorldMatrix(true);
  34572. return result;
  34573. };
  34574. /**
  34575. * Disposes the InstancedMesh.
  34576. * Returns nothing.
  34577. */
  34578. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  34579. // Remove from mesh
  34580. var index = this._sourceMesh.instances.indexOf(this);
  34581. this._sourceMesh.instances.splice(index, 1);
  34582. _super.prototype.dispose.call(this, doNotRecurse);
  34583. };
  34584. return InstancedMesh;
  34585. }(BABYLON.AbstractMesh));
  34586. BABYLON.InstancedMesh = InstancedMesh;
  34587. })(BABYLON || (BABYLON = {}));
  34588. //# sourceMappingURL=babylon.instancedMesh.js.map
  34589. /// <reference path="babylon.mesh.ts" />
  34590. var BABYLON;
  34591. (function (BABYLON) {
  34592. var LinesMesh = (function (_super) {
  34593. __extends(LinesMesh, _super);
  34594. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  34595. if (parent === void 0) { parent = null; }
  34596. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  34597. _this.useVertexColor = useVertexColor;
  34598. _this.color = new BABYLON.Color3(1, 1, 1);
  34599. _this.alpha = 1;
  34600. if (source) {
  34601. _this.color = source.color.clone();
  34602. _this.alpha = source.alpha;
  34603. _this.useVertexColor = source.useVertexColor;
  34604. }
  34605. _this._intersectionThreshold = 0.1;
  34606. var options = {
  34607. attributes: [BABYLON.VertexBuffer.PositionKind],
  34608. uniforms: ["world", "viewProjection"],
  34609. needAlphaBlending: false,
  34610. };
  34611. if (!useVertexColor) {
  34612. options.uniforms.push("color");
  34613. options.needAlphaBlending = true;
  34614. }
  34615. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  34616. return _this;
  34617. }
  34618. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34619. /**
  34620. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34621. * This margin is expressed in world space coordinates, so its value may vary.
  34622. * Default value is 0.1
  34623. * @returns the intersection Threshold value.
  34624. */
  34625. get: function () {
  34626. return this._intersectionThreshold;
  34627. },
  34628. /**
  34629. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34630. * This margin is expressed in world space coordinates, so its value may vary.
  34631. * @param value the new threshold to apply
  34632. */
  34633. set: function (value) {
  34634. if (this._intersectionThreshold === value) {
  34635. return;
  34636. }
  34637. this._intersectionThreshold = value;
  34638. if (this.geometry) {
  34639. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34640. }
  34641. },
  34642. enumerable: true,
  34643. configurable: true
  34644. });
  34645. /**
  34646. * Returns the string "LineMesh"
  34647. */
  34648. LinesMesh.prototype.getClassName = function () {
  34649. return "LinesMesh";
  34650. };
  34651. Object.defineProperty(LinesMesh.prototype, "material", {
  34652. get: function () {
  34653. return this._colorShader;
  34654. },
  34655. enumerable: true,
  34656. configurable: true
  34657. });
  34658. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34659. get: function () {
  34660. return false;
  34661. },
  34662. enumerable: true,
  34663. configurable: true
  34664. });
  34665. LinesMesh.prototype.createInstance = function (name) {
  34666. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34667. return null;
  34668. };
  34669. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34670. // VBOs
  34671. this._geometry._bind(this._colorShader.getEffect());
  34672. // Color
  34673. if (!this.useVertexColor) {
  34674. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34675. }
  34676. return this;
  34677. };
  34678. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34679. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34680. return this;
  34681. }
  34682. var engine = this.getScene().getEngine();
  34683. // Draw order
  34684. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34685. return this;
  34686. };
  34687. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34688. this._colorShader.dispose();
  34689. _super.prototype.dispose.call(this, doNotRecurse);
  34690. };
  34691. /**
  34692. * Returns a new LineMesh object cloned from the current one.
  34693. */
  34694. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34695. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34696. };
  34697. return LinesMesh;
  34698. }(BABYLON.Mesh));
  34699. BABYLON.LinesMesh = LinesMesh;
  34700. })(BABYLON || (BABYLON = {}));
  34701. //# sourceMappingURL=babylon.linesMesh.js.map
  34702. var BABYLON;
  34703. (function (BABYLON) {
  34704. var StandardMaterialDefines = (function (_super) {
  34705. __extends(StandardMaterialDefines, _super);
  34706. function StandardMaterialDefines() {
  34707. var _this = _super.call(this) || this;
  34708. _this.DIFFUSE = false;
  34709. _this.AMBIENT = false;
  34710. _this.OPACITY = false;
  34711. _this.OPACITYRGB = false;
  34712. _this.REFLECTION = false;
  34713. _this.EMISSIVE = false;
  34714. _this.SPECULAR = false;
  34715. _this.BUMP = false;
  34716. _this.PARALLAX = false;
  34717. _this.PARALLAXOCCLUSION = false;
  34718. _this.SPECULAROVERALPHA = false;
  34719. _this.CLIPPLANE = false;
  34720. _this.ALPHATEST = false;
  34721. _this.ALPHAFROMDIFFUSE = false;
  34722. _this.POINTSIZE = false;
  34723. _this.FOG = false;
  34724. _this.SPECULARTERM = false;
  34725. _this.DIFFUSEFRESNEL = false;
  34726. _this.OPACITYFRESNEL = false;
  34727. _this.REFLECTIONFRESNEL = false;
  34728. _this.REFRACTIONFRESNEL = false;
  34729. _this.EMISSIVEFRESNEL = false;
  34730. _this.FRESNEL = false;
  34731. _this.NORMAL = false;
  34732. _this.UV1 = false;
  34733. _this.UV2 = false;
  34734. _this.VERTEXCOLOR = false;
  34735. _this.VERTEXALPHA = false;
  34736. _this.NUM_BONE_INFLUENCERS = 0;
  34737. _this.BonesPerMesh = 0;
  34738. _this.INSTANCES = false;
  34739. _this.GLOSSINESS = false;
  34740. _this.ROUGHNESS = false;
  34741. _this.EMISSIVEASILLUMINATION = false;
  34742. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34743. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34744. _this.LIGHTMAP = false;
  34745. _this.USELIGHTMAPASSHADOWMAP = false;
  34746. _this.REFLECTIONMAP_3D = false;
  34747. _this.REFLECTIONMAP_SPHERICAL = false;
  34748. _this.REFLECTIONMAP_PLANAR = false;
  34749. _this.REFLECTIONMAP_CUBIC = false;
  34750. _this.REFLECTIONMAP_PROJECTION = false;
  34751. _this.REFLECTIONMAP_SKYBOX = false;
  34752. _this.REFLECTIONMAP_EXPLICIT = false;
  34753. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34754. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34755. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34756. _this.INVERTCUBICMAP = false;
  34757. _this.LOGARITHMICDEPTH = false;
  34758. _this.REFRACTION = false;
  34759. _this.REFRACTIONMAP_3D = false;
  34760. _this.REFLECTIONOVERALPHA = false;
  34761. _this.INVERTNORMALMAPX = false;
  34762. _this.INVERTNORMALMAPY = false;
  34763. _this.TWOSIDEDLIGHTING = false;
  34764. _this.SHADOWFLOAT = false;
  34765. _this.CAMERACOLORGRADING = false;
  34766. _this.CAMERACOLORCURVES = false;
  34767. _this.MORPHTARGETS = false;
  34768. _this.MORPHTARGETS_NORMAL = false;
  34769. _this.MORPHTARGETS_TANGENT = false;
  34770. _this.NUM_MORPH_INFLUENCERS = 0;
  34771. _this.USERIGHTHANDEDSYSTEM = false;
  34772. _this.rebuild();
  34773. return _this;
  34774. }
  34775. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34776. var modes = [
  34777. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34778. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34779. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34780. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34781. ];
  34782. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34783. var mode = modes_1[_i];
  34784. this[mode] = (mode === modeToEnable);
  34785. }
  34786. };
  34787. return StandardMaterialDefines;
  34788. }(BABYLON.MaterialDefines));
  34789. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34790. var StandardMaterial = (function (_super) {
  34791. __extends(StandardMaterial, _super);
  34792. function StandardMaterial(name, scene) {
  34793. var _this = _super.call(this, name, scene) || this;
  34794. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34795. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34796. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34797. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34798. _this.specularPower = 64;
  34799. _this._useAlphaFromDiffuseTexture = false;
  34800. _this._useEmissiveAsIllumination = false;
  34801. _this._linkEmissiveWithDiffuse = false;
  34802. _this._useSpecularOverAlpha = false;
  34803. _this._useReflectionOverAlpha = false;
  34804. _this._disableLighting = false;
  34805. _this._useParallax = false;
  34806. _this._useParallaxOcclusion = false;
  34807. _this.parallaxScaleBias = 0.05;
  34808. _this._roughness = 0;
  34809. _this.indexOfRefraction = 0.98;
  34810. _this.invertRefractionY = true;
  34811. _this._useLightmapAsShadowmap = false;
  34812. _this._useReflectionFresnelFromSpecular = false;
  34813. _this._useGlossinessFromSpecularMapAlpha = false;
  34814. _this._maxSimultaneousLights = 4;
  34815. /**
  34816. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34817. */
  34818. _this._invertNormalMapX = false;
  34819. /**
  34820. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34821. */
  34822. _this._invertNormalMapY = false;
  34823. /**
  34824. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34825. */
  34826. _this._twoSidedLighting = false;
  34827. /**
  34828. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34829. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34830. * 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;
  34831. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34832. */
  34833. _this._cameraColorCurves = null;
  34834. _this._renderTargets = new BABYLON.SmartArray(16);
  34835. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34836. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34837. _this.getRenderTargetTextures = function () {
  34838. _this._renderTargets.reset();
  34839. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34840. _this._renderTargets.push(_this._reflectionTexture);
  34841. }
  34842. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34843. _this._renderTargets.push(_this._refractionTexture);
  34844. }
  34845. return _this._renderTargets;
  34846. };
  34847. return _this;
  34848. }
  34849. StandardMaterial.prototype.getClassName = function () {
  34850. return "StandardMaterial";
  34851. };
  34852. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34853. get: function () {
  34854. return this._useLogarithmicDepth;
  34855. },
  34856. set: function (value) {
  34857. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34858. this._markAllSubMeshesAsMiscDirty();
  34859. },
  34860. enumerable: true,
  34861. configurable: true
  34862. });
  34863. StandardMaterial.prototype.needAlphaBlending = function () {
  34864. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34865. };
  34866. StandardMaterial.prototype.needAlphaTesting = function () {
  34867. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34868. };
  34869. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34870. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34871. };
  34872. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34873. return this._diffuseTexture;
  34874. };
  34875. /**
  34876. * Child classes can use it to update shaders
  34877. */
  34878. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34879. if (this.isFrozen) {
  34880. if (this._wasPreviouslyReady && subMesh.effect) {
  34881. return true;
  34882. }
  34883. }
  34884. if (!subMesh._materialDefines) {
  34885. subMesh._materialDefines = new StandardMaterialDefines();
  34886. }
  34887. var scene = this.getScene();
  34888. var defines = subMesh._materialDefines;
  34889. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34890. if (defines._renderId === scene.getRenderId()) {
  34891. return true;
  34892. }
  34893. }
  34894. var engine = scene.getEngine();
  34895. // Lights
  34896. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34897. // Textures
  34898. if (defines._areTexturesDirty) {
  34899. defines._needUVs = false;
  34900. if (scene.texturesEnabled) {
  34901. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34902. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34903. return false;
  34904. }
  34905. else {
  34906. defines._needUVs = true;
  34907. defines.DIFFUSE = true;
  34908. }
  34909. }
  34910. else {
  34911. defines.DIFFUSE = false;
  34912. }
  34913. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34914. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34915. return false;
  34916. }
  34917. else {
  34918. defines._needUVs = true;
  34919. defines.AMBIENT = true;
  34920. }
  34921. }
  34922. else {
  34923. defines.AMBIENT = false;
  34924. }
  34925. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34926. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34927. return false;
  34928. }
  34929. else {
  34930. defines._needUVs = true;
  34931. defines.OPACITY = true;
  34932. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34933. }
  34934. }
  34935. else {
  34936. defines.OPACITY = false;
  34937. }
  34938. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34939. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34940. return false;
  34941. }
  34942. else {
  34943. defines._needNormals = true;
  34944. defines.REFLECTION = true;
  34945. defines.ROUGHNESS = (this._roughness > 0);
  34946. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34947. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34948. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34949. switch (this._reflectionTexture.coordinatesMode) {
  34950. case BABYLON.Texture.CUBIC_MODE:
  34951. case BABYLON.Texture.INVCUBIC_MODE:
  34952. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34953. break;
  34954. case BABYLON.Texture.EXPLICIT_MODE:
  34955. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34956. break;
  34957. case BABYLON.Texture.PLANAR_MODE:
  34958. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34959. break;
  34960. case BABYLON.Texture.PROJECTION_MODE:
  34961. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34962. break;
  34963. case BABYLON.Texture.SKYBOX_MODE:
  34964. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34965. break;
  34966. case BABYLON.Texture.SPHERICAL_MODE:
  34967. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34968. break;
  34969. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34970. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34971. break;
  34972. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34973. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34974. break;
  34975. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34976. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34977. break;
  34978. }
  34979. }
  34980. }
  34981. else {
  34982. defines.REFLECTION = false;
  34983. }
  34984. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34985. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34986. return false;
  34987. }
  34988. else {
  34989. defines._needUVs = true;
  34990. defines.EMISSIVE = true;
  34991. }
  34992. }
  34993. else {
  34994. defines.EMISSIVE = false;
  34995. }
  34996. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34997. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34998. return false;
  34999. }
  35000. else {
  35001. defines._needUVs = true;
  35002. defines.LIGHTMAP = true;
  35003. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35004. }
  35005. }
  35006. else {
  35007. defines.LIGHTMAP = false;
  35008. }
  35009. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35010. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35011. return false;
  35012. }
  35013. else {
  35014. defines._needUVs = true;
  35015. defines.SPECULAR = true;
  35016. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35017. }
  35018. }
  35019. else {
  35020. defines.SPECULAR = false;
  35021. }
  35022. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35023. // Bump texure can not be none blocking.
  35024. if (!this._bumpTexture.isReady()) {
  35025. return false;
  35026. }
  35027. else {
  35028. defines._needUVs = true;
  35029. defines.BUMP = true;
  35030. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  35031. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  35032. defines.PARALLAX = this._useParallax;
  35033. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35034. }
  35035. }
  35036. else {
  35037. defines.BUMP = false;
  35038. }
  35039. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35040. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35041. return false;
  35042. }
  35043. else {
  35044. defines._needUVs = true;
  35045. defines.REFRACTION = true;
  35046. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35047. }
  35048. }
  35049. else {
  35050. defines.REFRACTION = false;
  35051. }
  35052. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35053. // Camera Color Grading can not be none blocking.
  35054. if (!this._cameraColorGradingTexture.isReady()) {
  35055. return false;
  35056. }
  35057. else {
  35058. defines.CAMERACOLORGRADING = true;
  35059. }
  35060. }
  35061. else {
  35062. defines.CAMERACOLORGRADING = false;
  35063. }
  35064. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35065. }
  35066. else {
  35067. defines.DIFFUSE = false;
  35068. defines.AMBIENT = false;
  35069. defines.OPACITY = false;
  35070. defines.REFLECTION = false;
  35071. defines.EMISSIVE = false;
  35072. defines.LIGHTMAP = false;
  35073. defines.BUMP = false;
  35074. defines.REFRACTION = false;
  35075. defines.CAMERACOLORGRADING = false;
  35076. }
  35077. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  35078. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35079. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35080. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35081. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35082. }
  35083. if (defines._areFresnelDirty) {
  35084. if (StandardMaterial.FresnelEnabled) {
  35085. // Fresnel
  35086. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  35087. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  35088. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  35089. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  35090. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  35091. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35092. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35093. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35094. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35095. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35096. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35097. defines._needNormals = true;
  35098. defines.FRESNEL = true;
  35099. }
  35100. }
  35101. else {
  35102. defines.FRESNEL = false;
  35103. }
  35104. }
  35105. // Misc.
  35106. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35107. // Attribs
  35108. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35109. // Values that need to be evaluated on every frame
  35110. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35111. if (scene._mirroredCameraPosition && defines.BUMP) {
  35112. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  35113. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  35114. defines.markAsUnprocessed();
  35115. }
  35116. // Get correct effect
  35117. if (defines.isDirty) {
  35118. defines.markAsProcessed();
  35119. scene.resetCachedMaterial();
  35120. // Fallbacks
  35121. var fallbacks = new BABYLON.EffectFallbacks();
  35122. if (defines.REFLECTION) {
  35123. fallbacks.addFallback(0, "REFLECTION");
  35124. }
  35125. if (defines.SPECULAR) {
  35126. fallbacks.addFallback(0, "SPECULAR");
  35127. }
  35128. if (defines.BUMP) {
  35129. fallbacks.addFallback(0, "BUMP");
  35130. }
  35131. if (defines.PARALLAX) {
  35132. fallbacks.addFallback(1, "PARALLAX");
  35133. }
  35134. if (defines.PARALLAXOCCLUSION) {
  35135. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35136. }
  35137. if (defines.SPECULAROVERALPHA) {
  35138. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35139. }
  35140. if (defines.FOG) {
  35141. fallbacks.addFallback(1, "FOG");
  35142. }
  35143. if (defines.POINTSIZE) {
  35144. fallbacks.addFallback(0, "POINTSIZE");
  35145. }
  35146. if (defines.LOGARITHMICDEPTH) {
  35147. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35148. }
  35149. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35150. if (defines.SPECULARTERM) {
  35151. fallbacks.addFallback(0, "SPECULARTERM");
  35152. }
  35153. if (defines.DIFFUSEFRESNEL) {
  35154. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35155. }
  35156. if (defines.OPACITYFRESNEL) {
  35157. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35158. }
  35159. if (defines.REFLECTIONFRESNEL) {
  35160. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35161. }
  35162. if (defines.EMISSIVEFRESNEL) {
  35163. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35164. }
  35165. if (defines.FRESNEL) {
  35166. fallbacks.addFallback(4, "FRESNEL");
  35167. }
  35168. //Attributes
  35169. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35170. if (defines.NORMAL) {
  35171. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35172. }
  35173. if (defines.UV1) {
  35174. attribs.push(BABYLON.VertexBuffer.UVKind);
  35175. }
  35176. if (defines.UV2) {
  35177. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35178. }
  35179. if (defines.VERTEXCOLOR) {
  35180. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35181. }
  35182. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35183. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35184. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35185. var shaderName = "default";
  35186. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35187. "vFogInfos", "vFogColor", "pointSize",
  35188. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35189. "mBones",
  35190. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35191. "depthValues",
  35192. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35193. "logarithmicDepthConstant"
  35194. ];
  35195. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35196. var uniformBuffers = ["Material", "Scene"];
  35197. if (defines.CAMERACOLORCURVES) {
  35198. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35199. }
  35200. if (defines.CAMERACOLORGRADING) {
  35201. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35202. }
  35203. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35204. uniformsNames: uniforms,
  35205. uniformBuffersNames: uniformBuffers,
  35206. samplers: samplers,
  35207. defines: defines,
  35208. maxSimultaneousLights: this._maxSimultaneousLights
  35209. });
  35210. if (this.customShaderNameResolve) {
  35211. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35212. }
  35213. var join = defines.toString();
  35214. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35215. attributes: attribs,
  35216. uniformsNames: uniforms,
  35217. uniformBuffersNames: uniformBuffers,
  35218. samplers: samplers,
  35219. defines: join,
  35220. fallbacks: fallbacks,
  35221. onCompiled: this.onCompiled,
  35222. onError: this.onError,
  35223. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35224. }, engine), defines);
  35225. this.buildUniformLayout();
  35226. }
  35227. if (!subMesh.effect.isReady()) {
  35228. return false;
  35229. }
  35230. defines._renderId = scene.getRenderId();
  35231. this._wasPreviouslyReady = true;
  35232. return true;
  35233. };
  35234. StandardMaterial.prototype.buildUniformLayout = function () {
  35235. // Order is important !
  35236. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35237. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35238. this._uniformBuffer.addUniform("opacityParts", 4);
  35239. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35240. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35241. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35242. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35243. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35244. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35245. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35246. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35247. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35248. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35249. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35250. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35251. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35252. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35253. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35254. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35255. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35256. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35257. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35258. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35259. this._uniformBuffer.addUniform("specularMatrix", 16);
  35260. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35261. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35262. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35263. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35264. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35265. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35266. this._uniformBuffer.addUniform("pointSize", 1);
  35267. this._uniformBuffer.create();
  35268. };
  35269. StandardMaterial.prototype.unbind = function () {
  35270. if (this._activeEffect) {
  35271. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35272. this._activeEffect.setTexture("reflection2DSampler", null);
  35273. }
  35274. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35275. this._activeEffect.setTexture("refraction2DSampler", null);
  35276. }
  35277. }
  35278. _super.prototype.unbind.call(this);
  35279. };
  35280. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35281. var scene = this.getScene();
  35282. var defines = subMesh._materialDefines;
  35283. if (!defines) {
  35284. return;
  35285. }
  35286. var effect = subMesh.effect;
  35287. this._activeEffect = effect;
  35288. // Matrices
  35289. this.bindOnlyWorldMatrix(world);
  35290. // Bones
  35291. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35292. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35293. this._uniformBuffer.bindToEffect(effect, "Material");
  35294. this.bindViewProjection(effect);
  35295. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35296. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35297. // Fresnel
  35298. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35299. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35300. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35301. }
  35302. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35303. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35304. }
  35305. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35306. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35307. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35308. }
  35309. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35310. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35311. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35312. }
  35313. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35314. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35315. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35316. }
  35317. }
  35318. // Textures
  35319. if (scene.texturesEnabled) {
  35320. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35321. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35322. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  35323. }
  35324. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35325. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35326. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35327. }
  35328. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35329. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35330. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35331. }
  35332. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35333. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35334. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35335. }
  35336. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35337. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35338. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35339. }
  35340. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35341. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35342. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35343. }
  35344. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35345. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35346. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  35347. }
  35348. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35349. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35350. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35351. }
  35352. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35353. var depth = 1.0;
  35354. if (!this._refractionTexture.isCube) {
  35355. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35356. if (this._refractionTexture.depth) {
  35357. depth = this._refractionTexture.depth;
  35358. }
  35359. }
  35360. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35361. }
  35362. }
  35363. // Point size
  35364. if (this.pointsCloud) {
  35365. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35366. }
  35367. if (defines.SPECULARTERM) {
  35368. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35369. }
  35370. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35371. // Diffuse
  35372. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35373. }
  35374. // Textures
  35375. if (scene.texturesEnabled) {
  35376. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35377. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35378. }
  35379. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35380. effect.setTexture("ambientSampler", this._ambientTexture);
  35381. }
  35382. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35383. effect.setTexture("opacitySampler", this._opacityTexture);
  35384. }
  35385. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35386. if (this._reflectionTexture.isCube) {
  35387. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35388. }
  35389. else {
  35390. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35391. }
  35392. }
  35393. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35394. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35395. }
  35396. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35397. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35398. }
  35399. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35400. effect.setTexture("specularSampler", this._specularTexture);
  35401. }
  35402. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35403. effect.setTexture("bumpSampler", this._bumpTexture);
  35404. }
  35405. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35406. var depth = 1.0;
  35407. if (this._refractionTexture.isCube) {
  35408. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35409. }
  35410. else {
  35411. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35412. }
  35413. }
  35414. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35415. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  35416. }
  35417. }
  35418. // Clip plane
  35419. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35420. // Colors
  35421. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35422. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35423. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35424. }
  35425. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35426. // Lights
  35427. if (scene.lightsEnabled && !this._disableLighting) {
  35428. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35429. }
  35430. // View
  35431. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35432. this.bindView(effect);
  35433. }
  35434. // Fog
  35435. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35436. // Morph targets
  35437. if (defines.NUM_MORPH_INFLUENCERS) {
  35438. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35439. }
  35440. // Log. depth
  35441. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35442. // Color Curves
  35443. if (this._cameraColorCurves) {
  35444. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  35445. }
  35446. }
  35447. this._uniformBuffer.update();
  35448. this._afterBind(mesh, this._activeEffect);
  35449. };
  35450. StandardMaterial.prototype.getAnimatables = function () {
  35451. var results = [];
  35452. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35453. results.push(this._diffuseTexture);
  35454. }
  35455. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35456. results.push(this._ambientTexture);
  35457. }
  35458. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35459. results.push(this._opacityTexture);
  35460. }
  35461. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35462. results.push(this._reflectionTexture);
  35463. }
  35464. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35465. results.push(this._emissiveTexture);
  35466. }
  35467. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35468. results.push(this._specularTexture);
  35469. }
  35470. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35471. results.push(this._bumpTexture);
  35472. }
  35473. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35474. results.push(this._lightmapTexture);
  35475. }
  35476. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35477. results.push(this._refractionTexture);
  35478. }
  35479. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35480. results.push(this._cameraColorGradingTexture);
  35481. }
  35482. return results;
  35483. };
  35484. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35485. if (forceDisposeTextures) {
  35486. if (this._diffuseTexture) {
  35487. this._diffuseTexture.dispose();
  35488. }
  35489. if (this._ambientTexture) {
  35490. this._ambientTexture.dispose();
  35491. }
  35492. if (this._opacityTexture) {
  35493. this._opacityTexture.dispose();
  35494. }
  35495. if (this._reflectionTexture) {
  35496. this._reflectionTexture.dispose();
  35497. }
  35498. if (this._emissiveTexture) {
  35499. this._emissiveTexture.dispose();
  35500. }
  35501. if (this._specularTexture) {
  35502. this._specularTexture.dispose();
  35503. }
  35504. if (this._bumpTexture) {
  35505. this._bumpTexture.dispose();
  35506. }
  35507. if (this._lightmapTexture) {
  35508. this._lightmapTexture.dispose();
  35509. }
  35510. if (this._refractionTexture) {
  35511. this._refractionTexture.dispose();
  35512. }
  35513. if (this._cameraColorGradingTexture) {
  35514. this._cameraColorGradingTexture.dispose();
  35515. }
  35516. }
  35517. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35518. };
  35519. StandardMaterial.prototype.clone = function (name) {
  35520. var _this = this;
  35521. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35522. result.name = name;
  35523. result.id = name;
  35524. return result;
  35525. };
  35526. StandardMaterial.prototype.serialize = function () {
  35527. return BABYLON.SerializationHelper.Serialize(this);
  35528. };
  35529. // Statics
  35530. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35531. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35532. };
  35533. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35534. get: function () {
  35535. return StandardMaterial._DiffuseTextureEnabled;
  35536. },
  35537. set: function (value) {
  35538. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35539. return;
  35540. }
  35541. StandardMaterial._DiffuseTextureEnabled = value;
  35542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35543. },
  35544. enumerable: true,
  35545. configurable: true
  35546. });
  35547. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35548. get: function () {
  35549. return StandardMaterial._AmbientTextureEnabled;
  35550. },
  35551. set: function (value) {
  35552. if (StandardMaterial._AmbientTextureEnabled === value) {
  35553. return;
  35554. }
  35555. StandardMaterial._AmbientTextureEnabled = value;
  35556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35557. },
  35558. enumerable: true,
  35559. configurable: true
  35560. });
  35561. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35562. get: function () {
  35563. return StandardMaterial._OpacityTextureEnabled;
  35564. },
  35565. set: function (value) {
  35566. if (StandardMaterial._OpacityTextureEnabled === value) {
  35567. return;
  35568. }
  35569. StandardMaterial._OpacityTextureEnabled = value;
  35570. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35571. },
  35572. enumerable: true,
  35573. configurable: true
  35574. });
  35575. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35576. get: function () {
  35577. return StandardMaterial._ReflectionTextureEnabled;
  35578. },
  35579. set: function (value) {
  35580. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35581. return;
  35582. }
  35583. StandardMaterial._ReflectionTextureEnabled = value;
  35584. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35585. },
  35586. enumerable: true,
  35587. configurable: true
  35588. });
  35589. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35590. get: function () {
  35591. return StandardMaterial._EmissiveTextureEnabled;
  35592. },
  35593. set: function (value) {
  35594. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35595. return;
  35596. }
  35597. StandardMaterial._EmissiveTextureEnabled = value;
  35598. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35599. },
  35600. enumerable: true,
  35601. configurable: true
  35602. });
  35603. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35604. get: function () {
  35605. return StandardMaterial._SpecularTextureEnabled;
  35606. },
  35607. set: function (value) {
  35608. if (StandardMaterial._SpecularTextureEnabled === value) {
  35609. return;
  35610. }
  35611. StandardMaterial._SpecularTextureEnabled = value;
  35612. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35613. },
  35614. enumerable: true,
  35615. configurable: true
  35616. });
  35617. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35618. get: function () {
  35619. return StandardMaterial._BumpTextureEnabled;
  35620. },
  35621. set: function (value) {
  35622. if (StandardMaterial._BumpTextureEnabled === value) {
  35623. return;
  35624. }
  35625. StandardMaterial._BumpTextureEnabled = value;
  35626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35627. },
  35628. enumerable: true,
  35629. configurable: true
  35630. });
  35631. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35632. get: function () {
  35633. return StandardMaterial._LightmapTextureEnabled;
  35634. },
  35635. set: function (value) {
  35636. if (StandardMaterial._LightmapTextureEnabled === value) {
  35637. return;
  35638. }
  35639. StandardMaterial._LightmapTextureEnabled = value;
  35640. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35641. },
  35642. enumerable: true,
  35643. configurable: true
  35644. });
  35645. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35646. get: function () {
  35647. return StandardMaterial._RefractionTextureEnabled;
  35648. },
  35649. set: function (value) {
  35650. if (StandardMaterial._RefractionTextureEnabled === value) {
  35651. return;
  35652. }
  35653. StandardMaterial._RefractionTextureEnabled = value;
  35654. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35655. },
  35656. enumerable: true,
  35657. configurable: true
  35658. });
  35659. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35660. get: function () {
  35661. return StandardMaterial._ColorGradingTextureEnabled;
  35662. },
  35663. set: function (value) {
  35664. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35665. return;
  35666. }
  35667. StandardMaterial._ColorGradingTextureEnabled = value;
  35668. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35669. },
  35670. enumerable: true,
  35671. configurable: true
  35672. });
  35673. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35674. get: function () {
  35675. return StandardMaterial._FresnelEnabled;
  35676. },
  35677. set: function (value) {
  35678. if (StandardMaterial._FresnelEnabled === value) {
  35679. return;
  35680. }
  35681. StandardMaterial._FresnelEnabled = value;
  35682. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35683. },
  35684. enumerable: true,
  35685. configurable: true
  35686. });
  35687. return StandardMaterial;
  35688. }(BABYLON.PushMaterial));
  35689. // Flags used to enable or disable a type of texture for all Standard Materials
  35690. StandardMaterial._DiffuseTextureEnabled = true;
  35691. StandardMaterial._AmbientTextureEnabled = true;
  35692. StandardMaterial._OpacityTextureEnabled = true;
  35693. StandardMaterial._ReflectionTextureEnabled = true;
  35694. StandardMaterial._EmissiveTextureEnabled = true;
  35695. StandardMaterial._SpecularTextureEnabled = true;
  35696. StandardMaterial._BumpTextureEnabled = true;
  35697. StandardMaterial._LightmapTextureEnabled = true;
  35698. StandardMaterial._RefractionTextureEnabled = true;
  35699. StandardMaterial._ColorGradingTextureEnabled = true;
  35700. StandardMaterial._FresnelEnabled = true;
  35701. __decorate([
  35702. BABYLON.serializeAsTexture("diffuseTexture")
  35703. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35704. __decorate([
  35705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35706. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35707. __decorate([
  35708. BABYLON.serializeAsTexture("ambientTexture")
  35709. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35710. __decorate([
  35711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35712. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35713. __decorate([
  35714. BABYLON.serializeAsTexture("opacityTexture")
  35715. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35716. __decorate([
  35717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35718. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35719. __decorate([
  35720. BABYLON.serializeAsTexture("reflectionTexture")
  35721. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35722. __decorate([
  35723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35724. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35725. __decorate([
  35726. BABYLON.serializeAsTexture("emissiveTexture")
  35727. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35728. __decorate([
  35729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35730. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35731. __decorate([
  35732. BABYLON.serializeAsTexture("specularTexture")
  35733. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35734. __decorate([
  35735. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35736. ], StandardMaterial.prototype, "specularTexture", void 0);
  35737. __decorate([
  35738. BABYLON.serializeAsTexture("bumpTexture")
  35739. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35740. __decorate([
  35741. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35742. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35743. __decorate([
  35744. BABYLON.serializeAsTexture("lightmapTexture")
  35745. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35746. __decorate([
  35747. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35748. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35749. __decorate([
  35750. BABYLON.serializeAsTexture("refractionTexture")
  35751. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35752. __decorate([
  35753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35754. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35755. __decorate([
  35756. BABYLON.serializeAsColor3("ambient")
  35757. ], StandardMaterial.prototype, "ambientColor", void 0);
  35758. __decorate([
  35759. BABYLON.serializeAsColor3("diffuse")
  35760. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35761. __decorate([
  35762. BABYLON.serializeAsColor3("specular")
  35763. ], StandardMaterial.prototype, "specularColor", void 0);
  35764. __decorate([
  35765. BABYLON.serializeAsColor3("emissive")
  35766. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35767. __decorate([
  35768. BABYLON.serialize()
  35769. ], StandardMaterial.prototype, "specularPower", void 0);
  35770. __decorate([
  35771. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35772. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35773. __decorate([
  35774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35775. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35776. __decorate([
  35777. BABYLON.serialize("useEmissiveAsIllumination")
  35778. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35779. __decorate([
  35780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35781. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35782. __decorate([
  35783. BABYLON.serialize("linkEmissiveWithDiffuse")
  35784. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35785. __decorate([
  35786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35787. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35788. __decorate([
  35789. BABYLON.serialize("useSpecularOverAlpha")
  35790. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35791. __decorate([
  35792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35793. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35794. __decorate([
  35795. BABYLON.serialize("useReflectionOverAlpha")
  35796. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35797. __decorate([
  35798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35799. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35800. __decorate([
  35801. BABYLON.serialize("disableLighting")
  35802. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35803. __decorate([
  35804. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35805. ], StandardMaterial.prototype, "disableLighting", void 0);
  35806. __decorate([
  35807. BABYLON.serialize("useParallax")
  35808. ], StandardMaterial.prototype, "_useParallax", void 0);
  35809. __decorate([
  35810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35811. ], StandardMaterial.prototype, "useParallax", void 0);
  35812. __decorate([
  35813. BABYLON.serialize("useParallaxOcclusion")
  35814. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35815. __decorate([
  35816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35817. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35818. __decorate([
  35819. BABYLON.serialize()
  35820. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35821. __decorate([
  35822. BABYLON.serialize("roughness")
  35823. ], StandardMaterial.prototype, "_roughness", void 0);
  35824. __decorate([
  35825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35826. ], StandardMaterial.prototype, "roughness", void 0);
  35827. __decorate([
  35828. BABYLON.serialize()
  35829. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35830. __decorate([
  35831. BABYLON.serialize()
  35832. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35833. __decorate([
  35834. BABYLON.serialize("useLightmapAsShadowmap")
  35835. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35836. __decorate([
  35837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35838. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35839. __decorate([
  35840. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35841. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35842. __decorate([
  35843. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35844. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35845. __decorate([
  35846. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35847. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35848. __decorate([
  35849. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35850. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35851. __decorate([
  35852. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35853. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35854. __decorate([
  35855. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35856. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35857. __decorate([
  35858. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35859. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35860. __decorate([
  35861. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35862. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35863. __decorate([
  35864. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35865. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35866. __decorate([
  35867. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35868. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35869. __decorate([
  35870. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35871. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35872. __decorate([
  35873. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35874. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35875. __decorate([
  35876. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35877. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35878. __decorate([
  35879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35880. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35881. __decorate([
  35882. BABYLON.serialize("maxSimultaneousLights")
  35883. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35884. __decorate([
  35885. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35886. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35887. __decorate([
  35888. BABYLON.serialize("invertNormalMapX")
  35889. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35890. __decorate([
  35891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35892. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35893. __decorate([
  35894. BABYLON.serialize("invertNormalMapY")
  35895. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35896. __decorate([
  35897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35898. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35899. __decorate([
  35900. BABYLON.serialize("twoSidedLighting")
  35901. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35902. __decorate([
  35903. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35904. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35905. __decorate([
  35906. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  35907. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  35908. __decorate([
  35909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35910. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  35911. __decorate([
  35912. BABYLON.serializeAsColorCurves("cameraColorCurves")
  35913. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  35914. __decorate([
  35915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35916. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  35917. __decorate([
  35918. BABYLON.serialize()
  35919. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35920. BABYLON.StandardMaterial = StandardMaterial;
  35921. })(BABYLON || (BABYLON = {}));
  35922. //# sourceMappingURL=babylon.standardMaterial.js.map
  35923. var BABYLON;
  35924. (function (BABYLON) {
  35925. /**
  35926. * This class implement a typical dictionary using a string as key and the generic type T as value.
  35927. * The underlying implementation relies on an associative array to ensure the best performances.
  35928. * The value can be anything including 'null' but except 'undefined'
  35929. */
  35930. var StringDictionary = (function () {
  35931. function StringDictionary() {
  35932. this._count = 0;
  35933. this._data = {};
  35934. }
  35935. /**
  35936. * This will clear this dictionary and copy the content from the 'source' one.
  35937. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  35938. * @param source the dictionary to take the content from and copy to this dictionary
  35939. */
  35940. StringDictionary.prototype.copyFrom = function (source) {
  35941. var _this = this;
  35942. this.clear();
  35943. source.forEach(function (t, v) { return _this.add(t, v); });
  35944. };
  35945. /**
  35946. * Get a value based from its key
  35947. * @param key the given key to get the matching value from
  35948. * @return the value if found, otherwise undefined is returned
  35949. */
  35950. StringDictionary.prototype.get = function (key) {
  35951. var val = this._data[key];
  35952. if (val !== undefined) {
  35953. return val;
  35954. }
  35955. return undefined;
  35956. };
  35957. /**
  35958. * Get a value from its key or add it if it doesn't exist.
  35959. * This method will ensure you that a given key/data will be present in the dictionary.
  35960. * @param key the given key to get the matching value from
  35961. * @param factory the factory that will create the value if the key is not present in the dictionary.
  35962. * The factory will only be invoked if there's no data for the given key.
  35963. * @return the value corresponding to the key.
  35964. */
  35965. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  35966. var val = this.get(key);
  35967. if (val !== undefined) {
  35968. return val;
  35969. }
  35970. val = factory(key);
  35971. if (val) {
  35972. this.add(key, val);
  35973. }
  35974. return val;
  35975. };
  35976. /**
  35977. * Get a value from its key if present in the dictionary otherwise add it
  35978. * @param key the key to get the value from
  35979. * @param val if there's no such key/value pair in the dictionary add it with this value
  35980. * @return the value corresponding to the key
  35981. */
  35982. StringDictionary.prototype.getOrAdd = function (key, val) {
  35983. var curVal = this.get(key);
  35984. if (curVal !== undefined) {
  35985. return curVal;
  35986. }
  35987. this.add(key, val);
  35988. return val;
  35989. };
  35990. /**
  35991. * Check if there's a given key in the dictionary
  35992. * @param key the key to check for
  35993. * @return true if the key is present, false otherwise
  35994. */
  35995. StringDictionary.prototype.contains = function (key) {
  35996. return this._data[key] !== undefined;
  35997. };
  35998. /**
  35999. * Add a new key and its corresponding value
  36000. * @param key the key to add
  36001. * @param value the value corresponding to the key
  36002. * @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
  36003. */
  36004. StringDictionary.prototype.add = function (key, value) {
  36005. if (this._data[key] !== undefined) {
  36006. return false;
  36007. }
  36008. this._data[key] = value;
  36009. ++this._count;
  36010. return true;
  36011. };
  36012. StringDictionary.prototype.set = function (key, value) {
  36013. if (this._data[key] === undefined) {
  36014. return false;
  36015. }
  36016. this._data[key] = value;
  36017. return true;
  36018. };
  36019. /**
  36020. * Get the element of the given key and remove it from the dictionary
  36021. * @param key
  36022. */
  36023. StringDictionary.prototype.getAndRemove = function (key) {
  36024. var val = this.get(key);
  36025. if (val !== undefined) {
  36026. delete this._data[key];
  36027. --this._count;
  36028. return val;
  36029. }
  36030. return null;
  36031. };
  36032. /**
  36033. * Remove a key/value from the dictionary.
  36034. * @param key the key to remove
  36035. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  36036. */
  36037. StringDictionary.prototype.remove = function (key) {
  36038. if (this.contains(key)) {
  36039. delete this._data[key];
  36040. --this._count;
  36041. return true;
  36042. }
  36043. return false;
  36044. };
  36045. /**
  36046. * Clear the whole content of the dictionary
  36047. */
  36048. StringDictionary.prototype.clear = function () {
  36049. this._data = {};
  36050. this._count = 0;
  36051. };
  36052. Object.defineProperty(StringDictionary.prototype, "count", {
  36053. get: function () {
  36054. return this._count;
  36055. },
  36056. enumerable: true,
  36057. configurable: true
  36058. });
  36059. /**
  36060. * Execute a callback on each key/val of the dictionary.
  36061. * Note that you can remove any element in this dictionary in the callback implementation
  36062. * @param callback the callback to execute on a given key/value pair
  36063. */
  36064. StringDictionary.prototype.forEach = function (callback) {
  36065. for (var cur in this._data) {
  36066. var val = this._data[cur];
  36067. callback(cur, val);
  36068. }
  36069. };
  36070. /**
  36071. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  36072. * If the callback returns null or undefined the method will iterate to the next key/value pair
  36073. * Note that you can remove any element in this dictionary in the callback implementation
  36074. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  36075. */
  36076. StringDictionary.prototype.first = function (callback) {
  36077. for (var cur in this._data) {
  36078. var val = this._data[cur];
  36079. var res = callback(cur, val);
  36080. if (res) {
  36081. return res;
  36082. }
  36083. }
  36084. return null;
  36085. };
  36086. return StringDictionary;
  36087. }());
  36088. BABYLON.StringDictionary = StringDictionary;
  36089. })(BABYLON || (BABYLON = {}));
  36090. //# sourceMappingURL=babylon.stringDictionary.js.map
  36091. var BABYLON;
  36092. (function (BABYLON) {
  36093. var DynamicFloatArrayElementInfo = (function () {
  36094. function DynamicFloatArrayElementInfo() {
  36095. }
  36096. return DynamicFloatArrayElementInfo;
  36097. }());
  36098. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  36099. /**
  36100. * 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.
  36101. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  36102. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  36103. * 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.
  36104. * 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.
  36105. * 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".
  36106. */
  36107. var DynamicFloatArray = (function () {
  36108. /**
  36109. * Construct an instance of the dynamic float array
  36110. * @param stride size of one element in float (i.e. not bytes!)
  36111. * @param initialElementCount the number of available entries at construction
  36112. */
  36113. function DynamicFloatArray(stride, initialElementCount) {
  36114. this.compareValueOffset = null;
  36115. this.sortingAscending = true;
  36116. this._stride = stride;
  36117. this.buffer = new Float32Array(stride * initialElementCount);
  36118. this._lastUsed = 0;
  36119. this._firstFree = 0;
  36120. this._allEntries = new Array(initialElementCount);
  36121. this._freeEntries = new Array(initialElementCount);
  36122. for (var i = 0; i < initialElementCount; i++) {
  36123. var element = new DynamicFloatArrayElementInfo();
  36124. element.offset = i * stride;
  36125. this._allEntries[i] = element;
  36126. this._freeEntries[initialElementCount - i - 1] = element;
  36127. }
  36128. }
  36129. /**
  36130. * Allocate an element in the array.
  36131. * @return the element info instance that contains the offset into the main buffer of the element's location.
  36132. * Beware, this offset may change when you call pack()
  36133. */
  36134. DynamicFloatArray.prototype.allocElement = function () {
  36135. if (this._freeEntries.length === 0) {
  36136. this._growBuffer();
  36137. }
  36138. var el = this._freeEntries.pop();
  36139. this._lastUsed = Math.max(el.offset, this._lastUsed);
  36140. if (el.offset === this._firstFree) {
  36141. if (this._freeEntries.length > 0) {
  36142. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  36143. }
  36144. else {
  36145. this._firstFree += this._stride;
  36146. }
  36147. }
  36148. return el;
  36149. };
  36150. /**
  36151. * Free the element corresponding to the given element info
  36152. * @param elInfo the element that describe the allocated element
  36153. */
  36154. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  36155. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  36156. this._freeEntries.push(elInfo);
  36157. };
  36158. /**
  36159. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  36160. * 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().
  36161. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  36162. */
  36163. DynamicFloatArray.prototype.pack = function () {
  36164. // no free slot? no need to pack
  36165. if (this._freeEntries.length === 0) {
  36166. return this.buffer;
  36167. }
  36168. // If the buffer is already packed the last used will always be lower than the first free
  36169. // 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.
  36170. if (this._lastUsed < this._firstFree) {
  36171. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  36172. return elementsBuffer_1;
  36173. }
  36174. var s = this._stride;
  36175. // 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
  36176. var lastFree = new DynamicFloatArrayElementInfo();
  36177. lastFree.offset = this.totalElementCount * s;
  36178. this._freeEntries.push(lastFree);
  36179. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  36180. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36181. var firstFreeSlotOffset = sortedFree[0].offset;
  36182. var freeZoneSize = 1;
  36183. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  36184. var prevOffset = sortedFree[0].offset;
  36185. for (var i = 1; i < sortedFree.length; i++) {
  36186. // 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
  36187. if (firstFreeSlotOffset >= occupiedZoneSize) {
  36188. break;
  36189. }
  36190. var curFree = sortedFree[i];
  36191. var curOffset = curFree.offset;
  36192. // Compute the distance between this offset and the previous
  36193. var distance = curOffset - prevOffset;
  36194. // If the distance is the stride size, they are adjacent, it good, move to the next
  36195. if (distance === s) {
  36196. // Free zone is one element bigger
  36197. ++freeZoneSize;
  36198. // as we're about to iterate to the next, the cur becomes the previous...
  36199. prevOffset = curOffset;
  36200. continue;
  36201. }
  36202. // Distance is bigger, which means there's x element between the previous free and this one
  36203. var usedRange = (distance / s) - 1;
  36204. // Two cases the free zone is smaller than the data to move or bigger
  36205. // Copy what can fit in the free zone
  36206. var curMoveOffset = curOffset - s;
  36207. var copyCount = Math.min(freeZoneSize, usedRange);
  36208. for (var j = 0; j < copyCount; j++) {
  36209. var freeI = firstFreeSlotOffset / s;
  36210. var curI = curMoveOffset / s;
  36211. var moveEl = sortedAll[curI];
  36212. this._moveElement(moveEl, firstFreeSlotOffset);
  36213. var replacedEl = sortedAll[freeI];
  36214. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36215. replacedEl.offset = curMoveOffset;
  36216. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36217. sortedAll[freeI] = moveEl;
  36218. sortedAll[curI] = replacedEl;
  36219. curMoveOffset -= s;
  36220. firstFreeSlotOffset += s;
  36221. }
  36222. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36223. if (freeZoneSize <= usedRange) {
  36224. firstFreeSlotOffset = curMoveOffset + s;
  36225. freeZoneSize = 1 + copyCount;
  36226. }
  36227. else {
  36228. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36229. }
  36230. // as we're about to iterate to the next, the cur becomes the previous...
  36231. prevOffset = curOffset;
  36232. }
  36233. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36234. this._lastUsed = firstFreeSlotOffset - s;
  36235. this._firstFree = firstFreeSlotOffset;
  36236. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36237. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36238. this._allEntries = sortedAll;
  36239. return elementsBuffer;
  36240. };
  36241. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36242. for (var i = 0; i < this._stride; i++) {
  36243. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36244. }
  36245. element.offset = destOffset;
  36246. };
  36247. DynamicFloatArray.prototype._growBuffer = function () {
  36248. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36249. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36250. var newBuffer = new Float32Array(newElCount * this._stride);
  36251. newBuffer.set(this.buffer);
  36252. var curCount = this.totalElementCount;
  36253. var addedCount = newElCount - this.totalElementCount;
  36254. for (var i = 0; i < addedCount; i++) {
  36255. var element = new DynamicFloatArrayElementInfo();
  36256. element.offset = (curCount + i) * this.stride;
  36257. this._allEntries.push(element);
  36258. this._freeEntries[addedCount - i - 1] = element;
  36259. }
  36260. this._firstFree = curCount * this.stride;
  36261. this.buffer = newBuffer;
  36262. };
  36263. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36264. /**
  36265. * Get the total count of entries that can fit in the current buffer
  36266. * @returns the elements count
  36267. */
  36268. get: function () {
  36269. return this._allEntries.length;
  36270. },
  36271. enumerable: true,
  36272. configurable: true
  36273. });
  36274. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36275. /**
  36276. * Get the count of free entries that can still be allocated without resizing the buffer
  36277. * @returns the free elements count
  36278. */
  36279. get: function () {
  36280. return this._freeEntries.length;
  36281. },
  36282. enumerable: true,
  36283. configurable: true
  36284. });
  36285. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36286. /**
  36287. * Get the count of allocated elements
  36288. * @returns the allocated elements count
  36289. */
  36290. get: function () {
  36291. return this._allEntries.length - this._freeEntries.length;
  36292. },
  36293. enumerable: true,
  36294. configurable: true
  36295. });
  36296. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36297. /**
  36298. * Return the size of one element in float
  36299. * @returns the size in float
  36300. */
  36301. get: function () {
  36302. return this._stride;
  36303. },
  36304. enumerable: true,
  36305. configurable: true
  36306. });
  36307. DynamicFloatArray.prototype.sort = function () {
  36308. var _this = this;
  36309. if (!this.compareValueOffset) {
  36310. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36311. }
  36312. var count = this.usedElementCount;
  36313. // Do we have to (re)create the sort table?
  36314. if (!this._sortTable || this._sortTable.length < count) {
  36315. // 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...
  36316. var newCount = Math.min(this.totalElementCount, count * 2);
  36317. this._sortTable = new Array(newCount);
  36318. }
  36319. if (!this._sortedTable || this._sortedTable.length !== count) {
  36320. this._sortedTable = new Array(count);
  36321. }
  36322. // Because, you know...
  36323. this.pack();
  36324. //let stride = this.stride;
  36325. //for (let i = 0; i < count; i++) {
  36326. // let si = this._sortTable[i];
  36327. // if (!si) {
  36328. // si = new SortInfo();
  36329. // this._sortTable[i] = si;
  36330. // }
  36331. // si.entry = this._allEntries[i];
  36332. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36333. // si.swapedOffset = null;
  36334. // this._sortedTable[i] = si;
  36335. //}
  36336. var curOffset = 0;
  36337. var stride = this.stride;
  36338. for (var i = 0; i < count; i++, curOffset += stride) {
  36339. var si = this._sortTable[i];
  36340. if (!si) {
  36341. si = new SortInfo();
  36342. this._sortTable[i] = si;
  36343. }
  36344. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36345. si.offset = curOffset;
  36346. si.swapedOffset = null;
  36347. this._sortedTable[i] = si;
  36348. }
  36349. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36350. if (this.sortingAscending) {
  36351. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36352. }
  36353. else {
  36354. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36355. }
  36356. var swapElements = function (src, dst) {
  36357. for (var i = 0; i < stride; i++) {
  36358. var tps = _this.buffer[dst + i];
  36359. _this.buffer[dst + i] = _this.buffer[src + i];
  36360. _this.buffer[src + i] = tps;
  36361. }
  36362. };
  36363. // 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:
  36364. // 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),
  36365. // and I still want something with a good algorithm complexity.
  36366. // 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,
  36367. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36368. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36369. // 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
  36370. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36371. // 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
  36372. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36373. for (var i = 0; i < count; i++) {
  36374. // Get the element to move
  36375. var sourceSI = this._sortedTable[i];
  36376. var destSI = this._sortTable[i];
  36377. var sourceOff = sourceSI.offset;
  36378. // If the source changed location, find the new one
  36379. if (sourceSI.swapedOffset) {
  36380. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36381. var curSI = sourceSI;
  36382. while (curSI.swapedOffset) {
  36383. curSI = this._sortTable[curSI.swapedOffset / stride];
  36384. }
  36385. // Finally get the right location
  36386. sourceOff = curSI.offset;
  36387. }
  36388. // Tag the element being replaced with its new location
  36389. destSI.swapedOffset = sourceOff;
  36390. // Swap elements (only if needed)
  36391. if (sourceOff !== destSI.offset) {
  36392. swapElements(sourceOff, destSI.offset);
  36393. }
  36394. // Update the offset in the corresponding DFAE
  36395. //sourceSI.entry.offset = destSI.entry.offset;
  36396. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36397. }
  36398. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36399. return true;
  36400. };
  36401. return DynamicFloatArray;
  36402. }());
  36403. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36404. var SortInfo = (function () {
  36405. function SortInfo() {
  36406. this.compareData = this.offset = this.swapedOffset = null;
  36407. }
  36408. return SortInfo;
  36409. }());
  36410. })(BABYLON || (BABYLON = {}));
  36411. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  36412. var BABYLON;
  36413. (function (BABYLON) {
  36414. var Condition = (function () {
  36415. function Condition(actionManager) {
  36416. this._actionManager = actionManager;
  36417. }
  36418. Condition.prototype.isValid = function () {
  36419. return true;
  36420. };
  36421. Condition.prototype._getProperty = function (propertyPath) {
  36422. return this._actionManager._getProperty(propertyPath);
  36423. };
  36424. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36425. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36426. };
  36427. Condition.prototype.serialize = function () {
  36428. };
  36429. Condition.prototype._serialize = function (serializedCondition) {
  36430. return {
  36431. type: 2,
  36432. children: [],
  36433. name: serializedCondition.name,
  36434. properties: serializedCondition.properties
  36435. };
  36436. };
  36437. return Condition;
  36438. }());
  36439. BABYLON.Condition = Condition;
  36440. var ValueCondition = (function (_super) {
  36441. __extends(ValueCondition, _super);
  36442. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36443. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36444. var _this = _super.call(this, actionManager) || this;
  36445. _this.propertyPath = propertyPath;
  36446. _this.value = value;
  36447. _this.operator = operator;
  36448. _this._target = target;
  36449. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36450. _this._property = _this._getProperty(_this.propertyPath);
  36451. return _this;
  36452. }
  36453. Object.defineProperty(ValueCondition, "IsEqual", {
  36454. get: function () {
  36455. return ValueCondition._IsEqual;
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. Object.defineProperty(ValueCondition, "IsDifferent", {
  36461. get: function () {
  36462. return ValueCondition._IsDifferent;
  36463. },
  36464. enumerable: true,
  36465. configurable: true
  36466. });
  36467. Object.defineProperty(ValueCondition, "IsGreater", {
  36468. get: function () {
  36469. return ValueCondition._IsGreater;
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(ValueCondition, "IsLesser", {
  36475. get: function () {
  36476. return ValueCondition._IsLesser;
  36477. },
  36478. enumerable: true,
  36479. configurable: true
  36480. });
  36481. // Methods
  36482. ValueCondition.prototype.isValid = function () {
  36483. switch (this.operator) {
  36484. case ValueCondition.IsGreater:
  36485. return this._effectiveTarget[this._property] > this.value;
  36486. case ValueCondition.IsLesser:
  36487. return this._effectiveTarget[this._property] < this.value;
  36488. case ValueCondition.IsEqual:
  36489. case ValueCondition.IsDifferent:
  36490. var check;
  36491. if (this.value.equals) {
  36492. check = this.value.equals(this._effectiveTarget[this._property]);
  36493. }
  36494. else {
  36495. check = this.value === this._effectiveTarget[this._property];
  36496. }
  36497. return this.operator === ValueCondition.IsEqual ? check : !check;
  36498. }
  36499. return false;
  36500. };
  36501. ValueCondition.prototype.serialize = function () {
  36502. return this._serialize({
  36503. name: "ValueCondition",
  36504. properties: [
  36505. BABYLON.Action._GetTargetProperty(this._target),
  36506. { name: "propertyPath", value: this.propertyPath },
  36507. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36508. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36509. ]
  36510. });
  36511. };
  36512. ValueCondition.GetOperatorName = function (operator) {
  36513. switch (operator) {
  36514. case ValueCondition._IsEqual: return "IsEqual";
  36515. case ValueCondition._IsDifferent: return "IsDifferent";
  36516. case ValueCondition._IsGreater: return "IsGreater";
  36517. case ValueCondition._IsLesser: return "IsLesser";
  36518. default: return "";
  36519. }
  36520. };
  36521. return ValueCondition;
  36522. }(Condition));
  36523. // Statics
  36524. ValueCondition._IsEqual = 0;
  36525. ValueCondition._IsDifferent = 1;
  36526. ValueCondition._IsGreater = 2;
  36527. ValueCondition._IsLesser = 3;
  36528. BABYLON.ValueCondition = ValueCondition;
  36529. var PredicateCondition = (function (_super) {
  36530. __extends(PredicateCondition, _super);
  36531. function PredicateCondition(actionManager, predicate) {
  36532. var _this = _super.call(this, actionManager) || this;
  36533. _this.predicate = predicate;
  36534. return _this;
  36535. }
  36536. PredicateCondition.prototype.isValid = function () {
  36537. return this.predicate();
  36538. };
  36539. return PredicateCondition;
  36540. }(Condition));
  36541. BABYLON.PredicateCondition = PredicateCondition;
  36542. var StateCondition = (function (_super) {
  36543. __extends(StateCondition, _super);
  36544. function StateCondition(actionManager, target, value) {
  36545. var _this = _super.call(this, actionManager) || this;
  36546. _this.value = value;
  36547. _this._target = target;
  36548. return _this;
  36549. }
  36550. // Methods
  36551. StateCondition.prototype.isValid = function () {
  36552. return this._target.state === this.value;
  36553. };
  36554. StateCondition.prototype.serialize = function () {
  36555. return this._serialize({
  36556. name: "StateCondition",
  36557. properties: [
  36558. BABYLON.Action._GetTargetProperty(this._target),
  36559. { name: "value", value: this.value }
  36560. ]
  36561. });
  36562. };
  36563. return StateCondition;
  36564. }(Condition));
  36565. BABYLON.StateCondition = StateCondition;
  36566. })(BABYLON || (BABYLON = {}));
  36567. //# sourceMappingURL=babylon.condition.js.map
  36568. var BABYLON;
  36569. (function (BABYLON) {
  36570. var Action = (function () {
  36571. function Action(triggerOptions, condition) {
  36572. this.triggerOptions = triggerOptions;
  36573. if (triggerOptions.parameter) {
  36574. this.trigger = triggerOptions.trigger;
  36575. this._triggerParameter = triggerOptions.parameter;
  36576. }
  36577. else {
  36578. this.trigger = triggerOptions;
  36579. }
  36580. this._nextActiveAction = this;
  36581. this._condition = condition;
  36582. }
  36583. // Methods
  36584. Action.prototype._prepare = function () {
  36585. };
  36586. Action.prototype.getTriggerParameter = function () {
  36587. return this._triggerParameter;
  36588. };
  36589. Action.prototype._executeCurrent = function (evt) {
  36590. if (this._nextActiveAction._condition) {
  36591. var condition = this._nextActiveAction._condition;
  36592. var currentRenderId = this._actionManager.getScene().getRenderId();
  36593. // We cache the current evaluation for the current frame
  36594. if (condition._evaluationId === currentRenderId) {
  36595. if (!condition._currentResult) {
  36596. return;
  36597. }
  36598. }
  36599. else {
  36600. condition._evaluationId = currentRenderId;
  36601. if (!condition.isValid()) {
  36602. condition._currentResult = false;
  36603. return;
  36604. }
  36605. condition._currentResult = true;
  36606. }
  36607. }
  36608. this._nextActiveAction.execute(evt);
  36609. this.skipToNextActiveAction();
  36610. };
  36611. Action.prototype.execute = function (evt) {
  36612. };
  36613. Action.prototype.skipToNextActiveAction = function () {
  36614. if (this._nextActiveAction._child) {
  36615. if (!this._nextActiveAction._child._actionManager) {
  36616. this._nextActiveAction._child._actionManager = this._actionManager;
  36617. }
  36618. this._nextActiveAction = this._nextActiveAction._child;
  36619. }
  36620. else {
  36621. this._nextActiveAction = this;
  36622. }
  36623. };
  36624. Action.prototype.then = function (action) {
  36625. this._child = action;
  36626. action._actionManager = this._actionManager;
  36627. action._prepare();
  36628. return action;
  36629. };
  36630. Action.prototype._getProperty = function (propertyPath) {
  36631. return this._actionManager._getProperty(propertyPath);
  36632. };
  36633. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36634. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36635. };
  36636. Action.prototype.serialize = function (parent) {
  36637. };
  36638. // Called by BABYLON.Action objects in serialize(...). Internal use
  36639. Action.prototype._serialize = function (serializedAction, parent) {
  36640. var serializationObject = {
  36641. type: 1,
  36642. children: [],
  36643. name: serializedAction.name,
  36644. properties: serializedAction.properties || []
  36645. };
  36646. // Serialize child
  36647. if (this._child) {
  36648. this._child.serialize(serializationObject);
  36649. }
  36650. // Check if "this" has a condition
  36651. if (this._condition) {
  36652. var serializedCondition = this._condition.serialize();
  36653. serializedCondition.children.push(serializationObject);
  36654. if (parent) {
  36655. parent.children.push(serializedCondition);
  36656. }
  36657. return serializedCondition;
  36658. }
  36659. if (parent) {
  36660. parent.children.push(serializationObject);
  36661. }
  36662. return serializationObject;
  36663. };
  36664. return Action;
  36665. }());
  36666. Action._SerializeValueAsString = function (value) {
  36667. if (typeof value === "number") {
  36668. return value.toString();
  36669. }
  36670. if (typeof value === "boolean") {
  36671. return value ? "true" : "false";
  36672. }
  36673. if (value instanceof BABYLON.Vector2) {
  36674. return value.x + ", " + value.y;
  36675. }
  36676. if (value instanceof BABYLON.Vector3) {
  36677. return value.x + ", " + value.y + ", " + value.z;
  36678. }
  36679. if (value instanceof BABYLON.Color3) {
  36680. return value.r + ", " + value.g + ", " + value.b;
  36681. }
  36682. if (value instanceof BABYLON.Color4) {
  36683. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36684. }
  36685. return value; // string
  36686. };
  36687. Action._GetTargetProperty = function (target) {
  36688. return {
  36689. name: "target",
  36690. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36691. : target instanceof BABYLON.Light ? "LightProperties"
  36692. : target instanceof BABYLON.Camera ? "CameraProperties"
  36693. : "SceneProperties",
  36694. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36695. };
  36696. };
  36697. BABYLON.Action = Action;
  36698. })(BABYLON || (BABYLON = {}));
  36699. //# sourceMappingURL=babylon.action.js.map
  36700. var BABYLON;
  36701. (function (BABYLON) {
  36702. /**
  36703. * ActionEvent is the event beint sent when an action is triggered.
  36704. */
  36705. var ActionEvent = (function () {
  36706. /**
  36707. * @constructor
  36708. * @param source The mesh or sprite that triggered the action.
  36709. * @param pointerX The X mouse cursor position at the time of the event
  36710. * @param pointerY The Y mouse cursor position at the time of the event
  36711. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36712. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36713. */
  36714. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36715. this.source = source;
  36716. this.pointerX = pointerX;
  36717. this.pointerY = pointerY;
  36718. this.meshUnderPointer = meshUnderPointer;
  36719. this.sourceEvent = sourceEvent;
  36720. this.additionalData = additionalData;
  36721. }
  36722. /**
  36723. * Helper function to auto-create an ActionEvent from a source mesh.
  36724. * @param source The source mesh that triggered the event
  36725. * @param evt {Event} The original (browser) event
  36726. */
  36727. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36728. var scene = source.getScene();
  36729. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36730. };
  36731. /**
  36732. * Helper function to auto-create an ActionEvent from a source mesh.
  36733. * @param source The source sprite that triggered the event
  36734. * @param scene Scene associated with the sprite
  36735. * @param evt {Event} The original (browser) event
  36736. */
  36737. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36738. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36739. };
  36740. /**
  36741. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36742. * @param scene the scene where the event occurred
  36743. * @param evt {Event} The original (browser) event
  36744. */
  36745. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36746. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36747. };
  36748. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36749. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36750. };
  36751. return ActionEvent;
  36752. }());
  36753. BABYLON.ActionEvent = ActionEvent;
  36754. /**
  36755. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36756. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36757. */
  36758. var ActionManager = (function () {
  36759. function ActionManager(scene) {
  36760. // Members
  36761. this.actions = new Array();
  36762. this.hoverCursor = '';
  36763. this._scene = scene;
  36764. scene._actionManagers.push(this);
  36765. }
  36766. Object.defineProperty(ActionManager, "NothingTrigger", {
  36767. get: function () {
  36768. return ActionManager._NothingTrigger;
  36769. },
  36770. enumerable: true,
  36771. configurable: true
  36772. });
  36773. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36774. get: function () {
  36775. return ActionManager._OnPickTrigger;
  36776. },
  36777. enumerable: true,
  36778. configurable: true
  36779. });
  36780. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36781. get: function () {
  36782. return ActionManager._OnLeftPickTrigger;
  36783. },
  36784. enumerable: true,
  36785. configurable: true
  36786. });
  36787. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36788. get: function () {
  36789. return ActionManager._OnRightPickTrigger;
  36790. },
  36791. enumerable: true,
  36792. configurable: true
  36793. });
  36794. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36795. get: function () {
  36796. return ActionManager._OnCenterPickTrigger;
  36797. },
  36798. enumerable: true,
  36799. configurable: true
  36800. });
  36801. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36802. get: function () {
  36803. return ActionManager._OnPickDownTrigger;
  36804. },
  36805. enumerable: true,
  36806. configurable: true
  36807. });
  36808. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  36809. get: function () {
  36810. return ActionManager._OnDoublePickTrigger;
  36811. },
  36812. enumerable: true,
  36813. configurable: true
  36814. });
  36815. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36816. get: function () {
  36817. return ActionManager._OnPickUpTrigger;
  36818. },
  36819. enumerable: true,
  36820. configurable: true
  36821. });
  36822. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36823. /// This trigger will only be raised if you also declared a OnPickDown
  36824. get: function () {
  36825. return ActionManager._OnPickOutTrigger;
  36826. },
  36827. enumerable: true,
  36828. configurable: true
  36829. });
  36830. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36831. get: function () {
  36832. return ActionManager._OnLongPressTrigger;
  36833. },
  36834. enumerable: true,
  36835. configurable: true
  36836. });
  36837. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36838. get: function () {
  36839. return ActionManager._OnPointerOverTrigger;
  36840. },
  36841. enumerable: true,
  36842. configurable: true
  36843. });
  36844. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36845. get: function () {
  36846. return ActionManager._OnPointerOutTrigger;
  36847. },
  36848. enumerable: true,
  36849. configurable: true
  36850. });
  36851. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36852. get: function () {
  36853. return ActionManager._OnEveryFrameTrigger;
  36854. },
  36855. enumerable: true,
  36856. configurable: true
  36857. });
  36858. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36859. get: function () {
  36860. return ActionManager._OnIntersectionEnterTrigger;
  36861. },
  36862. enumerable: true,
  36863. configurable: true
  36864. });
  36865. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36866. get: function () {
  36867. return ActionManager._OnIntersectionExitTrigger;
  36868. },
  36869. enumerable: true,
  36870. configurable: true
  36871. });
  36872. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36873. get: function () {
  36874. return ActionManager._OnKeyDownTrigger;
  36875. },
  36876. enumerable: true,
  36877. configurable: true
  36878. });
  36879. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36880. get: function () {
  36881. return ActionManager._OnKeyUpTrigger;
  36882. },
  36883. enumerable: true,
  36884. configurable: true
  36885. });
  36886. // Methods
  36887. ActionManager.prototype.dispose = function () {
  36888. var index = this._scene._actionManagers.indexOf(this);
  36889. for (var i = 0; i < this.actions.length; i++) {
  36890. var action = this.actions[i];
  36891. ActionManager.Triggers[action.trigger]--;
  36892. if (ActionManager.Triggers[action.trigger] === 0) {
  36893. delete ActionManager.Triggers[action.trigger];
  36894. }
  36895. }
  36896. if (index > -1) {
  36897. this._scene._actionManagers.splice(index, 1);
  36898. }
  36899. };
  36900. ActionManager.prototype.getScene = function () {
  36901. return this._scene;
  36902. };
  36903. /**
  36904. * Does this action manager handles actions of any of the given triggers
  36905. * @param {number[]} triggers - the triggers to be tested
  36906. * @return {boolean} whether one (or more) of the triggers is handeled
  36907. */
  36908. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36909. for (var index = 0; index < this.actions.length; index++) {
  36910. var action = this.actions[index];
  36911. if (triggers.indexOf(action.trigger) > -1) {
  36912. return true;
  36913. }
  36914. }
  36915. return false;
  36916. };
  36917. /**
  36918. * Does this action manager handles actions of a given trigger
  36919. * @param {number} trigger - the trigger to be tested
  36920. * @return {boolean} whether the trigger is handeled
  36921. */
  36922. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36923. for (var index = 0; index < this.actions.length; index++) {
  36924. var action = this.actions[index];
  36925. if (action.trigger === trigger) {
  36926. return true;
  36927. }
  36928. }
  36929. return false;
  36930. };
  36931. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36932. /**
  36933. * Does this action manager has pointer triggers
  36934. * @return {boolean} whether or not it has pointer triggers
  36935. */
  36936. get: function () {
  36937. for (var index = 0; index < this.actions.length; index++) {
  36938. var action = this.actions[index];
  36939. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36940. return true;
  36941. }
  36942. }
  36943. return false;
  36944. },
  36945. enumerable: true,
  36946. configurable: true
  36947. });
  36948. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36949. /**
  36950. * Does this action manager has pick triggers
  36951. * @return {boolean} whether or not it has pick triggers
  36952. */
  36953. get: function () {
  36954. for (var index = 0; index < this.actions.length; index++) {
  36955. var action = this.actions[index];
  36956. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36957. return true;
  36958. }
  36959. }
  36960. return false;
  36961. },
  36962. enumerable: true,
  36963. configurable: true
  36964. });
  36965. Object.defineProperty(ActionManager, "HasTriggers", {
  36966. /**
  36967. * Does exist one action manager with at least one trigger
  36968. * @return {boolean} whether or not it exists one action manager with one trigger
  36969. **/
  36970. get: function () {
  36971. for (var t in ActionManager.Triggers) {
  36972. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36973. return true;
  36974. }
  36975. }
  36976. return false;
  36977. },
  36978. enumerable: true,
  36979. configurable: true
  36980. });
  36981. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36982. /**
  36983. * Does exist one action manager with at least one pick trigger
  36984. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36985. **/
  36986. get: function () {
  36987. for (var t in ActionManager.Triggers) {
  36988. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36989. var t_int = parseInt(t);
  36990. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36991. return true;
  36992. }
  36993. }
  36994. }
  36995. return false;
  36996. },
  36997. enumerable: true,
  36998. configurable: true
  36999. });
  37000. /**
  37001. * Does exist one action manager that handles actions of a given trigger
  37002. * @param {number} trigger - the trigger to be tested
  37003. * @return {boolean} whether the trigger is handeled by at least one action manager
  37004. **/
  37005. ActionManager.HasSpecificTrigger = function (trigger) {
  37006. for (var t in ActionManager.Triggers) {
  37007. if (ActionManager.Triggers.hasOwnProperty(t)) {
  37008. var t_int = parseInt(t);
  37009. if (t_int === trigger) {
  37010. return true;
  37011. }
  37012. }
  37013. }
  37014. return false;
  37015. };
  37016. /**
  37017. * Registers an action to this action manager
  37018. * @param {BABYLON.Action} action - the action to be registered
  37019. * @return {BABYLON.Action} the action amended (prepared) after registration
  37020. */
  37021. ActionManager.prototype.registerAction = function (action) {
  37022. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  37023. if (this.getScene().actionManager !== this) {
  37024. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  37025. return null;
  37026. }
  37027. }
  37028. this.actions.push(action);
  37029. if (ActionManager.Triggers[action.trigger]) {
  37030. ActionManager.Triggers[action.trigger]++;
  37031. }
  37032. else {
  37033. ActionManager.Triggers[action.trigger] = 1;
  37034. }
  37035. action._actionManager = this;
  37036. action._prepare();
  37037. return action;
  37038. };
  37039. /**
  37040. * Process a specific trigger
  37041. * @param {number} trigger - the trigger to process
  37042. * @param evt {BABYLON.ActionEvent} the event details to be processed
  37043. */
  37044. ActionManager.prototype.processTrigger = function (trigger, evt) {
  37045. for (var index = 0; index < this.actions.length; index++) {
  37046. var action = this.actions[index];
  37047. if (action.trigger === trigger) {
  37048. if (trigger === ActionManager.OnKeyUpTrigger
  37049. || trigger === ActionManager.OnKeyDownTrigger) {
  37050. var parameter = action.getTriggerParameter();
  37051. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  37052. if (!parameter.toLowerCase) {
  37053. continue;
  37054. }
  37055. var lowerCase = parameter.toLowerCase();
  37056. if (lowerCase !== evt.sourceEvent.key) {
  37057. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  37058. var actualkey = String.fromCharCode(unicode).toLowerCase();
  37059. if (actualkey !== lowerCase) {
  37060. continue;
  37061. }
  37062. }
  37063. }
  37064. }
  37065. action._executeCurrent(evt);
  37066. }
  37067. }
  37068. };
  37069. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  37070. var properties = propertyPath.split(".");
  37071. for (var index = 0; index < properties.length - 1; index++) {
  37072. target = target[properties[index]];
  37073. }
  37074. return target;
  37075. };
  37076. ActionManager.prototype._getProperty = function (propertyPath) {
  37077. var properties = propertyPath.split(".");
  37078. return properties[properties.length - 1];
  37079. };
  37080. ActionManager.prototype.serialize = function (name) {
  37081. var root = {
  37082. children: [],
  37083. name: name,
  37084. type: 3,
  37085. properties: [] // Empty for root but required
  37086. };
  37087. for (var i = 0; i < this.actions.length; i++) {
  37088. var triggerObject = {
  37089. type: 0,
  37090. children: [],
  37091. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  37092. properties: []
  37093. };
  37094. var triggerOptions = this.actions[i].triggerOptions;
  37095. if (triggerOptions && typeof triggerOptions !== "number") {
  37096. if (triggerOptions.parameter instanceof BABYLON.Node) {
  37097. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  37098. }
  37099. else {
  37100. var parameter = {};
  37101. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  37102. if (triggerOptions.parameter.mesh) {
  37103. parameter._meshId = triggerOptions.parameter.mesh.id;
  37104. }
  37105. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  37106. }
  37107. }
  37108. // Serialize child action, recursively
  37109. this.actions[i].serialize(triggerObject);
  37110. // Add serialized trigger
  37111. root.children.push(triggerObject);
  37112. }
  37113. return root;
  37114. };
  37115. ActionManager.Parse = function (parsedActions, object, scene) {
  37116. var actionManager = new BABYLON.ActionManager(scene);
  37117. if (object === null)
  37118. scene.actionManager = actionManager;
  37119. else
  37120. object.actionManager = actionManager;
  37121. // instanciate a new object
  37122. var instanciate = function (name, params) {
  37123. var newInstance = Object.create(BABYLON[name].prototype);
  37124. newInstance.constructor.apply(newInstance, params);
  37125. return newInstance;
  37126. };
  37127. var parseParameter = function (name, value, target, propertyPath) {
  37128. if (propertyPath === null) {
  37129. // String, boolean or float
  37130. var floatValue = parseFloat(value);
  37131. if (value === "true" || value === "false")
  37132. return value === "true";
  37133. else
  37134. return isNaN(floatValue) ? value : floatValue;
  37135. }
  37136. var effectiveTarget = propertyPath.split(".");
  37137. var values = value.split(",");
  37138. // Get effective Target
  37139. for (var i = 0; i < effectiveTarget.length; i++) {
  37140. target = target[effectiveTarget[i]];
  37141. }
  37142. // Return appropriate value with its type
  37143. if (typeof (target) === "boolean")
  37144. return values[0] === "true";
  37145. if (typeof (target) === "string")
  37146. return values[0];
  37147. // Parameters with multiple values such as Vector3 etc.
  37148. var split = new Array();
  37149. for (var i = 0; i < values.length; i++)
  37150. split.push(parseFloat(values[i]));
  37151. if (target instanceof BABYLON.Vector3)
  37152. return BABYLON.Vector3.FromArray(split);
  37153. if (target instanceof BABYLON.Vector4)
  37154. return BABYLON.Vector4.FromArray(split);
  37155. if (target instanceof BABYLON.Color3)
  37156. return BABYLON.Color3.FromArray(split);
  37157. if (target instanceof BABYLON.Color4)
  37158. return BABYLON.Color4.FromArray(split);
  37159. return parseFloat(values[0]);
  37160. };
  37161. // traverse graph per trigger
  37162. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37163. if (combineArray === void 0) { combineArray = null; }
  37164. if (parsedAction.detached)
  37165. return;
  37166. var parameters = new Array();
  37167. var target = null;
  37168. var propertyPath = null;
  37169. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37170. // Parameters
  37171. if (parsedAction.type === 2)
  37172. parameters.push(actionManager);
  37173. else
  37174. parameters.push(trigger);
  37175. if (combine) {
  37176. var actions = new Array();
  37177. for (var j = 0; j < parsedAction.combine.length; j++) {
  37178. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37179. }
  37180. parameters.push(actions);
  37181. }
  37182. else {
  37183. for (var i = 0; i < parsedAction.properties.length; i++) {
  37184. var value = parsedAction.properties[i].value;
  37185. var name = parsedAction.properties[i].name;
  37186. var targetType = parsedAction.properties[i].targetType;
  37187. if (name === "target")
  37188. if (targetType !== null && targetType === "SceneProperties")
  37189. value = target = scene;
  37190. else
  37191. value = target = scene.getNodeByName(value);
  37192. else if (name === "parent")
  37193. value = scene.getNodeByName(value);
  37194. else if (name === "sound")
  37195. value = scene.getSoundByName(value);
  37196. else if (name !== "propertyPath") {
  37197. if (parsedAction.type === 2 && name === "operator")
  37198. value = BABYLON.ValueCondition[value];
  37199. else
  37200. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37201. }
  37202. else {
  37203. propertyPath = value;
  37204. }
  37205. parameters.push(value);
  37206. }
  37207. }
  37208. if (combineArray === null) {
  37209. parameters.push(condition);
  37210. }
  37211. else {
  37212. parameters.push(null);
  37213. }
  37214. // If interpolate value action
  37215. if (parsedAction.name === "InterpolateValueAction") {
  37216. var param = parameters[parameters.length - 2];
  37217. parameters[parameters.length - 1] = param;
  37218. parameters[parameters.length - 2] = condition;
  37219. }
  37220. // Action or condition(s) and not CombineAction
  37221. var newAction = instanciate(parsedAction.name, parameters);
  37222. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37223. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37224. if (action)
  37225. action.then(nothing);
  37226. else
  37227. actionManager.registerAction(nothing);
  37228. action = nothing;
  37229. }
  37230. if (combineArray === null) {
  37231. if (newAction instanceof BABYLON.Condition) {
  37232. condition = newAction;
  37233. newAction = action;
  37234. }
  37235. else {
  37236. condition = null;
  37237. if (action)
  37238. action.then(newAction);
  37239. else
  37240. actionManager.registerAction(newAction);
  37241. }
  37242. }
  37243. else {
  37244. combineArray.push(newAction);
  37245. }
  37246. for (var i = 0; i < parsedAction.children.length; i++)
  37247. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37248. };
  37249. // triggers
  37250. for (var i = 0; i < parsedActions.children.length; i++) {
  37251. var triggerParams;
  37252. var trigger = parsedActions.children[i];
  37253. if (trigger.properties.length > 0) {
  37254. var param = trigger.properties[0].value;
  37255. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37256. if (value._meshId) {
  37257. value.mesh = scene.getMeshByID(value._meshId);
  37258. }
  37259. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37260. }
  37261. else
  37262. triggerParams = BABYLON.ActionManager[trigger.name];
  37263. for (var j = 0; j < trigger.children.length; j++) {
  37264. if (!trigger.detached)
  37265. traverse(trigger.children[j], triggerParams, null, null);
  37266. }
  37267. }
  37268. };
  37269. ActionManager.GetTriggerName = function (trigger) {
  37270. switch (trigger) {
  37271. case 0: return "NothingTrigger";
  37272. case 1: return "OnPickTrigger";
  37273. case 2: return "OnLeftPickTrigger";
  37274. case 3: return "OnRightPickTrigger";
  37275. case 4: return "OnCenterPickTrigger";
  37276. case 5: return "OnPickDownTrigger";
  37277. case 6: return "OnPickUpTrigger";
  37278. case 7: return "OnLongPressTrigger";
  37279. case 8: return "OnPointerOverTrigger";
  37280. case 9: return "OnPointerOutTrigger";
  37281. case 10: return "OnEveryFrameTrigger";
  37282. case 11: return "OnIntersectionEnterTrigger";
  37283. case 12: return "OnIntersectionExitTrigger";
  37284. case 13: return "OnKeyDownTrigger";
  37285. case 14: return "OnKeyUpTrigger";
  37286. case 15: return "OnPickOutTrigger";
  37287. default: return "";
  37288. }
  37289. };
  37290. return ActionManager;
  37291. }());
  37292. // Statics
  37293. ActionManager._NothingTrigger = 0;
  37294. ActionManager._OnPickTrigger = 1;
  37295. ActionManager._OnLeftPickTrigger = 2;
  37296. ActionManager._OnRightPickTrigger = 3;
  37297. ActionManager._OnCenterPickTrigger = 4;
  37298. ActionManager._OnPickDownTrigger = 5;
  37299. ActionManager._OnDoublePickTrigger = 6;
  37300. ActionManager._OnPickUpTrigger = 7;
  37301. ActionManager._OnLongPressTrigger = 8;
  37302. ActionManager._OnPointerOverTrigger = 9;
  37303. ActionManager._OnPointerOutTrigger = 10;
  37304. ActionManager._OnEveryFrameTrigger = 11;
  37305. ActionManager._OnIntersectionEnterTrigger = 12;
  37306. ActionManager._OnIntersectionExitTrigger = 13;
  37307. ActionManager._OnKeyDownTrigger = 14;
  37308. ActionManager._OnKeyUpTrigger = 15;
  37309. ActionManager._OnPickOutTrigger = 16;
  37310. ActionManager.Triggers = {};
  37311. BABYLON.ActionManager = ActionManager;
  37312. })(BABYLON || (BABYLON = {}));
  37313. //# sourceMappingURL=babylon.actionManager.js.map
  37314. var BABYLON;
  37315. (function (BABYLON) {
  37316. var InterpolateValueAction = (function (_super) {
  37317. __extends(InterpolateValueAction, _super);
  37318. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37319. if (duration === void 0) { duration = 1000; }
  37320. var _this = _super.call(this, triggerOptions, condition) || this;
  37321. _this.propertyPath = propertyPath;
  37322. _this.value = value;
  37323. _this.duration = duration;
  37324. _this.stopOtherAnimations = stopOtherAnimations;
  37325. _this.onInterpolationDone = onInterpolationDone;
  37326. _this._target = _this._effectiveTarget = target;
  37327. return _this;
  37328. }
  37329. InterpolateValueAction.prototype._prepare = function () {
  37330. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37331. this._property = this._getProperty(this.propertyPath);
  37332. };
  37333. InterpolateValueAction.prototype.execute = function () {
  37334. var scene = this._actionManager.getScene();
  37335. var keys = [
  37336. {
  37337. frame: 0,
  37338. value: this._effectiveTarget[this._property]
  37339. }, {
  37340. frame: 100,
  37341. value: this.value
  37342. }
  37343. ];
  37344. var dataType;
  37345. if (typeof this.value === "number") {
  37346. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37347. }
  37348. else if (this.value instanceof BABYLON.Color3) {
  37349. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37350. }
  37351. else if (this.value instanceof BABYLON.Vector3) {
  37352. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37353. }
  37354. else if (this.value instanceof BABYLON.Matrix) {
  37355. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37356. }
  37357. else if (this.value instanceof BABYLON.Quaternion) {
  37358. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37359. }
  37360. else {
  37361. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37362. return;
  37363. }
  37364. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37365. animation.setKeys(keys);
  37366. if (this.stopOtherAnimations) {
  37367. scene.stopAnimation(this._effectiveTarget);
  37368. }
  37369. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37370. };
  37371. InterpolateValueAction.prototype.serialize = function (parent) {
  37372. return _super.prototype._serialize.call(this, {
  37373. name: "InterpolateValueAction",
  37374. properties: [
  37375. BABYLON.Action._GetTargetProperty(this._target),
  37376. { name: "propertyPath", value: this.propertyPath },
  37377. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37378. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37379. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37380. ]
  37381. }, parent);
  37382. };
  37383. return InterpolateValueAction;
  37384. }(BABYLON.Action));
  37385. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37386. })(BABYLON || (BABYLON = {}));
  37387. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37388. var BABYLON;
  37389. (function (BABYLON) {
  37390. var SwitchBooleanAction = (function (_super) {
  37391. __extends(SwitchBooleanAction, _super);
  37392. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37393. var _this = _super.call(this, triggerOptions, condition) || this;
  37394. _this.propertyPath = propertyPath;
  37395. _this._target = _this._effectiveTarget = target;
  37396. return _this;
  37397. }
  37398. SwitchBooleanAction.prototype._prepare = function () {
  37399. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37400. this._property = this._getProperty(this.propertyPath);
  37401. };
  37402. SwitchBooleanAction.prototype.execute = function () {
  37403. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37404. };
  37405. SwitchBooleanAction.prototype.serialize = function (parent) {
  37406. return _super.prototype._serialize.call(this, {
  37407. name: "SwitchBooleanAction",
  37408. properties: [
  37409. BABYLON.Action._GetTargetProperty(this._target),
  37410. { name: "propertyPath", value: this.propertyPath }
  37411. ]
  37412. }, parent);
  37413. };
  37414. return SwitchBooleanAction;
  37415. }(BABYLON.Action));
  37416. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37417. var SetStateAction = (function (_super) {
  37418. __extends(SetStateAction, _super);
  37419. function SetStateAction(triggerOptions, target, value, condition) {
  37420. var _this = _super.call(this, triggerOptions, condition) || this;
  37421. _this.value = value;
  37422. _this._target = target;
  37423. return _this;
  37424. }
  37425. SetStateAction.prototype.execute = function () {
  37426. this._target.state = this.value;
  37427. };
  37428. SetStateAction.prototype.serialize = function (parent) {
  37429. return _super.prototype._serialize.call(this, {
  37430. name: "SetStateAction",
  37431. properties: [
  37432. BABYLON.Action._GetTargetProperty(this._target),
  37433. { name: "value", value: this.value }
  37434. ]
  37435. }, parent);
  37436. };
  37437. return SetStateAction;
  37438. }(BABYLON.Action));
  37439. BABYLON.SetStateAction = SetStateAction;
  37440. var SetValueAction = (function (_super) {
  37441. __extends(SetValueAction, _super);
  37442. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37443. var _this = _super.call(this, triggerOptions, condition) || this;
  37444. _this.propertyPath = propertyPath;
  37445. _this.value = value;
  37446. _this._target = _this._effectiveTarget = target;
  37447. return _this;
  37448. }
  37449. SetValueAction.prototype._prepare = function () {
  37450. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37451. this._property = this._getProperty(this.propertyPath);
  37452. };
  37453. SetValueAction.prototype.execute = function () {
  37454. this._effectiveTarget[this._property] = this.value;
  37455. if (this._target.markAsDirty) {
  37456. this._target.markAsDirty(this._property);
  37457. }
  37458. };
  37459. SetValueAction.prototype.serialize = function (parent) {
  37460. return _super.prototype._serialize.call(this, {
  37461. name: "SetValueAction",
  37462. properties: [
  37463. BABYLON.Action._GetTargetProperty(this._target),
  37464. { name: "propertyPath", value: this.propertyPath },
  37465. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37466. ]
  37467. }, parent);
  37468. };
  37469. return SetValueAction;
  37470. }(BABYLON.Action));
  37471. BABYLON.SetValueAction = SetValueAction;
  37472. var IncrementValueAction = (function (_super) {
  37473. __extends(IncrementValueAction, _super);
  37474. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37475. var _this = _super.call(this, triggerOptions, condition) || this;
  37476. _this.propertyPath = propertyPath;
  37477. _this.value = value;
  37478. _this._target = _this._effectiveTarget = target;
  37479. return _this;
  37480. }
  37481. IncrementValueAction.prototype._prepare = function () {
  37482. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37483. this._property = this._getProperty(this.propertyPath);
  37484. if (typeof this._effectiveTarget[this._property] !== "number") {
  37485. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37486. }
  37487. };
  37488. IncrementValueAction.prototype.execute = function () {
  37489. this._effectiveTarget[this._property] += this.value;
  37490. if (this._target.markAsDirty) {
  37491. this._target.markAsDirty(this._property);
  37492. }
  37493. };
  37494. IncrementValueAction.prototype.serialize = function (parent) {
  37495. return _super.prototype._serialize.call(this, {
  37496. name: "IncrementValueAction",
  37497. properties: [
  37498. BABYLON.Action._GetTargetProperty(this._target),
  37499. { name: "propertyPath", value: this.propertyPath },
  37500. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37501. ]
  37502. }, parent);
  37503. };
  37504. return IncrementValueAction;
  37505. }(BABYLON.Action));
  37506. BABYLON.IncrementValueAction = IncrementValueAction;
  37507. var PlayAnimationAction = (function (_super) {
  37508. __extends(PlayAnimationAction, _super);
  37509. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37510. var _this = _super.call(this, triggerOptions, condition) || this;
  37511. _this.from = from;
  37512. _this.to = to;
  37513. _this.loop = loop;
  37514. _this._target = target;
  37515. return _this;
  37516. }
  37517. PlayAnimationAction.prototype._prepare = function () {
  37518. };
  37519. PlayAnimationAction.prototype.execute = function () {
  37520. var scene = this._actionManager.getScene();
  37521. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37522. };
  37523. PlayAnimationAction.prototype.serialize = function (parent) {
  37524. return _super.prototype._serialize.call(this, {
  37525. name: "PlayAnimationAction",
  37526. properties: [
  37527. BABYLON.Action._GetTargetProperty(this._target),
  37528. { name: "from", value: String(this.from) },
  37529. { name: "to", value: String(this.to) },
  37530. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37531. ]
  37532. }, parent);
  37533. };
  37534. return PlayAnimationAction;
  37535. }(BABYLON.Action));
  37536. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37537. var StopAnimationAction = (function (_super) {
  37538. __extends(StopAnimationAction, _super);
  37539. function StopAnimationAction(triggerOptions, target, condition) {
  37540. var _this = _super.call(this, triggerOptions, condition) || this;
  37541. _this._target = target;
  37542. return _this;
  37543. }
  37544. StopAnimationAction.prototype._prepare = function () {
  37545. };
  37546. StopAnimationAction.prototype.execute = function () {
  37547. var scene = this._actionManager.getScene();
  37548. scene.stopAnimation(this._target);
  37549. };
  37550. StopAnimationAction.prototype.serialize = function (parent) {
  37551. return _super.prototype._serialize.call(this, {
  37552. name: "StopAnimationAction",
  37553. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37554. }, parent);
  37555. };
  37556. return StopAnimationAction;
  37557. }(BABYLON.Action));
  37558. BABYLON.StopAnimationAction = StopAnimationAction;
  37559. var DoNothingAction = (function (_super) {
  37560. __extends(DoNothingAction, _super);
  37561. function DoNothingAction(triggerOptions, condition) {
  37562. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37563. return _super.call(this, triggerOptions, condition) || this;
  37564. }
  37565. DoNothingAction.prototype.execute = function () {
  37566. };
  37567. DoNothingAction.prototype.serialize = function (parent) {
  37568. return _super.prototype._serialize.call(this, {
  37569. name: "DoNothingAction",
  37570. properties: []
  37571. }, parent);
  37572. };
  37573. return DoNothingAction;
  37574. }(BABYLON.Action));
  37575. BABYLON.DoNothingAction = DoNothingAction;
  37576. var CombineAction = (function (_super) {
  37577. __extends(CombineAction, _super);
  37578. function CombineAction(triggerOptions, children, condition) {
  37579. var _this = _super.call(this, triggerOptions, condition) || this;
  37580. _this.children = children;
  37581. return _this;
  37582. }
  37583. CombineAction.prototype._prepare = function () {
  37584. for (var index = 0; index < this.children.length; index++) {
  37585. this.children[index]._actionManager = this._actionManager;
  37586. this.children[index]._prepare();
  37587. }
  37588. };
  37589. CombineAction.prototype.execute = function (evt) {
  37590. for (var index = 0; index < this.children.length; index++) {
  37591. this.children[index].execute(evt);
  37592. }
  37593. };
  37594. CombineAction.prototype.serialize = function (parent) {
  37595. var serializationObject = _super.prototype._serialize.call(this, {
  37596. name: "CombineAction",
  37597. properties: [],
  37598. combine: []
  37599. }, parent);
  37600. for (var i = 0; i < this.children.length; i++) {
  37601. serializationObject.combine.push(this.children[i].serialize(null));
  37602. }
  37603. return serializationObject;
  37604. };
  37605. return CombineAction;
  37606. }(BABYLON.Action));
  37607. BABYLON.CombineAction = CombineAction;
  37608. var ExecuteCodeAction = (function (_super) {
  37609. __extends(ExecuteCodeAction, _super);
  37610. function ExecuteCodeAction(triggerOptions, func, condition) {
  37611. var _this = _super.call(this, triggerOptions, condition) || this;
  37612. _this.func = func;
  37613. return _this;
  37614. }
  37615. ExecuteCodeAction.prototype.execute = function (evt) {
  37616. this.func(evt);
  37617. };
  37618. return ExecuteCodeAction;
  37619. }(BABYLON.Action));
  37620. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37621. var SetParentAction = (function (_super) {
  37622. __extends(SetParentAction, _super);
  37623. function SetParentAction(triggerOptions, target, parent, condition) {
  37624. var _this = _super.call(this, triggerOptions, condition) || this;
  37625. _this._target = target;
  37626. _this._parent = parent;
  37627. return _this;
  37628. }
  37629. SetParentAction.prototype._prepare = function () {
  37630. };
  37631. SetParentAction.prototype.execute = function () {
  37632. if (this._target.parent === this._parent) {
  37633. return;
  37634. }
  37635. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37636. invertParentWorldMatrix.invert();
  37637. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37638. this._target.parent = this._parent;
  37639. };
  37640. SetParentAction.prototype.serialize = function (parent) {
  37641. return _super.prototype._serialize.call(this, {
  37642. name: "SetParentAction",
  37643. properties: [
  37644. BABYLON.Action._GetTargetProperty(this._target),
  37645. BABYLON.Action._GetTargetProperty(this._parent),
  37646. ]
  37647. }, parent);
  37648. };
  37649. return SetParentAction;
  37650. }(BABYLON.Action));
  37651. BABYLON.SetParentAction = SetParentAction;
  37652. var PlaySoundAction = (function (_super) {
  37653. __extends(PlaySoundAction, _super);
  37654. function PlaySoundAction(triggerOptions, sound, condition) {
  37655. var _this = _super.call(this, triggerOptions, condition) || this;
  37656. _this._sound = sound;
  37657. return _this;
  37658. }
  37659. PlaySoundAction.prototype._prepare = function () {
  37660. };
  37661. PlaySoundAction.prototype.execute = function () {
  37662. if (this._sound !== undefined)
  37663. this._sound.play();
  37664. };
  37665. PlaySoundAction.prototype.serialize = function (parent) {
  37666. return _super.prototype._serialize.call(this, {
  37667. name: "PlaySoundAction",
  37668. properties: [{ name: "sound", value: this._sound.name }]
  37669. }, parent);
  37670. };
  37671. return PlaySoundAction;
  37672. }(BABYLON.Action));
  37673. BABYLON.PlaySoundAction = PlaySoundAction;
  37674. var StopSoundAction = (function (_super) {
  37675. __extends(StopSoundAction, _super);
  37676. function StopSoundAction(triggerOptions, sound, condition) {
  37677. var _this = _super.call(this, triggerOptions, condition) || this;
  37678. _this._sound = sound;
  37679. return _this;
  37680. }
  37681. StopSoundAction.prototype._prepare = function () {
  37682. };
  37683. StopSoundAction.prototype.execute = function () {
  37684. if (this._sound !== undefined)
  37685. this._sound.stop();
  37686. };
  37687. StopSoundAction.prototype.serialize = function (parent) {
  37688. return _super.prototype._serialize.call(this, {
  37689. name: "StopSoundAction",
  37690. properties: [{ name: "sound", value: this._sound.name }]
  37691. }, parent);
  37692. };
  37693. return StopSoundAction;
  37694. }(BABYLON.Action));
  37695. BABYLON.StopSoundAction = StopSoundAction;
  37696. })(BABYLON || (BABYLON = {}));
  37697. //# sourceMappingURL=babylon.directActions.js.map
  37698. var BABYLON;
  37699. (function (BABYLON) {
  37700. var Debug;
  37701. (function (Debug) {
  37702. /**
  37703. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  37704. */
  37705. var SkeletonViewer = (function () {
  37706. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  37707. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  37708. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  37709. this.skeleton = skeleton;
  37710. this.mesh = mesh;
  37711. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  37712. this.renderingGroupId = renderingGroupId;
  37713. this.color = BABYLON.Color3.White();
  37714. this._debugLines = [];
  37715. this._isEnabled = false;
  37716. this._scene = scene;
  37717. this.update();
  37718. this._renderFunction = this.update.bind(this);
  37719. }
  37720. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  37721. get: function () {
  37722. return this._isEnabled;
  37723. },
  37724. set: function (value) {
  37725. if (this._isEnabled === value) {
  37726. return;
  37727. }
  37728. this._isEnabled = value;
  37729. if (value) {
  37730. this._scene.registerBeforeRender(this._renderFunction);
  37731. }
  37732. else {
  37733. this._scene.unregisterBeforeRender(this._renderFunction);
  37734. }
  37735. },
  37736. enumerable: true,
  37737. configurable: true
  37738. });
  37739. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  37740. if (x === void 0) { x = 0; }
  37741. if (y === void 0) { y = 0; }
  37742. if (z === void 0) { z = 0; }
  37743. var tmat = BABYLON.Tmp.Matrix[0];
  37744. var parentBone = bone.getParent();
  37745. tmat.copyFrom(bone.getLocalMatrix());
  37746. if (x !== 0 || y !== 0 || z !== 0) {
  37747. var tmat2 = BABYLON.Tmp.Matrix[1];
  37748. BABYLON.Matrix.IdentityToRef(tmat2);
  37749. tmat2.m[12] = x;
  37750. tmat2.m[13] = y;
  37751. tmat2.m[14] = z;
  37752. tmat2.multiplyToRef(tmat, tmat);
  37753. }
  37754. if (parentBone) {
  37755. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  37756. }
  37757. tmat.multiplyToRef(meshMat, tmat);
  37758. position.x = tmat.m[12];
  37759. position.y = tmat.m[13];
  37760. position.z = tmat.m[14];
  37761. };
  37762. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  37763. var len = bones.length;
  37764. var meshPos = this.mesh.position;
  37765. for (var i = 0; i < len; i++) {
  37766. var bone = bones[i];
  37767. var points = this._debugLines[i];
  37768. if (!points) {
  37769. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37770. this._debugLines[i] = points;
  37771. }
  37772. this._getBonePosition(points[0], bone, meshMat);
  37773. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  37774. points[0].subtractInPlace(meshPos);
  37775. points[1].subtractInPlace(meshPos);
  37776. }
  37777. };
  37778. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  37779. var len = bones.length;
  37780. var boneNum = 0;
  37781. var meshPos = this.mesh.position;
  37782. for (var i = len - 1; i >= 0; i--) {
  37783. var childBone = bones[i];
  37784. var parentBone = childBone.getParent();
  37785. if (!parentBone) {
  37786. continue;
  37787. }
  37788. var points = this._debugLines[boneNum];
  37789. if (!points) {
  37790. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37791. this._debugLines[boneNum] = points;
  37792. }
  37793. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  37794. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  37795. points[0].subtractInPlace(meshPos);
  37796. points[1].subtractInPlace(meshPos);
  37797. boneNum++;
  37798. }
  37799. };
  37800. SkeletonViewer.prototype.update = function () {
  37801. if (this.autoUpdateBonesMatrices) {
  37802. this.skeleton.computeAbsoluteTransforms();
  37803. }
  37804. if (this.skeleton.bones[0].length === undefined) {
  37805. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37806. }
  37807. else {
  37808. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37809. }
  37810. if (!this._debugMesh) {
  37811. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  37812. this._debugMesh.renderingGroupId = this.renderingGroupId;
  37813. }
  37814. else {
  37815. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  37816. }
  37817. this._debugMesh.position.copyFrom(this.mesh.position);
  37818. this._debugMesh.color = this.color;
  37819. };
  37820. SkeletonViewer.prototype.dispose = function () {
  37821. if (this._debugMesh) {
  37822. this.isEnabled = false;
  37823. this._debugMesh.dispose();
  37824. this._debugMesh = null;
  37825. }
  37826. };
  37827. return SkeletonViewer;
  37828. }());
  37829. Debug.SkeletonViewer = SkeletonViewer;
  37830. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37831. })(BABYLON || (BABYLON = {}));
  37832. //# sourceMappingURL=babylon.skeletonViewer.js.map
  37833. var BABYLON;
  37834. (function (BABYLON) {
  37835. var Debug;
  37836. (function (Debug) {
  37837. var AxesViewer = (function () {
  37838. function AxesViewer(scene, scaleLines) {
  37839. if (scaleLines === void 0) { scaleLines = 1; }
  37840. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37841. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37842. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37843. this.scaleLines = 1;
  37844. this.scaleLines = scaleLines;
  37845. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  37846. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  37847. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  37848. this._xmesh.renderingGroupId = 2;
  37849. this._ymesh.renderingGroupId = 2;
  37850. this._zmesh.renderingGroupId = 2;
  37851. this._xmesh.material.checkReadyOnlyOnce = true;
  37852. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  37853. this._ymesh.material.checkReadyOnlyOnce = true;
  37854. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  37855. this._zmesh.material.checkReadyOnlyOnce = true;
  37856. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  37857. this.scene = scene;
  37858. }
  37859. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  37860. var scaleLines = this.scaleLines;
  37861. this._xmesh.position.copyFrom(position);
  37862. this._ymesh.position.copyFrom(position);
  37863. this._zmesh.position.copyFrom(position);
  37864. var point2 = this._xline[1];
  37865. point2.x = xaxis.x * scaleLines;
  37866. point2.y = xaxis.y * scaleLines;
  37867. point2.z = xaxis.z * scaleLines;
  37868. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  37869. point2 = this._yline[1];
  37870. point2.x = yaxis.x * scaleLines;
  37871. point2.y = yaxis.y * scaleLines;
  37872. point2.z = yaxis.z * scaleLines;
  37873. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  37874. point2 = this._zline[1];
  37875. point2.x = zaxis.x * scaleLines;
  37876. point2.y = zaxis.y * scaleLines;
  37877. point2.z = zaxis.z * scaleLines;
  37878. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  37879. };
  37880. AxesViewer.prototype.dispose = function () {
  37881. if (this._xmesh) {
  37882. this._xmesh.dispose();
  37883. this._ymesh.dispose();
  37884. this._zmesh.dispose();
  37885. this._xmesh = null;
  37886. this._ymesh = null;
  37887. this._zmesh = null;
  37888. this._xline = null;
  37889. this._yline = null;
  37890. this._zline = null;
  37891. this.scene = null;
  37892. }
  37893. };
  37894. return AxesViewer;
  37895. }());
  37896. Debug.AxesViewer = AxesViewer;
  37897. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37898. })(BABYLON || (BABYLON = {}));
  37899. //# sourceMappingURL=babylon.axesViewer.js.map
  37900. var BABYLON;
  37901. (function (BABYLON) {
  37902. var Debug;
  37903. (function (Debug) {
  37904. var BoneAxesViewer = (function (_super) {
  37905. __extends(BoneAxesViewer, _super);
  37906. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  37907. if (scaleLines === void 0) { scaleLines = 1; }
  37908. var _this = _super.call(this, scene, scaleLines) || this;
  37909. _this.pos = BABYLON.Vector3.Zero();
  37910. _this.xaxis = BABYLON.Vector3.Zero();
  37911. _this.yaxis = BABYLON.Vector3.Zero();
  37912. _this.zaxis = BABYLON.Vector3.Zero();
  37913. _this.mesh = mesh;
  37914. _this.bone = bone;
  37915. return _this;
  37916. }
  37917. BoneAxesViewer.prototype.update = function () {
  37918. var bone = this.bone;
  37919. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  37920. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  37921. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  37922. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  37923. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  37924. };
  37925. BoneAxesViewer.prototype.dispose = function () {
  37926. if (this.pos) {
  37927. this.pos = null;
  37928. this.xaxis = null;
  37929. this.yaxis = null;
  37930. this.zaxis = null;
  37931. this.mesh = null;
  37932. this.bone = null;
  37933. _super.prototype.dispose.call(this);
  37934. }
  37935. };
  37936. return BoneAxesViewer;
  37937. }(Debug.AxesViewer));
  37938. Debug.BoneAxesViewer = BoneAxesViewer;
  37939. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37940. })(BABYLON || (BABYLON = {}));
  37941. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  37942. var BABYLON;
  37943. (function (BABYLON) {
  37944. var RayHelper = (function () {
  37945. function RayHelper(ray) {
  37946. this.ray = ray;
  37947. }
  37948. RayHelper.CreateAndShow = function (ray, scene, color) {
  37949. var helper = new RayHelper(ray);
  37950. helper.show(scene, color);
  37951. return helper;
  37952. };
  37953. RayHelper.prototype.show = function (scene, color) {
  37954. if (!this._renderFunction) {
  37955. var ray = this.ray;
  37956. this._renderFunction = this._render.bind(this);
  37957. this._scene = scene;
  37958. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  37959. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  37960. this._scene.registerBeforeRender(this._renderFunction);
  37961. }
  37962. if (color) {
  37963. this._renderLine.color.copyFrom(color);
  37964. }
  37965. };
  37966. RayHelper.prototype.hide = function () {
  37967. if (this._renderFunction) {
  37968. this._scene.unregisterBeforeRender(this._renderFunction);
  37969. this._scene = null;
  37970. this._renderFunction = null;
  37971. this._renderLine.dispose();
  37972. this._renderLine = null;
  37973. this._renderPoints = null;
  37974. }
  37975. };
  37976. RayHelper.prototype._render = function () {
  37977. var ray = this.ray;
  37978. var point = this._renderPoints[1];
  37979. var len = Math.min(ray.length, 1000000);
  37980. point.copyFrom(ray.direction);
  37981. point.scaleInPlace(len);
  37982. point.addInPlace(ray.origin);
  37983. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  37984. };
  37985. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  37986. this._attachedToMesh = mesh;
  37987. var ray = this.ray;
  37988. if (!ray.direction) {
  37989. ray.direction = BABYLON.Vector3.Zero();
  37990. }
  37991. if (!ray.origin) {
  37992. ray.origin = BABYLON.Vector3.Zero();
  37993. }
  37994. if (length) {
  37995. ray.length = length;
  37996. }
  37997. if (!meshSpaceOrigin) {
  37998. meshSpaceOrigin = BABYLON.Vector3.Zero();
  37999. }
  38000. if (!meshSpaceDirection) {
  38001. // -1 so that this will work with Mesh.lookAt
  38002. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  38003. }
  38004. if (!this._meshSpaceDirection) {
  38005. this._meshSpaceDirection = meshSpaceDirection.clone();
  38006. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  38007. }
  38008. else {
  38009. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  38010. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  38011. }
  38012. if (!this._updateToMeshFunction) {
  38013. this._updateToMeshFunction = this._updateToMesh.bind(this);
  38014. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  38015. }
  38016. this._updateToMesh();
  38017. };
  38018. RayHelper.prototype.detachFromMesh = function () {
  38019. if (this._attachedToMesh) {
  38020. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  38021. this._attachedToMesh = null;
  38022. this._updateToMeshFunction = null;
  38023. }
  38024. };
  38025. RayHelper.prototype._updateToMesh = function () {
  38026. var ray = this.ray;
  38027. if (this._attachedToMesh._isDisposed) {
  38028. this.detachFromMesh();
  38029. return;
  38030. }
  38031. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  38032. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  38033. };
  38034. RayHelper.prototype.dispose = function () {
  38035. this.hide();
  38036. this.detachFromMesh();
  38037. this.ray = null;
  38038. };
  38039. return RayHelper;
  38040. }());
  38041. BABYLON.RayHelper = RayHelper;
  38042. })(BABYLON || (BABYLON = {}));
  38043. //# sourceMappingURL=babylon.rayHelper.js.map
  38044. var BABYLON;
  38045. (function (BABYLON) {
  38046. var DebugLayer = (function () {
  38047. function DebugLayer(scene) {
  38048. this._scene = scene;
  38049. }
  38050. /** Creates the inspector window. */
  38051. DebugLayer.prototype._createInspector = function (config) {
  38052. if (config === void 0) { config = {}; }
  38053. var popup = config.popup || false;
  38054. var initialTab = config.initialTab || 0;
  38055. var parentElement = config.parentElement || null;
  38056. if (!this._inspector) {
  38057. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  38058. } // else nothing to do,; instance is already existing
  38059. };
  38060. DebugLayer.prototype.isVisible = function () {
  38061. if (!this._inspector) {
  38062. return false;
  38063. }
  38064. return true;
  38065. };
  38066. DebugLayer.prototype.hide = function () {
  38067. if (this._inspector) {
  38068. try {
  38069. this._inspector.dispose();
  38070. }
  38071. catch (e) {
  38072. // If the inspector has been removed directly from the inspector tool
  38073. }
  38074. this._inspector = null;
  38075. }
  38076. };
  38077. DebugLayer.prototype.show = function (config) {
  38078. if (config === void 0) { config = {}; }
  38079. if (typeof INSPECTOR == 'undefined') {
  38080. // Load inspector and add it to the DOM
  38081. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  38082. }
  38083. else {
  38084. // Otherwise creates the inspector
  38085. this._createInspector(config);
  38086. }
  38087. };
  38088. return DebugLayer;
  38089. }());
  38090. // Get protocol used - http or https
  38091. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  38092. BABYLON.DebugLayer = DebugLayer;
  38093. })(BABYLON || (BABYLON = {}));
  38094. //# sourceMappingURL=babylon.debugLayer.js.map
  38095. var BABYLON;
  38096. (function (BABYLON) {
  38097. var BoundingBoxRenderer = (function () {
  38098. function BoundingBoxRenderer(scene) {
  38099. this.frontColor = new BABYLON.Color3(1, 1, 1);
  38100. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  38101. this.showBackLines = true;
  38102. this.renderList = new BABYLON.SmartArray(32);
  38103. this._vertexBuffers = {};
  38104. this._scene = scene;
  38105. }
  38106. BoundingBoxRenderer.prototype._prepareRessources = function () {
  38107. if (this._colorShader) {
  38108. return;
  38109. }
  38110. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  38111. attributes: [BABYLON.VertexBuffer.PositionKind],
  38112. uniforms: ["world", "viewProjection", "color"]
  38113. });
  38114. var engine = this._scene.getEngine();
  38115. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  38116. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  38117. 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]);
  38118. };
  38119. BoundingBoxRenderer.prototype.reset = function () {
  38120. this.renderList.reset();
  38121. };
  38122. BoundingBoxRenderer.prototype.render = function () {
  38123. if (this.renderList.length === 0) {
  38124. return;
  38125. }
  38126. this._prepareRessources();
  38127. if (!this._colorShader.isReady()) {
  38128. return;
  38129. }
  38130. var engine = this._scene.getEngine();
  38131. engine.setDepthWrite(false);
  38132. this._colorShader._preBind();
  38133. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38134. var boundingBox = this.renderList.data[boundingBoxIndex];
  38135. var min = boundingBox.minimum;
  38136. var max = boundingBox.maximum;
  38137. var diff = max.subtract(min);
  38138. var median = min.add(diff.scale(0.5));
  38139. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38140. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38141. .multiply(boundingBox.getWorldMatrix());
  38142. // VBOs
  38143. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38144. if (this.showBackLines) {
  38145. // Back
  38146. engine.setDepthFunctionToGreaterOrEqual();
  38147. this._scene.resetCachedMaterial();
  38148. this._colorShader.setColor4("color", this.backColor.toColor4());
  38149. this._colorShader.bind(worldMatrix);
  38150. // Draw order
  38151. engine.draw(false, 0, 24);
  38152. }
  38153. // Front
  38154. engine.setDepthFunctionToLess();
  38155. this._scene.resetCachedMaterial();
  38156. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38157. this._colorShader.bind(worldMatrix);
  38158. // Draw order
  38159. engine.draw(false, 0, 24);
  38160. }
  38161. this._colorShader.unbind();
  38162. engine.setDepthFunctionToLessOrEqual();
  38163. engine.setDepthWrite(true);
  38164. };
  38165. BoundingBoxRenderer.prototype.dispose = function () {
  38166. if (!this._colorShader) {
  38167. return;
  38168. }
  38169. this.renderList.dispose();
  38170. this._colorShader.dispose();
  38171. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38172. if (buffer) {
  38173. buffer.dispose();
  38174. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38175. }
  38176. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38177. };
  38178. return BoundingBoxRenderer;
  38179. }());
  38180. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38181. })(BABYLON || (BABYLON = {}));
  38182. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38183. var BABYLON;
  38184. (function (BABYLON) {
  38185. var MultiMaterial = (function (_super) {
  38186. __extends(MultiMaterial, _super);
  38187. function MultiMaterial(name, scene) {
  38188. var _this = _super.call(this, name, scene, true) || this;
  38189. _this.subMaterials = new Array();
  38190. scene.multiMaterials.push(_this);
  38191. return _this;
  38192. }
  38193. // Properties
  38194. MultiMaterial.prototype.getSubMaterial = function (index) {
  38195. if (index < 0 || index >= this.subMaterials.length) {
  38196. return this.getScene().defaultMaterial;
  38197. }
  38198. return this.subMaterials[index];
  38199. };
  38200. // Methods
  38201. MultiMaterial.prototype.getClassName = function () {
  38202. return "MultiMaterial";
  38203. };
  38204. MultiMaterial.prototype.isReady = function (mesh) {
  38205. for (var index = 0; index < this.subMaterials.length; index++) {
  38206. var subMaterial = this.subMaterials[index];
  38207. if (subMaterial) {
  38208. if (!this.subMaterials[index].isReady(mesh)) {
  38209. return false;
  38210. }
  38211. }
  38212. }
  38213. return true;
  38214. };
  38215. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  38216. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  38217. for (var index = 0; index < this.subMaterials.length; index++) {
  38218. var subMaterial = null;
  38219. if (cloneChildren) {
  38220. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  38221. }
  38222. else {
  38223. subMaterial = this.subMaterials[index];
  38224. }
  38225. newMultiMaterial.subMaterials.push(subMaterial);
  38226. }
  38227. return newMultiMaterial;
  38228. };
  38229. MultiMaterial.prototype.serialize = function () {
  38230. var serializationObject = {};
  38231. serializationObject.name = this.name;
  38232. serializationObject.id = this.id;
  38233. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38234. serializationObject.materials = [];
  38235. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  38236. var subMat = this.subMaterials[matIndex];
  38237. if (subMat) {
  38238. serializationObject.materials.push(subMat.id);
  38239. }
  38240. else {
  38241. serializationObject.materials.push(null);
  38242. }
  38243. }
  38244. return serializationObject;
  38245. };
  38246. return MultiMaterial;
  38247. }(BABYLON.Material));
  38248. BABYLON.MultiMaterial = MultiMaterial;
  38249. })(BABYLON || (BABYLON = {}));
  38250. //# sourceMappingURL=babylon.multiMaterial.js.map
  38251. var BABYLON;
  38252. (function (BABYLON) {
  38253. var PBRMaterialDefines = (function (_super) {
  38254. __extends(PBRMaterialDefines, _super);
  38255. function PBRMaterialDefines() {
  38256. var _this = _super.call(this) || this;
  38257. _this.PBR = true;
  38258. _this.ALBEDO = false;
  38259. _this.AMBIENT = false;
  38260. _this.AMBIENTINGRAYSCALE = false;
  38261. _this.OPACITY = false;
  38262. _this.OPACITYRGB = false;
  38263. _this.REFLECTION = false;
  38264. _this.EMISSIVE = false;
  38265. _this.REFLECTIVITY = false;
  38266. _this.BUMP = false;
  38267. _this.PARALLAX = false;
  38268. _this.PARALLAXOCCLUSION = false;
  38269. _this.SPECULAROVERALPHA = false;
  38270. _this.CLIPPLANE = false;
  38271. _this.ALPHATEST = false;
  38272. _this.ALPHAFROMALBEDO = false;
  38273. _this.POINTSIZE = false;
  38274. _this.FOG = false;
  38275. _this.SPECULARTERM = false;
  38276. _this.OPACITYFRESNEL = false;
  38277. _this.EMISSIVEFRESNEL = false;
  38278. _this.FRESNEL = false;
  38279. _this.NORMAL = false;
  38280. _this.TANGENT = false;
  38281. _this.UV1 = false;
  38282. _this.UV2 = false;
  38283. _this.VERTEXCOLOR = false;
  38284. _this.VERTEXALPHA = false;
  38285. _this.NUM_BONE_INFLUENCERS = 0;
  38286. _this.BonesPerMesh = 0;
  38287. _this.INSTANCES = false;
  38288. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38289. _this.MICROSURFACEAUTOMATIC = false;
  38290. _this.EMISSIVEASILLUMINATION = false;
  38291. _this.LIGHTMAP = false;
  38292. _this.USELIGHTMAPASSHADOWMAP = false;
  38293. _this.REFLECTIONMAP_3D = false;
  38294. _this.REFLECTIONMAP_SPHERICAL = false;
  38295. _this.REFLECTIONMAP_PLANAR = false;
  38296. _this.REFLECTIONMAP_CUBIC = false;
  38297. _this.REFLECTIONMAP_PROJECTION = false;
  38298. _this.REFLECTIONMAP_SKYBOX = false;
  38299. _this.REFLECTIONMAP_EXPLICIT = false;
  38300. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38301. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38302. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38303. _this.INVERTCUBICMAP = false;
  38304. _this.LOGARITHMICDEPTH = false;
  38305. _this.CAMERATONEMAP = false;
  38306. _this.CAMERACONTRAST = false;
  38307. _this.CAMERACOLORGRADING = false;
  38308. _this.CAMERACOLORCURVES = false;
  38309. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38310. _this.REFRACTION = false;
  38311. _this.REFRACTIONMAP_3D = false;
  38312. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38313. _this.REFRACTIONMAPINLINEARSPACE = false;
  38314. _this.LODBASEDMICROSFURACE = false;
  38315. _this.USEPHYSICALLIGHTFALLOFF = false;
  38316. _this.RADIANCEOVERALPHA = false;
  38317. _this.USEPMREMREFLECTION = false;
  38318. _this.USEPMREMREFRACTION = false;
  38319. _this.INVERTNORMALMAPX = false;
  38320. _this.INVERTNORMALMAPY = false;
  38321. _this.TWOSIDEDLIGHTING = false;
  38322. _this.SHADOWFLOAT = false;
  38323. _this.NORMALXYSCALE = true;
  38324. _this.USERIGHTHANDEDSYSTEM = false;
  38325. _this.METALLICWORKFLOW = false;
  38326. _this.METALLICMAP = false;
  38327. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38328. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38329. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38330. _this.AOSTOREINMETALMAPRED = false;
  38331. _this.MICROSURFACEMAP = false;
  38332. _this.MORPHTARGETS = false;
  38333. _this.MORPHTARGETS_NORMAL = false;
  38334. _this.MORPHTARGETS_TANGENT = false;
  38335. _this.NUM_MORPH_INFLUENCERS = 0;
  38336. _this.ALPHATESTVALUE = 0.4;
  38337. _this.LDROUTPUT = true;
  38338. _this.rebuild();
  38339. return _this;
  38340. }
  38341. PBRMaterialDefines.prototype.reset = function () {
  38342. _super.prototype.reset.call(this);
  38343. this.ALPHATESTVALUE = 0.4;
  38344. this.PBR = true;
  38345. };
  38346. return PBRMaterialDefines;
  38347. }(BABYLON.MaterialDefines));
  38348. /**
  38349. * The Physically based material base class of BJS.
  38350. *
  38351. * This offers the main features of a standard PBR material.
  38352. * For more information, please refer to the documentation :
  38353. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38354. */
  38355. var PBRBaseMaterial = (function (_super) {
  38356. __extends(PBRBaseMaterial, _super);
  38357. /**
  38358. * Instantiates a new PBRMaterial instance.
  38359. *
  38360. * @param name The material name
  38361. * @param scene The scene the material will be use in.
  38362. */
  38363. function PBRBaseMaterial(name, scene) {
  38364. var _this = _super.call(this, name, scene) || this;
  38365. /**
  38366. * Intensity of the direct lights e.g. the four lights available in your scene.
  38367. * This impacts both the direct diffuse and specular highlights.
  38368. */
  38369. _this._directIntensity = 1.0;
  38370. /**
  38371. * Intensity of the emissive part of the material.
  38372. * This helps controlling the emissive effect without modifying the emissive color.
  38373. */
  38374. _this._emissiveIntensity = 1.0;
  38375. /**
  38376. * Intensity of the environment e.g. how much the environment will light the object
  38377. * either through harmonics for rough material or through the refelction for shiny ones.
  38378. */
  38379. _this._environmentIntensity = 1.0;
  38380. /**
  38381. * This is a special control allowing the reduction of the specular highlights coming from the
  38382. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38383. */
  38384. _this._specularIntensity = 1.0;
  38385. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38386. /**
  38387. * Debug Control allowing disabling the bump map on this material.
  38388. */
  38389. _this._disableBumpMap = false;
  38390. /**
  38391. * The camera exposure used on this material.
  38392. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38393. * This corresponds to a photographic exposure.
  38394. */
  38395. _this._cameraExposure = 1.0;
  38396. /**
  38397. * The camera contrast used on this material.
  38398. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  38399. */
  38400. _this._cameraContrast = 1.0;
  38401. /**
  38402. * Color Grading 2D Lookup Texture.
  38403. * This allows special effects like sepia, black and white to sixties rendering style.
  38404. */
  38405. _this._cameraColorGradingTexture = null;
  38406. /**
  38407. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38408. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38409. * 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;
  38410. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38411. */
  38412. _this._cameraColorCurves = null;
  38413. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  38414. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  38415. /**
  38416. * AKA Occlusion Texture Intensity in other nomenclature.
  38417. */
  38418. _this._ambientTextureStrength = 1.0;
  38419. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38420. /**
  38421. * AKA Diffuse Color in other nomenclature.
  38422. */
  38423. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38424. /**
  38425. * AKA Specular Color in other nomenclature.
  38426. */
  38427. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38428. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38429. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38430. /**
  38431. * AKA Glossiness in other nomenclature.
  38432. */
  38433. _this._microSurface = 0.9;
  38434. /**
  38435. * source material index of refraction (IOR)' / 'destination material IOR.
  38436. */
  38437. _this._indexOfRefraction = 0.66;
  38438. /**
  38439. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38440. */
  38441. _this._invertRefractionY = false;
  38442. /**
  38443. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38444. * Materials half opaque for instance using refraction could benefit from this control.
  38445. */
  38446. _this._linkRefractionWithTransparency = false;
  38447. _this._useLightmapAsShadowmap = false;
  38448. /**
  38449. * In this mode, the emissive informtaion will always be added to the lighting once.
  38450. * A light for instance can be thought as emissive.
  38451. */
  38452. _this._useEmissiveAsIllumination = false;
  38453. /**
  38454. * Secifies that the alpha is coming form the albedo channel alpha channel.
  38455. */
  38456. _this._useAlphaFromAlbedoTexture = false;
  38457. /**
  38458. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38459. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38460. */
  38461. _this._useSpecularOverAlpha = true;
  38462. /**
  38463. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38464. */
  38465. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38466. /**
  38467. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38468. */
  38469. _this._useRoughnessFromMetallicTextureAlpha = true;
  38470. /**
  38471. * Specifies if the metallic texture contains the roughness information in its green channel.
  38472. */
  38473. _this._useRoughnessFromMetallicTextureGreen = false;
  38474. /**
  38475. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38476. */
  38477. _this._useMetallnessFromMetallicTextureBlue = false;
  38478. /**
  38479. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38480. */
  38481. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38482. /**
  38483. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38484. */
  38485. _this._useAmbientInGrayScale = false;
  38486. /**
  38487. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38488. * The material will try to infer what glossiness each pixel should be.
  38489. */
  38490. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38491. /**
  38492. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  38493. * the creation of the material.
  38494. */
  38495. _this._useScalarInLinearSpace = false;
  38496. /**
  38497. * BJS is using an harcoded light falloff based on a manually sets up range.
  38498. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38499. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38500. */
  38501. _this._usePhysicalLightFalloff = true;
  38502. /**
  38503. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38504. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38505. */
  38506. _this._useRadianceOverAlpha = true;
  38507. /**
  38508. * Allows using the bump map in parallax mode.
  38509. */
  38510. _this._useParallax = false;
  38511. /**
  38512. * Allows using the bump map in parallax occlusion mode.
  38513. */
  38514. _this._useParallaxOcclusion = false;
  38515. /**
  38516. * Controls the scale bias of the parallax mode.
  38517. */
  38518. _this._parallaxScaleBias = 0.05;
  38519. /**
  38520. * If sets to true, disables all the lights affecting the material.
  38521. */
  38522. _this._disableLighting = false;
  38523. /**
  38524. * Number of Simultaneous lights allowed on the material.
  38525. */
  38526. _this._maxSimultaneousLights = 4;
  38527. /**
  38528. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38529. */
  38530. _this._invertNormalMapX = false;
  38531. /**
  38532. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38533. */
  38534. _this._invertNormalMapY = false;
  38535. /**
  38536. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38537. */
  38538. _this._twoSidedLighting = false;
  38539. /**
  38540. * Defines the alpha limits in alpha test mode.
  38541. */
  38542. _this._alphaCutOff = 0.4;
  38543. /**
  38544. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38545. */
  38546. _this._forceAlphaTest = false;
  38547. /**
  38548. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  38549. * in combination of post process in float or half float mode.
  38550. */
  38551. _this._ldrOutput = true;
  38552. _this._renderTargets = new BABYLON.SmartArray(16);
  38553. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38554. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38555. _this._tempColor = new BABYLON.Color3();
  38556. _this._defines = new PBRMaterialDefines();
  38557. _this._cachedDefines = new PBRMaterialDefines();
  38558. _this._myScene = null;
  38559. _this._myShadowGenerator = null;
  38560. _this._cachedDefines.BonesPerMesh = -1;
  38561. _this.getRenderTargetTextures = function () {
  38562. _this._renderTargets.reset();
  38563. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38564. _this._renderTargets.push(_this._reflectionTexture);
  38565. }
  38566. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38567. _this._renderTargets.push(_this._refractionTexture);
  38568. }
  38569. return _this._renderTargets;
  38570. };
  38571. return _this;
  38572. }
  38573. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38574. get: function () {
  38575. return this._useLogarithmicDepth;
  38576. },
  38577. set: function (value) {
  38578. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38584. if (this._linkRefractionWithTransparency) {
  38585. return false;
  38586. }
  38587. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38588. };
  38589. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38590. if (this._linkRefractionWithTransparency) {
  38591. return false;
  38592. }
  38593. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  38594. };
  38595. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38596. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  38597. };
  38598. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38599. return this._albedoTexture;
  38600. };
  38601. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38602. if (!mesh) {
  38603. return true;
  38604. }
  38605. if (this._defines.INSTANCES !== useInstances) {
  38606. return false;
  38607. }
  38608. return false;
  38609. };
  38610. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  38611. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  38612. };
  38613. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  38614. if (!useScalarInLinear) {
  38615. color.toLinearSpaceToRef(ref);
  38616. }
  38617. else {
  38618. ref.r = color.r;
  38619. ref.g = color.g;
  38620. ref.b = color.b;
  38621. }
  38622. };
  38623. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  38624. var lightIndex = 0;
  38625. var depthValuesAlreadySet = false;
  38626. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38627. var light = _a[_i];
  38628. var useUbo = light._uniformBuffer.useUbo;
  38629. var scaledIntensity = light.getScaledIntensity();
  38630. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  38631. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  38632. // GAMMA CORRECTION.
  38633. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  38634. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  38635. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  38636. if (defines["SPECULARTERM"]) {
  38637. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  38638. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  38639. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  38640. }
  38641. // Shadows
  38642. if (scene.shadowsEnabled) {
  38643. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  38644. }
  38645. light._uniformBuffer.update();
  38646. lightIndex++;
  38647. if (lightIndex === maxSimultaneousLights)
  38648. break;
  38649. }
  38650. };
  38651. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  38652. if (this.isFrozen) {
  38653. if (this._wasPreviouslyReady) {
  38654. return true;
  38655. }
  38656. }
  38657. var scene = this.getScene();
  38658. var engine = scene.getEngine();
  38659. var needUVs = false;
  38660. this._defines.reset();
  38661. if (scene.lightsEnabled && !this._disableLighting) {
  38662. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  38663. }
  38664. if (!this.checkReadyOnEveryCall) {
  38665. if (this._renderId === scene.getRenderId()) {
  38666. if (this._checkCache(scene, mesh, useInstances)) {
  38667. return true;
  38668. }
  38669. }
  38670. }
  38671. if (scene.texturesEnabled) {
  38672. if (scene.getEngine().getCaps().textureLOD) {
  38673. this._defines.LODBASEDMICROSFURACE = true;
  38674. }
  38675. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38676. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38677. return false;
  38678. }
  38679. needUVs = true;
  38680. this._defines.ALBEDO = true;
  38681. }
  38682. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38683. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38684. return false;
  38685. }
  38686. needUVs = true;
  38687. this._defines.AMBIENT = true;
  38688. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38689. }
  38690. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38691. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38692. return false;
  38693. }
  38694. needUVs = true;
  38695. this._defines.OPACITY = true;
  38696. if (this._opacityTexture.getAlphaFromRGB) {
  38697. this._defines.OPACITYRGB = true;
  38698. }
  38699. }
  38700. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  38701. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38702. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38703. return false;
  38704. }
  38705. this._defines.REFLECTION = true;
  38706. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38707. this._defines.INVERTCUBICMAP = true;
  38708. }
  38709. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38710. switch (reflectionTexture.coordinatesMode) {
  38711. case BABYLON.Texture.CUBIC_MODE:
  38712. case BABYLON.Texture.INVCUBIC_MODE:
  38713. this._defines.REFLECTIONMAP_CUBIC = true;
  38714. break;
  38715. case BABYLON.Texture.EXPLICIT_MODE:
  38716. this._defines.REFLECTIONMAP_EXPLICIT = true;
  38717. break;
  38718. case BABYLON.Texture.PLANAR_MODE:
  38719. this._defines.REFLECTIONMAP_PLANAR = true;
  38720. break;
  38721. case BABYLON.Texture.PROJECTION_MODE:
  38722. this._defines.REFLECTIONMAP_PROJECTION = true;
  38723. break;
  38724. case BABYLON.Texture.SKYBOX_MODE:
  38725. this._defines.REFLECTIONMAP_SKYBOX = true;
  38726. break;
  38727. case BABYLON.Texture.SPHERICAL_MODE:
  38728. this._defines.REFLECTIONMAP_SPHERICAL = true;
  38729. break;
  38730. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38731. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38732. break;
  38733. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38734. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38735. break;
  38736. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38737. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38738. break;
  38739. }
  38740. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  38741. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  38742. if (reflectionTexture.isPMREM) {
  38743. this._defines.USEPMREMREFLECTION = true;
  38744. }
  38745. }
  38746. }
  38747. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38748. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38749. return false;
  38750. }
  38751. needUVs = true;
  38752. this._defines.LIGHTMAP = true;
  38753. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38754. }
  38755. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38756. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38757. return false;
  38758. }
  38759. needUVs = true;
  38760. this._defines.EMISSIVE = true;
  38761. }
  38762. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38763. if (this._metallicTexture) {
  38764. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38765. return false;
  38766. }
  38767. needUVs = true;
  38768. this._defines.METALLICWORKFLOW = true;
  38769. this._defines.METALLICMAP = true;
  38770. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38771. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38772. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38773. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38774. }
  38775. else if (this._reflectivityTexture) {
  38776. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38777. return false;
  38778. }
  38779. needUVs = true;
  38780. this._defines.REFLECTIVITY = true;
  38781. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38782. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38783. }
  38784. if (this._microSurfaceTexture) {
  38785. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38786. return false;
  38787. }
  38788. needUVs = true;
  38789. this._defines.MICROSURFACEMAP = true;
  38790. }
  38791. }
  38792. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38793. // Bump texure can not be none blocking.
  38794. if (!this._bumpTexture.isReady()) {
  38795. return false;
  38796. }
  38797. needUVs = true;
  38798. this._defines.BUMP = true;
  38799. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38800. this._defines.PARALLAX = true;
  38801. if (this._useParallaxOcclusion) {
  38802. this._defines.PARALLAXOCCLUSION = true;
  38803. }
  38804. }
  38805. if (this._invertNormalMapX) {
  38806. this._defines.INVERTNORMALMAPX = true;
  38807. }
  38808. if (this._invertNormalMapY) {
  38809. this._defines.INVERTNORMALMAPY = true;
  38810. }
  38811. if (scene._mirroredCameraPosition) {
  38812. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  38813. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  38814. }
  38815. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  38816. }
  38817. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38818. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38819. return false;
  38820. }
  38821. needUVs = true;
  38822. this._defines.REFRACTION = true;
  38823. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38824. if (this._linkRefractionWithTransparency) {
  38825. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38826. }
  38827. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  38828. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  38829. if (this._refractionTexture.isPMREM) {
  38830. this._defines.USEPMREMREFRACTION = true;
  38831. }
  38832. }
  38833. }
  38834. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  38835. // Color Grading texure can not be none blocking.
  38836. if (!this._cameraColorGradingTexture.isReady()) {
  38837. return false;
  38838. }
  38839. this._defines.CAMERACOLORGRADING = true;
  38840. }
  38841. if (!this.backFaceCulling && this._twoSidedLighting) {
  38842. this._defines.TWOSIDEDLIGHTING = true;
  38843. }
  38844. }
  38845. this._defines.LDROUTPUT = this._ldrOutput;
  38846. // Effect
  38847. if (scene.clipPlane) {
  38848. this._defines.CLIPPLANE = true;
  38849. }
  38850. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  38851. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  38852. this._defines.ALPHATEST = true;
  38853. }
  38854. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38855. this._defines.ALPHAFROMALBEDO = true;
  38856. }
  38857. if (this._useEmissiveAsIllumination) {
  38858. this._defines.EMISSIVEASILLUMINATION = true;
  38859. }
  38860. if (this.useLogarithmicDepth) {
  38861. this._defines.LOGARITHMICDEPTH = true;
  38862. }
  38863. if (this._cameraContrast != 1) {
  38864. this._defines.CAMERACONTRAST = true;
  38865. }
  38866. if (this._cameraExposure != 1) {
  38867. this._defines.CAMERATONEMAP = true;
  38868. }
  38869. if (this._cameraColorCurves) {
  38870. this._defines.CAMERACOLORCURVES = true;
  38871. }
  38872. // Point size
  38873. if (this.pointsCloud || scene.forcePointsCloud) {
  38874. this._defines.POINTSIZE = true;
  38875. }
  38876. // Fog
  38877. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38878. this._defines.FOG = true;
  38879. }
  38880. if (BABYLON.StandardMaterial.FresnelEnabled) {
  38881. // Fresnel
  38882. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  38883. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38884. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  38885. this._defines.OPACITYFRESNEL = true;
  38886. }
  38887. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38888. this._defines.EMISSIVEFRESNEL = true;
  38889. }
  38890. this._defines.FRESNEL = true;
  38891. }
  38892. }
  38893. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  38894. this._defines.SPECULAROVERALPHA = true;
  38895. }
  38896. if (this._usePhysicalLightFalloff) {
  38897. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  38898. }
  38899. if (this._useRadianceOverAlpha) {
  38900. this._defines.RADIANCEOVERALPHA = true;
  38901. }
  38902. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38903. this._defines.METALLICWORKFLOW = true;
  38904. }
  38905. // Attribs
  38906. if (mesh) {
  38907. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38908. mesh.createNormals(true);
  38909. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  38910. }
  38911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38912. this._defines.NORMAL = true;
  38913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38914. this._defines.TANGENT = true;
  38915. }
  38916. }
  38917. if (needUVs) {
  38918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38919. this._defines.UV1 = true;
  38920. }
  38921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38922. this._defines.UV2 = true;
  38923. }
  38924. }
  38925. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38926. this._defines.VERTEXCOLOR = true;
  38927. if (mesh.hasVertexAlpha) {
  38928. this._defines.VERTEXALPHA = true;
  38929. }
  38930. }
  38931. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38932. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  38933. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  38934. }
  38935. // Instances
  38936. if (useInstances) {
  38937. this._defines.INSTANCES = true;
  38938. }
  38939. if (mesh.morphTargetManager) {
  38940. var manager = mesh.morphTargetManager;
  38941. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  38942. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  38943. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  38944. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  38945. }
  38946. }
  38947. // Get correct effect
  38948. if (!this._defines.isEqual(this._cachedDefines)) {
  38949. this._defines.cloneTo(this._cachedDefines);
  38950. scene.resetCachedMaterial();
  38951. // Fallbacks
  38952. var fallbacks = new BABYLON.EffectFallbacks();
  38953. if (this._defines.REFLECTION) {
  38954. fallbacks.addFallback(0, "REFLECTION");
  38955. }
  38956. if (this._defines.REFRACTION) {
  38957. fallbacks.addFallback(0, "REFRACTION");
  38958. }
  38959. if (this._defines.REFLECTIVITY) {
  38960. fallbacks.addFallback(0, "REFLECTIVITY");
  38961. }
  38962. if (this._defines.BUMP) {
  38963. fallbacks.addFallback(0, "BUMP");
  38964. }
  38965. if (this._defines.PARALLAX) {
  38966. fallbacks.addFallback(1, "PARALLAX");
  38967. }
  38968. if (this._defines.PARALLAXOCCLUSION) {
  38969. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38970. }
  38971. if (this._defines.SPECULAROVERALPHA) {
  38972. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38973. }
  38974. if (this._defines.FOG) {
  38975. fallbacks.addFallback(1, "FOG");
  38976. }
  38977. if (this._defines.POINTSIZE) {
  38978. fallbacks.addFallback(0, "POINTSIZE");
  38979. }
  38980. if (this._defines.LOGARITHMICDEPTH) {
  38981. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38982. }
  38983. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  38984. if (this._defines.SPECULARTERM) {
  38985. fallbacks.addFallback(0, "SPECULARTERM");
  38986. }
  38987. if (this._defines.OPACITYFRESNEL) {
  38988. fallbacks.addFallback(1, "OPACITYFRESNEL");
  38989. }
  38990. if (this._defines.EMISSIVEFRESNEL) {
  38991. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  38992. }
  38993. if (this._defines.FRESNEL) {
  38994. fallbacks.addFallback(3, "FRESNEL");
  38995. }
  38996. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  38997. fallbacks.addCPUSkinningFallback(0, mesh);
  38998. }
  38999. //Attributes
  39000. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39001. if (this._defines.NORMAL) {
  39002. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39003. }
  39004. if (this._defines.TANGENT) {
  39005. attribs.push(BABYLON.VertexBuffer.TangentKind);
  39006. }
  39007. if (this._defines.UV1) {
  39008. attribs.push(BABYLON.VertexBuffer.UVKind);
  39009. }
  39010. if (this._defines.UV2) {
  39011. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39012. }
  39013. if (this._defines.VERTEXCOLOR) {
  39014. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39015. }
  39016. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  39017. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  39018. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  39019. // Legacy browser patch
  39020. var join = this._defines.toString();
  39021. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  39022. "vFogInfos", "vFogColor", "pointSize",
  39023. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39024. "mBones",
  39025. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  39026. "depthValues",
  39027. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  39028. "vLightingIntensity",
  39029. "logarithmicDepthConstant",
  39030. "vSphericalX", "vSphericalY", "vSphericalZ",
  39031. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  39032. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  39033. "vMicrosurfaceTextureLods",
  39034. "vCameraInfos"
  39035. ];
  39036. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39037. var uniformBuffers = ["Material", "Scene"];
  39038. if (this._defines.CAMERACOLORCURVES) {
  39039. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  39040. }
  39041. if (this._defines.CAMERACOLORGRADING) {
  39042. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  39043. }
  39044. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39045. uniformsNames: uniforms,
  39046. uniformBuffersNames: uniformBuffers,
  39047. samplers: samplers,
  39048. defines: this._defines,
  39049. maxSimultaneousLights: this._maxSimultaneousLights
  39050. });
  39051. var onCompiled = function (effect) {
  39052. if (this.onCompiled) {
  39053. this.onCompiled(effect);
  39054. }
  39055. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  39056. }.bind(this);
  39057. this._effect = scene.getEngine().createEffect("pbr", {
  39058. attributes: attribs,
  39059. uniformsNames: uniforms,
  39060. uniformBuffersNames: uniformBuffers,
  39061. samplers: samplers,
  39062. defines: join,
  39063. fallbacks: fallbacks,
  39064. onCompiled: onCompiled,
  39065. onError: this.onError,
  39066. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  39067. }, engine);
  39068. this.buildUniformLayout();
  39069. }
  39070. if (!this._effect.isReady()) {
  39071. return false;
  39072. }
  39073. this._renderId = scene.getRenderId();
  39074. this._wasPreviouslyReady = true;
  39075. return true;
  39076. };
  39077. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  39078. // Order is important !
  39079. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  39080. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  39081. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39082. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39083. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39084. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  39085. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  39086. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39087. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39088. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39089. this._uniformBuffer.addUniform("albedoMatrix", 16);
  39090. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39091. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39092. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39093. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39094. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  39095. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  39096. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39097. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39098. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39099. this._uniformBuffer.addUniform("vReflectionColor", 3);
  39100. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  39101. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  39102. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  39103. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  39104. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39105. this._uniformBuffer.addUniform("opacityParts", 4);
  39106. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39107. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39108. this._uniformBuffer.addUniform("pointSize", 1);
  39109. this._uniformBuffer.create();
  39110. };
  39111. PBRBaseMaterial.prototype.unbind = function () {
  39112. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39113. this._uniformBuffer.setTexture("reflection2DSampler", null);
  39114. }
  39115. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39116. this._uniformBuffer.setTexture("refraction2DSampler", null);
  39117. }
  39118. _super.prototype.unbind.call(this);
  39119. };
  39120. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39121. this._effect.setMatrix("world", world);
  39122. };
  39123. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  39124. this._myScene = this.getScene();
  39125. var effect = this._effect;
  39126. // Matrices
  39127. this.bindOnlyWorldMatrix(world);
  39128. // Bones
  39129. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39130. if (this._myScene.getCachedMaterial() !== this) {
  39131. this._uniformBuffer.bindToEffect(effect, "Material");
  39132. this.bindViewProjection(effect);
  39133. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39134. // Fresnel
  39135. if (BABYLON.StandardMaterial.FresnelEnabled) {
  39136. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  39137. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  39138. }
  39139. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  39140. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  39141. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  39142. }
  39143. }
  39144. // Texture uniforms
  39145. if (this._myScene.texturesEnabled) {
  39146. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39147. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39148. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  39149. }
  39150. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39151. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39152. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  39153. }
  39154. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39155. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39156. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  39157. }
  39158. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  39159. ;
  39160. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39161. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  39162. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39163. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39164. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  39165. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  39166. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  39167. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  39168. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  39169. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  39170. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  39171. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  39172. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  39173. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  39174. }
  39175. }
  39176. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39177. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39178. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  39179. }
  39180. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39181. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39182. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  39183. }
  39184. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39185. if (this._metallicTexture) {
  39186. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39187. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  39188. }
  39189. else if (this._reflectivityTexture) {
  39190. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39191. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  39192. }
  39193. if (this._microSurfaceTexture) {
  39194. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39195. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  39196. }
  39197. }
  39198. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39199. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39200. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  39201. }
  39202. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39203. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  39204. var depth = 1.0;
  39205. if (!this._refractionTexture.isCube) {
  39206. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39207. if (this._refractionTexture.depth) {
  39208. depth = this._refractionTexture.depth;
  39209. }
  39210. }
  39211. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39212. }
  39213. if ((reflectionTexture || this._refractionTexture)) {
  39214. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  39215. }
  39216. }
  39217. // Point size
  39218. if (this.pointsCloud) {
  39219. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39220. }
  39221. // Colors
  39222. if (this._defines.METALLICWORKFLOW) {
  39223. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39224. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39225. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39226. }
  39227. else {
  39228. // GAMMA CORRECTION.
  39229. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  39230. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  39231. }
  39232. // GAMMA CORRECTION.
  39233. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  39234. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  39235. // GAMMA CORRECTION.
  39236. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  39237. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  39238. // GAMMA CORRECTION.
  39239. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  39240. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  39241. // Misc
  39242. this._lightingInfos.x = this._directIntensity;
  39243. this._lightingInfos.y = this._emissiveIntensity;
  39244. this._lightingInfos.z = this._environmentIntensity;
  39245. this._lightingInfos.w = this._specularIntensity;
  39246. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39247. }
  39248. // Textures
  39249. if (this._myScene.texturesEnabled) {
  39250. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39251. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39252. }
  39253. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39254. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39255. }
  39256. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39257. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39258. }
  39259. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39260. if (reflectionTexture.isCube) {
  39261. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  39262. }
  39263. else {
  39264. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  39265. }
  39266. }
  39267. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39268. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39269. }
  39270. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39271. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39272. }
  39273. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39274. if (this._metallicTexture) {
  39275. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39276. }
  39277. else if (this._reflectivityTexture) {
  39278. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39279. }
  39280. if (this._microSurfaceTexture) {
  39281. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39282. }
  39283. }
  39284. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39285. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39286. }
  39287. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39288. if (this._refractionTexture.isCube) {
  39289. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  39290. }
  39291. else {
  39292. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  39293. }
  39294. }
  39295. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  39296. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  39297. }
  39298. }
  39299. // Clip plane
  39300. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  39301. // Colors
  39302. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39303. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  39304. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39305. }
  39306. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  39307. // Lights
  39308. if (this._myScene.lightsEnabled && !this._disableLighting) {
  39309. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39310. }
  39311. // View
  39312. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39313. this.bindView(effect);
  39314. }
  39315. // Fog
  39316. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  39317. // Morph targets
  39318. if (this._defines.NUM_MORPH_INFLUENCERS) {
  39319. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  39320. }
  39321. this._cameraInfos.x = this._cameraExposure;
  39322. this._cameraInfos.y = this._cameraContrast;
  39323. effect.setVector4("vCameraInfos", this._cameraInfos);
  39324. if (this._cameraColorCurves) {
  39325. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  39326. }
  39327. // Log. depth
  39328. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  39329. }
  39330. this._uniformBuffer.update();
  39331. this._afterBind(mesh);
  39332. this._myScene = null;
  39333. };
  39334. PBRBaseMaterial.prototype.getAnimatables = function () {
  39335. var results = [];
  39336. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39337. results.push(this._albedoTexture);
  39338. }
  39339. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39340. results.push(this._ambientTexture);
  39341. }
  39342. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39343. results.push(this._opacityTexture);
  39344. }
  39345. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39346. results.push(this._reflectionTexture);
  39347. }
  39348. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39349. results.push(this._emissiveTexture);
  39350. }
  39351. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39352. results.push(this._metallicTexture);
  39353. }
  39354. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39355. results.push(this._reflectivityTexture);
  39356. }
  39357. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39358. results.push(this._bumpTexture);
  39359. }
  39360. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39361. results.push(this._lightmapTexture);
  39362. }
  39363. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39364. results.push(this._refractionTexture);
  39365. }
  39366. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  39367. results.push(this._cameraColorGradingTexture);
  39368. }
  39369. return results;
  39370. };
  39371. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39372. if (forceDisposeTextures) {
  39373. if (this._albedoTexture) {
  39374. this._albedoTexture.dispose();
  39375. }
  39376. if (this._ambientTexture) {
  39377. this._ambientTexture.dispose();
  39378. }
  39379. if (this._opacityTexture) {
  39380. this._opacityTexture.dispose();
  39381. }
  39382. if (this._reflectionTexture) {
  39383. this._reflectionTexture.dispose();
  39384. }
  39385. if (this._emissiveTexture) {
  39386. this._emissiveTexture.dispose();
  39387. }
  39388. if (this._metallicTexture) {
  39389. this._metallicTexture.dispose();
  39390. }
  39391. if (this._reflectivityTexture) {
  39392. this._reflectivityTexture.dispose();
  39393. }
  39394. if (this._bumpTexture) {
  39395. this._bumpTexture.dispose();
  39396. }
  39397. if (this._lightmapTexture) {
  39398. this._lightmapTexture.dispose();
  39399. }
  39400. if (this._refractionTexture) {
  39401. this._refractionTexture.dispose();
  39402. }
  39403. if (this._cameraColorGradingTexture) {
  39404. this._cameraColorGradingTexture.dispose();
  39405. }
  39406. }
  39407. this._renderTargets.dispose();
  39408. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39409. };
  39410. return PBRBaseMaterial;
  39411. }(BABYLON.Material));
  39412. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  39413. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39414. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  39415. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  39416. __decorate([
  39417. BABYLON.serialize()
  39418. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39419. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39420. })(BABYLON || (BABYLON = {}));
  39421. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39422. var BABYLON;
  39423. (function (BABYLON) {
  39424. var Internals;
  39425. (function (Internals) {
  39426. /**
  39427. * The Physically based simple base material of BJS.
  39428. *
  39429. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39430. * It is used as the base class for both the specGloss and metalRough conventions.
  39431. */
  39432. var PBRBaseSimpleMaterial = (function (_super) {
  39433. __extends(PBRBaseSimpleMaterial, _super);
  39434. /**
  39435. * Instantiates a new PBRMaterial instance.
  39436. *
  39437. * @param name The material name
  39438. * @param scene The scene the material will be use in.
  39439. */
  39440. function PBRBaseSimpleMaterial(name, scene) {
  39441. var _this = _super.call(this, name, scene) || this;
  39442. /**
  39443. * Number of Simultaneous lights allowed on the material.
  39444. */
  39445. _this.maxSimultaneousLights = 4;
  39446. /**
  39447. * If sets to true, disables all the lights affecting the material.
  39448. */
  39449. _this.disableLighting = false;
  39450. /**
  39451. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39452. */
  39453. _this.invertNormalMapX = false;
  39454. /**
  39455. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39456. */
  39457. _this.invertNormalMapY = false;
  39458. /**
  39459. * Emissivie color used to self-illuminate the model.
  39460. */
  39461. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39462. /**
  39463. * Occlusion Channel Strenght.
  39464. */
  39465. _this.occlusionStrength = 1.0;
  39466. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39467. _this._useEmissiveAsIllumination = true;
  39468. _this._useAmbientInGrayScale = true;
  39469. _this._useScalarInLinearSpace = true;
  39470. return _this;
  39471. }
  39472. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  39473. /**
  39474. * Gets the current transparency mode.
  39475. */
  39476. get: function () {
  39477. return this._transparencyMode;
  39478. },
  39479. /**
  39480. * Sets the transparency mode of the material.
  39481. */
  39482. set: function (value) {
  39483. this._transparencyMode = value;
  39484. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  39485. this._forceAlphaTest = true;
  39486. }
  39487. else {
  39488. this._forceAlphaTest = false;
  39489. }
  39490. },
  39491. enumerable: true,
  39492. configurable: true
  39493. });
  39494. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39495. /**
  39496. * Gets the current double sided mode.
  39497. */
  39498. get: function () {
  39499. return this._twoSidedLighting;
  39500. },
  39501. /**
  39502. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39503. */
  39504. set: function (value) {
  39505. this._twoSidedLighting = value;
  39506. this.backFaceCulling = !value;
  39507. },
  39508. enumerable: true,
  39509. configurable: true
  39510. });
  39511. /**
  39512. * Specifies wether or not the alpha value of the albedo texture should be used.
  39513. */
  39514. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39515. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39516. };
  39517. /**
  39518. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  39519. */
  39520. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  39521. if (this._linkRefractionWithTransparency) {
  39522. return false;
  39523. }
  39524. return (this.alpha < 1.0) ||
  39525. (this._shouldUseAlphaFromAlbedoTexture() &&
  39526. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  39527. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  39528. };
  39529. /**
  39530. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  39531. */
  39532. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  39533. if (this._linkRefractionWithTransparency) {
  39534. return false;
  39535. }
  39536. return this._shouldUseAlphaFromAlbedoTexture() &&
  39537. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  39538. };
  39539. return PBRBaseSimpleMaterial;
  39540. }(BABYLON.PBRBaseMaterial));
  39541. __decorate([
  39542. BABYLON.serialize(),
  39543. BABYLON.expandToProperty(null)
  39544. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39545. __decorate([
  39546. BABYLON.serialize(),
  39547. BABYLON.expandToProperty(null)
  39548. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39549. __decorate([
  39550. BABYLON.serializeAsTexture(),
  39551. BABYLON.expandToProperty(null, "_reflectionTexture")
  39552. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39553. __decorate([
  39554. BABYLON.serialize(),
  39555. BABYLON.expandToProperty(null)
  39556. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39557. __decorate([
  39558. BABYLON.serialize(),
  39559. BABYLON.expandToProperty(null)
  39560. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39561. __decorate([
  39562. BABYLON.serializeAsTexture(),
  39563. BABYLON.expandToProperty(null, "_bumpTexture")
  39564. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39565. __decorate([
  39566. BABYLON.serializeAsColor3("emissive"),
  39567. BABYLON.expandToProperty(null)
  39568. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39569. __decorate([
  39570. BABYLON.serializeAsTexture(),
  39571. BABYLON.expandToProperty(null)
  39572. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39573. __decorate([
  39574. BABYLON.serialize(),
  39575. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  39576. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39577. __decorate([
  39578. BABYLON.serializeAsTexture(),
  39579. BABYLON.expandToProperty(null, "_ambientTexture")
  39580. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39581. __decorate([
  39582. BABYLON.serialize(),
  39583. BABYLON.expandToProperty(null, "_alphaCutOff")
  39584. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39585. __decorate([
  39586. BABYLON.serialize()
  39587. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  39588. __decorate([
  39589. BABYLON.serialize()
  39590. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39591. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39592. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39593. })(BABYLON || (BABYLON = {}));
  39594. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39595. var BABYLON;
  39596. (function (BABYLON) {
  39597. /**
  39598. * The Physically based material of BJS.
  39599. *
  39600. * This offers the main features of a standard PBR material.
  39601. * For more information, please refer to the documentation :
  39602. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39603. */
  39604. var PBRMaterial = (function (_super) {
  39605. __extends(PBRMaterial, _super);
  39606. /**
  39607. * Instantiates a new PBRMaterial instance.
  39608. *
  39609. * @param name The material name
  39610. * @param scene The scene the material will be use in.
  39611. */
  39612. function PBRMaterial(name, scene) {
  39613. var _this = _super.call(this, name, scene) || this;
  39614. /**
  39615. * Intensity of the direct lights e.g. the four lights available in your scene.
  39616. * This impacts both the direct diffuse and specular highlights.
  39617. */
  39618. _this.directIntensity = 1.0;
  39619. /**
  39620. * Intensity of the emissive part of the material.
  39621. * This helps controlling the emissive effect without modifying the emissive color.
  39622. */
  39623. _this.emissiveIntensity = 1.0;
  39624. /**
  39625. * Intensity of the environment e.g. how much the environment will light the object
  39626. * either through harmonics for rough material or through the refelction for shiny ones.
  39627. */
  39628. _this.environmentIntensity = 1.0;
  39629. /**
  39630. * This is a special control allowing the reduction of the specular highlights coming from the
  39631. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39632. */
  39633. _this.specularIntensity = 1.0;
  39634. /**
  39635. * Debug Control allowing disabling the bump map on this material.
  39636. */
  39637. _this.disableBumpMap = false;
  39638. /**
  39639. * The camera exposure used on this material.
  39640. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39641. * This corresponds to a photographic exposure.
  39642. */
  39643. _this.cameraExposure = 1.0;
  39644. /**
  39645. * The camera contrast used on this material.
  39646. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  39647. */
  39648. _this.cameraContrast = 1.0;
  39649. /**
  39650. * Color Grading 2D Lookup Texture.
  39651. * This allows special effects like sepia, black and white to sixties rendering style.
  39652. */
  39653. _this.cameraColorGradingTexture = null;
  39654. /**
  39655. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39656. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39657. * 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;
  39658. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39659. */
  39660. _this.cameraColorCurves = null;
  39661. /**
  39662. * AKA Occlusion Texture Intensity in other nomenclature.
  39663. */
  39664. _this.ambientTextureStrength = 1.0;
  39665. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39666. /**
  39667. * AKA Diffuse Color in other nomenclature.
  39668. */
  39669. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39670. /**
  39671. * AKA Specular Color in other nomenclature.
  39672. */
  39673. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39674. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39675. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39676. /**
  39677. * AKA Glossiness in other nomenclature.
  39678. */
  39679. _this.microSurface = 0.9;
  39680. /**
  39681. * source material index of refraction (IOR)' / 'destination material IOR.
  39682. */
  39683. _this.indexOfRefraction = 0.66;
  39684. /**
  39685. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39686. */
  39687. _this.invertRefractionY = false;
  39688. /**
  39689. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39690. * Materials half opaque for instance using refraction could benefit from this control.
  39691. */
  39692. _this.linkRefractionWithTransparency = false;
  39693. _this.useLightmapAsShadowmap = false;
  39694. /**
  39695. * In this mode, the emissive informtaion will always be added to the lighting once.
  39696. * A light for instance can be thought as emissive.
  39697. */
  39698. _this.useEmissiveAsIllumination = false;
  39699. /**
  39700. * Secifies that the alpha is coming form the albedo channel alpha channel.
  39701. */
  39702. _this.useAlphaFromAlbedoTexture = false;
  39703. /**
  39704. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39705. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39706. */
  39707. _this.useSpecularOverAlpha = true;
  39708. /**
  39709. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39710. */
  39711. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39712. /**
  39713. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39714. */
  39715. _this.useRoughnessFromMetallicTextureAlpha = true;
  39716. /**
  39717. * Specifies if the metallic texture contains the roughness information in its green channel.
  39718. */
  39719. _this.useRoughnessFromMetallicTextureGreen = false;
  39720. /**
  39721. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39722. */
  39723. _this.useMetallnessFromMetallicTextureBlue = false;
  39724. /**
  39725. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39726. */
  39727. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39728. /**
  39729. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39730. */
  39731. _this.useAmbientInGrayScale = false;
  39732. /**
  39733. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39734. * The material will try to infer what glossiness each pixel should be.
  39735. */
  39736. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39737. /**
  39738. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  39739. * the creation of the material.
  39740. */
  39741. _this.useScalarInLinearSpace = false;
  39742. /**
  39743. * BJS is using an harcoded light falloff based on a manually sets up range.
  39744. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39745. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39746. */
  39747. _this.usePhysicalLightFalloff = true;
  39748. /**
  39749. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39750. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39751. */
  39752. _this.useRadianceOverAlpha = true;
  39753. /**
  39754. * Allows using the bump map in parallax mode.
  39755. */
  39756. _this.useParallax = false;
  39757. /**
  39758. * Allows using the bump map in parallax occlusion mode.
  39759. */
  39760. _this.useParallaxOcclusion = false;
  39761. /**
  39762. * Controls the scale bias of the parallax mode.
  39763. */
  39764. _this.parallaxScaleBias = 0.05;
  39765. /**
  39766. * If sets to true, disables all the lights affecting the material.
  39767. */
  39768. _this.disableLighting = false;
  39769. /**
  39770. * Number of Simultaneous lights allowed on the material.
  39771. */
  39772. _this.maxSimultaneousLights = 4;
  39773. /**
  39774. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39775. */
  39776. _this.invertNormalMapX = false;
  39777. /**
  39778. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39779. */
  39780. _this.invertNormalMapY = false;
  39781. /**
  39782. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39783. */
  39784. _this.twoSidedLighting = false;
  39785. return _this;
  39786. }
  39787. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39788. /**
  39789. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39790. */
  39791. get: function () {
  39792. return this._PBRMATERIAL_OPAQUE;
  39793. },
  39794. enumerable: true,
  39795. configurable: true
  39796. });
  39797. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39798. /**
  39799. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39800. */
  39801. get: function () {
  39802. return this._PBRMATERIAL_ALPHATEST;
  39803. },
  39804. enumerable: true,
  39805. configurable: true
  39806. });
  39807. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39808. /**
  39809. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39810. */
  39811. get: function () {
  39812. return this._PBRMATERIAL_ALPHABLEND;
  39813. },
  39814. enumerable: true,
  39815. configurable: true
  39816. });
  39817. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39818. /**
  39819. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39820. * They are also discarded below the alpha cutoff threshold to improve performances.
  39821. */
  39822. get: function () {
  39823. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39824. },
  39825. enumerable: true,
  39826. configurable: true
  39827. });
  39828. PBRMaterial.prototype.getClassName = function () {
  39829. return "PBRMaterial";
  39830. };
  39831. PBRMaterial.prototype.clone = function (name) {
  39832. var _this = this;
  39833. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39834. };
  39835. PBRMaterial.prototype.serialize = function () {
  39836. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39837. serializationObject.customType = "BABYLON.PBRMaterial";
  39838. return serializationObject;
  39839. };
  39840. // Statics
  39841. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39842. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39843. };
  39844. return PBRMaterial;
  39845. }(BABYLON.PBRBaseMaterial));
  39846. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39847. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39848. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39849. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39850. __decorate([
  39851. BABYLON.serialize(),
  39852. BABYLON.expandToProperty(null)
  39853. ], PBRMaterial.prototype, "directIntensity", void 0);
  39854. __decorate([
  39855. BABYLON.serialize(),
  39856. BABYLON.expandToProperty(null)
  39857. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39858. __decorate([
  39859. BABYLON.serialize(),
  39860. BABYLON.expandToProperty(null)
  39861. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39862. __decorate([
  39863. BABYLON.serialize(),
  39864. BABYLON.expandToProperty(null)
  39865. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39866. __decorate([
  39867. BABYLON.serialize(),
  39868. BABYLON.expandToProperty(null)
  39869. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39870. __decorate([
  39871. BABYLON.serialize(),
  39872. BABYLON.expandToProperty(null)
  39873. ], PBRMaterial.prototype, "cameraExposure", void 0);
  39874. __decorate([
  39875. BABYLON.serialize(),
  39876. BABYLON.expandToProperty(null)
  39877. ], PBRMaterial.prototype, "cameraContrast", void 0);
  39878. __decorate([
  39879. BABYLON.serializeAsTexture(),
  39880. BABYLON.expandToProperty(null)
  39881. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  39882. __decorate([
  39883. BABYLON.serializeAsColorCurves(),
  39884. BABYLON.expandToProperty(null)
  39885. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  39886. __decorate([
  39887. BABYLON.serializeAsTexture(),
  39888. BABYLON.expandToProperty(null)
  39889. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39890. __decorate([
  39891. BABYLON.serializeAsTexture(),
  39892. BABYLON.expandToProperty(null)
  39893. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39894. __decorate([
  39895. BABYLON.serialize(),
  39896. BABYLON.expandToProperty(null)
  39897. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39898. __decorate([
  39899. BABYLON.serializeAsTexture(),
  39900. BABYLON.expandToProperty(null)
  39901. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39902. __decorate([
  39903. BABYLON.serializeAsTexture(),
  39904. BABYLON.expandToProperty(null)
  39905. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39906. __decorate([
  39907. BABYLON.serializeAsTexture(),
  39908. BABYLON.expandToProperty(null)
  39909. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39910. __decorate([
  39911. BABYLON.serializeAsTexture(),
  39912. BABYLON.expandToProperty(null)
  39913. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39914. __decorate([
  39915. BABYLON.serializeAsTexture(),
  39916. BABYLON.expandToProperty(null)
  39917. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39918. __decorate([
  39919. BABYLON.serialize(),
  39920. BABYLON.expandToProperty(null)
  39921. ], PBRMaterial.prototype, "metallic", void 0);
  39922. __decorate([
  39923. BABYLON.serialize(),
  39924. BABYLON.expandToProperty(null)
  39925. ], PBRMaterial.prototype, "roughness", void 0);
  39926. __decorate([
  39927. BABYLON.serializeAsTexture(),
  39928. BABYLON.expandToProperty(null)
  39929. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39930. __decorate([
  39931. BABYLON.serializeAsTexture(),
  39932. BABYLON.expandToProperty(null)
  39933. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39934. __decorate([
  39935. BABYLON.serializeAsTexture(),
  39936. BABYLON.expandToProperty(null)
  39937. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39938. __decorate([
  39939. BABYLON.serializeAsTexture(),
  39940. BABYLON.expandToProperty(null)
  39941. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39942. __decorate([
  39943. BABYLON.serializeAsColor3("ambient"),
  39944. BABYLON.expandToProperty(null)
  39945. ], PBRMaterial.prototype, "ambientColor", void 0);
  39946. __decorate([
  39947. BABYLON.serializeAsColor3("albedo"),
  39948. BABYLON.expandToProperty(null)
  39949. ], PBRMaterial.prototype, "albedoColor", void 0);
  39950. __decorate([
  39951. BABYLON.serializeAsColor3("reflectivity"),
  39952. BABYLON.expandToProperty(null)
  39953. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39954. __decorate([
  39955. BABYLON.serializeAsColor3("reflection"),
  39956. BABYLON.expandToProperty(null)
  39957. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39958. __decorate([
  39959. BABYLON.serializeAsColor3("emissive"),
  39960. BABYLON.expandToProperty(null)
  39961. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39962. __decorate([
  39963. BABYLON.serialize(),
  39964. BABYLON.expandToProperty(null)
  39965. ], PBRMaterial.prototype, "microSurface", void 0);
  39966. __decorate([
  39967. BABYLON.serialize(),
  39968. BABYLON.expandToProperty(null)
  39969. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39970. __decorate([
  39971. BABYLON.serialize(),
  39972. BABYLON.expandToProperty(null)
  39973. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39974. __decorate([
  39975. BABYLON.serializeAsFresnelParameters(),
  39976. BABYLON.expandToProperty(null)
  39977. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  39978. __decorate([
  39979. BABYLON.serializeAsFresnelParameters(),
  39980. BABYLON.expandToProperty(null)
  39981. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  39982. __decorate([
  39983. BABYLON.serialize(),
  39984. BABYLON.expandToProperty(null)
  39985. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39986. __decorate([
  39987. BABYLON.serialize(),
  39988. BABYLON.expandToProperty(null)
  39989. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39990. __decorate([
  39991. BABYLON.serialize(),
  39992. BABYLON.expandToProperty(null)
  39993. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39994. __decorate([
  39995. BABYLON.serialize(),
  39996. BABYLON.expandToProperty(null)
  39997. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39998. __decorate([
  39999. BABYLON.serialize(),
  40000. BABYLON.expandToProperty(null)
  40001. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  40002. __decorate([
  40003. BABYLON.serialize(),
  40004. BABYLON.expandToProperty(null)
  40005. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  40006. __decorate([
  40007. BABYLON.serialize(),
  40008. BABYLON.expandToProperty(null)
  40009. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  40010. __decorate([
  40011. BABYLON.serialize(),
  40012. BABYLON.expandToProperty(null)
  40013. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  40014. __decorate([
  40015. BABYLON.serialize(),
  40016. BABYLON.expandToProperty(null)
  40017. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  40018. __decorate([
  40019. BABYLON.serialize(),
  40020. BABYLON.expandToProperty(null)
  40021. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  40022. __decorate([
  40023. BABYLON.serialize(),
  40024. BABYLON.expandToProperty(null)
  40025. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  40026. __decorate([
  40027. BABYLON.serialize(),
  40028. BABYLON.expandToProperty(null)
  40029. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  40030. __decorate([
  40031. BABYLON.serialize(),
  40032. BABYLON.expandToProperty(null)
  40033. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  40034. __decorate([
  40035. BABYLON.serialize(),
  40036. BABYLON.expandToProperty(null)
  40037. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  40038. __decorate([
  40039. BABYLON.serialize(),
  40040. BABYLON.expandToProperty(null)
  40041. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  40042. __decorate([
  40043. BABYLON.serialize(),
  40044. BABYLON.expandToProperty(null)
  40045. ], PBRMaterial.prototype, "useParallax", void 0);
  40046. __decorate([
  40047. BABYLON.serialize(),
  40048. BABYLON.expandToProperty(null)
  40049. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  40050. __decorate([
  40051. BABYLON.serialize(),
  40052. BABYLON.expandToProperty(null)
  40053. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  40054. __decorate([
  40055. BABYLON.serialize(),
  40056. BABYLON.expandToProperty(null)
  40057. ], PBRMaterial.prototype, "disableLighting", void 0);
  40058. __decorate([
  40059. BABYLON.serialize(),
  40060. BABYLON.expandToProperty(null)
  40061. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  40062. __decorate([
  40063. BABYLON.serialize(),
  40064. BABYLON.expandToProperty(null)
  40065. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  40066. __decorate([
  40067. BABYLON.serialize(),
  40068. BABYLON.expandToProperty(null)
  40069. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  40070. __decorate([
  40071. BABYLON.serialize(),
  40072. BABYLON.expandToProperty(null)
  40073. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  40074. BABYLON.PBRMaterial = PBRMaterial;
  40075. })(BABYLON || (BABYLON = {}));
  40076. //# sourceMappingURL=babylon.pbrMaterial.js.map
  40077. var BABYLON;
  40078. (function (BABYLON) {
  40079. /**
  40080. * The PBR material of BJS following the metal roughness convention.
  40081. *
  40082. * This fits to the define PBR convention in the GLTF definition:
  40083. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  40084. */
  40085. var PBRMetallicRoughnessMaterial = (function (_super) {
  40086. __extends(PBRMetallicRoughnessMaterial, _super);
  40087. /**
  40088. * Instantiates a new PBRMetalRoughnessMaterial instance.
  40089. *
  40090. * @param name The material name
  40091. * @param scene The scene the material will be use in.
  40092. */
  40093. function PBRMetallicRoughnessMaterial(name, scene) {
  40094. var _this = _super.call(this, name, scene) || this;
  40095. _this._useRoughnessFromMetallicTextureGreen = true;
  40096. _this._useMetallnessFromMetallicTextureBlue = true;
  40097. return _this;
  40098. }
  40099. /**
  40100. * Return the currrent class name of the material.
  40101. */
  40102. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  40103. return "PBRMetallicRoughnessMaterial";
  40104. };
  40105. /**
  40106. * Serialize the material to a parsable JSON object.
  40107. */
  40108. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  40109. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40110. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  40111. return serializationObject;
  40112. };
  40113. /**
  40114. * Parses a JSON object correponding to the serialize function.
  40115. */
  40116. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  40117. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  40118. };
  40119. return PBRMetallicRoughnessMaterial;
  40120. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  40121. __decorate([
  40122. BABYLON.serializeAsTexture(),
  40123. BABYLON.expandToProperty(null, "_albedoColor")
  40124. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  40125. __decorate([
  40126. BABYLON.serializeAsTexture(),
  40127. BABYLON.expandToProperty(null, "_albedoTexture")
  40128. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  40129. __decorate([
  40130. BABYLON.serialize(),
  40131. BABYLON.expandToProperty(null)
  40132. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40133. __decorate([
  40134. BABYLON.serialize(),
  40135. BABYLON.expandToProperty(null)
  40136. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40137. __decorate([
  40138. BABYLON.serializeAsTexture(),
  40139. BABYLON.expandToProperty(null, "_metallicTexture")
  40140. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40141. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40142. })(BABYLON || (BABYLON = {}));
  40143. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40144. var BABYLON;
  40145. (function (BABYLON) {
  40146. /**
  40147. * The PBR material of BJS following the specular glossiness convention.
  40148. *
  40149. * This fits to the define PBR convention in the GLTF definition:
  40150. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40151. */
  40152. var PBRSpecularGlossinessMaterial = (function (_super) {
  40153. __extends(PBRSpecularGlossinessMaterial, _super);
  40154. /**
  40155. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40156. *
  40157. * @param name The material name
  40158. * @param scene The scene the material will be use in.
  40159. */
  40160. function PBRSpecularGlossinessMaterial(name, scene) {
  40161. var _this = _super.call(this, name, scene) || this;
  40162. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40163. return _this;
  40164. }
  40165. /**
  40166. * Return the currrent class name of the material.
  40167. */
  40168. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40169. return "PBRSpecularGlossinessMaterial";
  40170. };
  40171. /**
  40172. * Serialize the material to a parsable JSON object.
  40173. */
  40174. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40175. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40176. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40177. return serializationObject;
  40178. };
  40179. /**
  40180. * Parses a JSON object correponding to the serialize function.
  40181. */
  40182. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40183. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40184. };
  40185. return PBRSpecularGlossinessMaterial;
  40186. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  40187. __decorate([
  40188. BABYLON.serializeAsColor3(),
  40189. BABYLON.expandToProperty(null, "_albedoColor")
  40190. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40191. __decorate([
  40192. BABYLON.serializeAsTexture(),
  40193. BABYLON.expandToProperty(null, "_albedoTexture")
  40194. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40195. __decorate([
  40196. BABYLON.serializeAsColor3(),
  40197. BABYLON.expandToProperty(null, "_reflectivityColor")
  40198. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40199. __decorate([
  40200. BABYLON.serialize(),
  40201. BABYLON.expandToProperty(null, "_microSurface")
  40202. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40203. __decorate([
  40204. BABYLON.serializeAsTexture(),
  40205. BABYLON.expandToProperty(null, "_reflectivityTexture")
  40206. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40207. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40208. })(BABYLON || (BABYLON = {}));
  40209. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40210. var BABYLON;
  40211. (function (BABYLON) {
  40212. var ShadowLight = (function (_super) {
  40213. __extends(ShadowLight, _super);
  40214. function ShadowLight() {
  40215. var _this = _super !== null && _super.apply(this, arguments) || this;
  40216. _this._needProjectionMatrixCompute = true;
  40217. return _this;
  40218. }
  40219. Object.defineProperty(ShadowLight.prototype, "direction", {
  40220. get: function () {
  40221. return this._direction;
  40222. },
  40223. set: function (value) {
  40224. this._direction = value;
  40225. },
  40226. enumerable: true,
  40227. configurable: true
  40228. });
  40229. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40230. get: function () {
  40231. return this._shadowMinZ;
  40232. },
  40233. set: function (value) {
  40234. this._shadowMinZ = value;
  40235. this.forceProjectionMatrixCompute();
  40236. },
  40237. enumerable: true,
  40238. configurable: true
  40239. });
  40240. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40241. get: function () {
  40242. return this._shadowMaxZ;
  40243. },
  40244. set: function (value) {
  40245. this._shadowMaxZ = value;
  40246. this.forceProjectionMatrixCompute();
  40247. },
  40248. enumerable: true,
  40249. configurable: true
  40250. });
  40251. /**
  40252. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40253. */
  40254. ShadowLight.prototype.computeTransformedInformation = function () {
  40255. if (this.parent && this.parent.getWorldMatrix) {
  40256. if (!this.transformedPosition) {
  40257. this.transformedPosition = BABYLON.Vector3.Zero();
  40258. }
  40259. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40260. // In case the direction is present.
  40261. if (this.direction) {
  40262. if (!this.transformedDirection) {
  40263. this.transformedDirection = BABYLON.Vector3.Zero();
  40264. }
  40265. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40266. }
  40267. return true;
  40268. }
  40269. return false;
  40270. };
  40271. /**
  40272. * Return the depth scale used for the shadow map.
  40273. */
  40274. ShadowLight.prototype.getDepthScale = function () {
  40275. return 30.0;
  40276. };
  40277. /**
  40278. * Returns the light direction (Vector3) for any passed face index.
  40279. */
  40280. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40281. return this.transformedDirection ? this.transformedDirection : this.direction;
  40282. };
  40283. /**
  40284. * Returns the DirectionalLight absolute position in the World.
  40285. */
  40286. ShadowLight.prototype.getAbsolutePosition = function () {
  40287. return this.transformedPosition ? this.transformedPosition : this.position;
  40288. };
  40289. /**
  40290. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40291. * Returns the updated DirectionalLight direction (Vector3).
  40292. */
  40293. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40294. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40295. return this.direction;
  40296. };
  40297. /**
  40298. * Returns the light rotation (Vector3).
  40299. */
  40300. ShadowLight.prototype.getRotation = function () {
  40301. this.direction.normalize();
  40302. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40303. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40304. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40305. };
  40306. /**
  40307. * Boolean : false by default.
  40308. */
  40309. ShadowLight.prototype.needCube = function () {
  40310. return false;
  40311. };
  40312. /**
  40313. * Specifies wether or not the projection matrix should be recomputed this frame.
  40314. */
  40315. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40316. return this._needProjectionMatrixCompute;
  40317. };
  40318. /**
  40319. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40320. */
  40321. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40322. this._needProjectionMatrixCompute = true;
  40323. };
  40324. /**
  40325. * Get the world matrix of the sahdow lights.
  40326. */
  40327. ShadowLight.prototype._getWorldMatrix = function () {
  40328. if (!this._worldMatrix) {
  40329. this._worldMatrix = BABYLON.Matrix.Identity();
  40330. }
  40331. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40332. return this._worldMatrix;
  40333. };
  40334. /**
  40335. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40336. * Returns the light.
  40337. */
  40338. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40339. if (this.customProjectionMatrixBuilder) {
  40340. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40341. }
  40342. else {
  40343. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40344. }
  40345. return this;
  40346. };
  40347. return ShadowLight;
  40348. }(BABYLON.Light));
  40349. __decorate([
  40350. BABYLON.serializeAsVector3()
  40351. ], ShadowLight.prototype, "position", void 0);
  40352. __decorate([
  40353. BABYLON.serializeAsVector3()
  40354. ], ShadowLight.prototype, "direction", null);
  40355. __decorate([
  40356. BABYLON.serialize()
  40357. ], ShadowLight.prototype, "shadowMinZ", null);
  40358. __decorate([
  40359. BABYLON.serialize()
  40360. ], ShadowLight.prototype, "shadowMaxZ", null);
  40361. BABYLON.ShadowLight = ShadowLight;
  40362. })(BABYLON || (BABYLON = {}));
  40363. //# sourceMappingURL=babylon.shadowLight.js.map
  40364. var BABYLON;
  40365. (function (BABYLON) {
  40366. var PointLight = (function (_super) {
  40367. __extends(PointLight, _super);
  40368. /**
  40369. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40370. * A PointLight emits the light in every direction.
  40371. * It can cast shadows.
  40372. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40373. * ```javascript
  40374. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40375. * ```
  40376. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40377. */
  40378. function PointLight(name, position, scene) {
  40379. var _this = _super.call(this, name, scene) || this;
  40380. _this._shadowAngle = Math.PI / 2;
  40381. _this.position = position;
  40382. return _this;
  40383. }
  40384. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40385. /**
  40386. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40387. * This specifies what angle the shadow will use to be created.
  40388. *
  40389. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40390. */
  40391. get: function () {
  40392. return this._shadowAngle;
  40393. },
  40394. /**
  40395. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40396. * This specifies what angle the shadow will use to be created.
  40397. *
  40398. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40399. */
  40400. set: function (value) {
  40401. this._shadowAngle = value;
  40402. this.forceProjectionMatrixCompute();
  40403. },
  40404. enumerable: true,
  40405. configurable: true
  40406. });
  40407. Object.defineProperty(PointLight.prototype, "direction", {
  40408. get: function () {
  40409. return this._direction;
  40410. },
  40411. /**
  40412. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40413. */
  40414. set: function (value) {
  40415. var previousNeedCube = this.needCube();
  40416. this._direction = value;
  40417. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40418. this._shadowGenerator.recreateShadowMap();
  40419. }
  40420. },
  40421. enumerable: true,
  40422. configurable: true
  40423. });
  40424. /**
  40425. * Returns the string "PointLight"
  40426. */
  40427. PointLight.prototype.getClassName = function () {
  40428. return "PointLight";
  40429. };
  40430. /**
  40431. * Returns the integer 0.
  40432. */
  40433. PointLight.prototype.getTypeID = function () {
  40434. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40435. };
  40436. /**
  40437. * Specifies wether or not the shadowmap should be a cube texture.
  40438. */
  40439. PointLight.prototype.needCube = function () {
  40440. return !this.direction;
  40441. };
  40442. /**
  40443. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40444. */
  40445. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40446. if (this.direction) {
  40447. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40448. }
  40449. else {
  40450. switch (faceIndex) {
  40451. case 0:
  40452. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40453. case 1:
  40454. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40455. case 2:
  40456. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40457. case 3:
  40458. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40459. case 4:
  40460. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40461. case 5:
  40462. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40463. }
  40464. }
  40465. return BABYLON.Vector3.Zero();
  40466. };
  40467. /**
  40468. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40469. * - fov = PI / 2
  40470. * - aspect ratio : 1.0
  40471. * - z-near and far equal to the active camera minZ and maxZ.
  40472. * Returns the PointLight.
  40473. */
  40474. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40475. var activeCamera = this.getScene().activeCamera;
  40476. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40477. };
  40478. PointLight.prototype._buildUniformLayout = function () {
  40479. this._uniformBuffer.addUniform("vLightData", 4);
  40480. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40481. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40482. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40483. this._uniformBuffer.create();
  40484. };
  40485. /**
  40486. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40487. * Returns the PointLight.
  40488. */
  40489. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40490. if (this.computeTransformedInformation()) {
  40491. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40492. return this;
  40493. }
  40494. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40495. return this;
  40496. };
  40497. return PointLight;
  40498. }(BABYLON.ShadowLight));
  40499. __decorate([
  40500. BABYLON.serialize()
  40501. ], PointLight.prototype, "shadowAngle", null);
  40502. BABYLON.PointLight = PointLight;
  40503. })(BABYLON || (BABYLON = {}));
  40504. //# sourceMappingURL=babylon.pointLight.js.map
  40505. /// <reference path="babylon.light.ts" />
  40506. var BABYLON;
  40507. (function (BABYLON) {
  40508. var DirectionalLight = (function (_super) {
  40509. __extends(DirectionalLight, _super);
  40510. /**
  40511. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40512. * The directional light is emitted from everywhere in the given direction.
  40513. * It can cast shawdows.
  40514. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40515. */
  40516. function DirectionalLight(name, direction, scene) {
  40517. var _this = _super.call(this, name, scene) || this;
  40518. _this._shadowFrustumSize = 0;
  40519. _this._shadowOrthoScale = 0.5;
  40520. _this.autoUpdateExtends = true;
  40521. // Cache
  40522. _this._orthoLeft = Number.MAX_VALUE;
  40523. _this._orthoRight = Number.MIN_VALUE;
  40524. _this._orthoTop = Number.MIN_VALUE;
  40525. _this._orthoBottom = Number.MAX_VALUE;
  40526. _this.position = direction.scale(-1.0);
  40527. _this.direction = direction;
  40528. return _this;
  40529. }
  40530. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  40531. /**
  40532. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  40533. */
  40534. get: function () {
  40535. return this._shadowFrustumSize;
  40536. },
  40537. /**
  40538. * Specifies a fix frustum size for the shadow generation.
  40539. */
  40540. set: function (value) {
  40541. this._shadowFrustumSize = value;
  40542. this.forceProjectionMatrixCompute();
  40543. },
  40544. enumerable: true,
  40545. configurable: true
  40546. });
  40547. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40548. get: function () {
  40549. return this._shadowOrthoScale;
  40550. },
  40551. set: function (value) {
  40552. this._shadowOrthoScale = value;
  40553. this.forceProjectionMatrixCompute();
  40554. },
  40555. enumerable: true,
  40556. configurable: true
  40557. });
  40558. /**
  40559. * Returns the string "DirectionalLight".
  40560. */
  40561. DirectionalLight.prototype.getClassName = function () {
  40562. return "DirectionalLight";
  40563. };
  40564. /**
  40565. * Returns the integer 1.
  40566. */
  40567. DirectionalLight.prototype.getTypeID = function () {
  40568. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40569. };
  40570. /**
  40571. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40572. * Returns the DirectionalLight Shadow projection matrix.
  40573. */
  40574. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40575. if (this.shadowFrustumSize > 0) {
  40576. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  40577. }
  40578. else {
  40579. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40580. }
  40581. };
  40582. /**
  40583. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  40584. * Returns the DirectionalLight Shadow projection matrix.
  40585. */
  40586. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  40587. var activeCamera = this.getScene().activeCamera;
  40588. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40589. };
  40590. /**
  40591. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  40592. * Returns the DirectionalLight Shadow projection matrix.
  40593. */
  40594. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40595. var activeCamera = this.getScene().activeCamera;
  40596. // Check extends
  40597. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40598. var tempVector3 = BABYLON.Vector3.Zero();
  40599. this._orthoLeft = Number.MAX_VALUE;
  40600. this._orthoRight = Number.MIN_VALUE;
  40601. this._orthoTop = Number.MIN_VALUE;
  40602. this._orthoBottom = Number.MAX_VALUE;
  40603. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40604. var mesh = renderList[meshIndex];
  40605. if (!mesh) {
  40606. continue;
  40607. }
  40608. var boundingInfo = mesh.getBoundingInfo();
  40609. if (!boundingInfo) {
  40610. continue;
  40611. }
  40612. var boundingBox = boundingInfo.boundingBox;
  40613. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40614. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40615. if (tempVector3.x < this._orthoLeft)
  40616. this._orthoLeft = tempVector3.x;
  40617. if (tempVector3.y < this._orthoBottom)
  40618. this._orthoBottom = tempVector3.y;
  40619. if (tempVector3.x > this._orthoRight)
  40620. this._orthoRight = tempVector3.x;
  40621. if (tempVector3.y > this._orthoTop)
  40622. this._orthoTop = tempVector3.y;
  40623. }
  40624. }
  40625. }
  40626. var xOffset = this._orthoRight - this._orthoLeft;
  40627. var yOffset = this._orthoTop - this._orthoBottom;
  40628. 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);
  40629. };
  40630. DirectionalLight.prototype._buildUniformLayout = function () {
  40631. this._uniformBuffer.addUniform("vLightData", 4);
  40632. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40633. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40634. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40635. this._uniformBuffer.create();
  40636. };
  40637. /**
  40638. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40639. * Returns the DirectionalLight.
  40640. */
  40641. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40642. if (this.computeTransformedInformation()) {
  40643. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40644. return this;
  40645. }
  40646. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40647. return this;
  40648. };
  40649. return DirectionalLight;
  40650. }(BABYLON.ShadowLight));
  40651. __decorate([
  40652. BABYLON.serialize()
  40653. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  40654. __decorate([
  40655. BABYLON.serialize()
  40656. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40657. __decorate([
  40658. BABYLON.serialize()
  40659. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40660. BABYLON.DirectionalLight = DirectionalLight;
  40661. })(BABYLON || (BABYLON = {}));
  40662. //# sourceMappingURL=babylon.directionalLight.js.map
  40663. var BABYLON;
  40664. (function (BABYLON) {
  40665. var SpotLight = (function (_super) {
  40666. __extends(SpotLight, _super);
  40667. /**
  40668. * Creates a SpotLight object in the scene with the passed parameters :
  40669. * - `position` (Vector3) is the initial SpotLight position,
  40670. * - `direction` (Vector3) is the initial SpotLight direction,
  40671. * - `angle` (float, in radians) is the spot light cone angle,
  40672. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40673. * A spot light is a simply light oriented cone.
  40674. * It can cast shadows.
  40675. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40676. */
  40677. function SpotLight(name, position, direction, angle, exponent, scene) {
  40678. var _this = _super.call(this, name, scene) || this;
  40679. _this.position = position;
  40680. _this.direction = direction;
  40681. _this.angle = angle;
  40682. _this.exponent = exponent;
  40683. return _this;
  40684. }
  40685. Object.defineProperty(SpotLight.prototype, "angle", {
  40686. get: function () {
  40687. return this._angle;
  40688. },
  40689. set: function (value) {
  40690. this._angle = value;
  40691. this.forceProjectionMatrixCompute();
  40692. },
  40693. enumerable: true,
  40694. configurable: true
  40695. });
  40696. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  40697. get: function () {
  40698. return this._shadowAngleScale;
  40699. },
  40700. /**
  40701. * Allows scaling the angle of the light for shadow generation only.
  40702. */
  40703. set: function (value) {
  40704. this._shadowAngleScale = value;
  40705. this.forceProjectionMatrixCompute();
  40706. },
  40707. enumerable: true,
  40708. configurable: true
  40709. });
  40710. /**
  40711. * Returns the string "SpotLight".
  40712. */
  40713. SpotLight.prototype.getClassName = function () {
  40714. return "SpotLight";
  40715. };
  40716. /**
  40717. * Returns the integer 2.
  40718. */
  40719. SpotLight.prototype.getTypeID = function () {
  40720. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40721. };
  40722. /**
  40723. * 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.
  40724. * Returns the SpotLight.
  40725. */
  40726. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40727. var activeCamera = this.getScene().activeCamera;
  40728. this._shadowAngleScale = this._shadowAngleScale || 1;
  40729. var angle = this._shadowAngleScale * this._angle;
  40730. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40731. };
  40732. SpotLight.prototype._buildUniformLayout = function () {
  40733. this._uniformBuffer.addUniform("vLightData", 4);
  40734. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40735. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40736. this._uniformBuffer.addUniform("vLightDirection", 3);
  40737. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40738. this._uniformBuffer.create();
  40739. };
  40740. /**
  40741. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40742. * Return the SpotLight.
  40743. */
  40744. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40745. var normalizeDirection;
  40746. if (this.computeTransformedInformation()) {
  40747. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40748. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40749. }
  40750. else {
  40751. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40752. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40753. }
  40754. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40755. return this;
  40756. };
  40757. return SpotLight;
  40758. }(BABYLON.ShadowLight));
  40759. __decorate([
  40760. BABYLON.serialize()
  40761. ], SpotLight.prototype, "angle", null);
  40762. __decorate([
  40763. BABYLON.serialize()
  40764. /**
  40765. * Allows scaling the angle of the light for shadow generation only.
  40766. */
  40767. ], SpotLight.prototype, "shadowAngleScale", null);
  40768. __decorate([
  40769. BABYLON.serialize()
  40770. ], SpotLight.prototype, "exponent", void 0);
  40771. BABYLON.SpotLight = SpotLight;
  40772. })(BABYLON || (BABYLON = {}));
  40773. //# sourceMappingURL=babylon.spotLight.js.map
  40774. var BABYLON;
  40775. (function (BABYLON) {
  40776. var PostProcess = (function () {
  40777. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  40778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40779. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40780. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  40781. if (blockCompilation === void 0) { blockCompilation = false; }
  40782. this.name = name;
  40783. this.width = -1;
  40784. this.height = -1;
  40785. this.autoClear = true;
  40786. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  40787. /*
  40788. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40789. Can only be used on a single postprocess or on the last one of a chain.
  40790. */
  40791. this.enablePixelPerfectMode = false;
  40792. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  40793. this.alwaysForcePOT = false;
  40794. this.samples = 1;
  40795. this._reusable = false;
  40796. this._textures = new BABYLON.SmartArray(2);
  40797. this._currentRenderTextureInd = 0;
  40798. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40799. this._texelSize = BABYLON.Vector2.Zero();
  40800. // Events
  40801. /**
  40802. * An event triggered when the postprocess is activated.
  40803. * @type {BABYLON.Observable}
  40804. */
  40805. this.onActivateObservable = new BABYLON.Observable();
  40806. /**
  40807. * An event triggered when the postprocess changes its size.
  40808. * @type {BABYLON.Observable}
  40809. */
  40810. this.onSizeChangedObservable = new BABYLON.Observable();
  40811. /**
  40812. * An event triggered when the postprocess applies its effect.
  40813. * @type {BABYLON.Observable}
  40814. */
  40815. this.onApplyObservable = new BABYLON.Observable();
  40816. /**
  40817. * An event triggered before rendering the postprocess
  40818. * @type {BABYLON.Observable}
  40819. */
  40820. this.onBeforeRenderObservable = new BABYLON.Observable();
  40821. /**
  40822. * An event triggered after rendering the postprocess
  40823. * @type {BABYLON.Observable}
  40824. */
  40825. this.onAfterRenderObservable = new BABYLON.Observable();
  40826. if (camera != null) {
  40827. this._camera = camera;
  40828. this._scene = camera.getScene();
  40829. camera.attachPostProcess(this);
  40830. this._engine = this._scene.getEngine();
  40831. }
  40832. else {
  40833. this._engine = engine;
  40834. }
  40835. this._options = options;
  40836. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40837. this._reusable = reusable || false;
  40838. this._textureType = textureType;
  40839. this._samplers = samplers || [];
  40840. this._samplers.push("textureSampler");
  40841. this._fragmentUrl = fragmentUrl;
  40842. this._vertexUrl = vertexUrl;
  40843. this._parameters = parameters || [];
  40844. this._parameters.push("scale");
  40845. this._indexParameters = indexParameters;
  40846. if (!blockCompilation) {
  40847. this.updateEffect(defines);
  40848. }
  40849. }
  40850. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40851. set: function (callback) {
  40852. if (this._onActivateObserver) {
  40853. this.onActivateObservable.remove(this._onActivateObserver);
  40854. }
  40855. this._onActivateObserver = this.onActivateObservable.add(callback);
  40856. },
  40857. enumerable: true,
  40858. configurable: true
  40859. });
  40860. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40861. set: function (callback) {
  40862. if (this._onSizeChangedObserver) {
  40863. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40864. }
  40865. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40866. },
  40867. enumerable: true,
  40868. configurable: true
  40869. });
  40870. Object.defineProperty(PostProcess.prototype, "onApply", {
  40871. set: function (callback) {
  40872. if (this._onApplyObserver) {
  40873. this.onApplyObservable.remove(this._onApplyObserver);
  40874. }
  40875. this._onApplyObserver = this.onApplyObservable.add(callback);
  40876. },
  40877. enumerable: true,
  40878. configurable: true
  40879. });
  40880. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40881. set: function (callback) {
  40882. if (this._onBeforeRenderObserver) {
  40883. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40884. }
  40885. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40886. },
  40887. enumerable: true,
  40888. configurable: true
  40889. });
  40890. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40891. set: function (callback) {
  40892. if (this._onAfterRenderObserver) {
  40893. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40894. }
  40895. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40896. },
  40897. enumerable: true,
  40898. configurable: true
  40899. });
  40900. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  40901. get: function () {
  40902. return this._textures.data[this._currentRenderTextureInd];
  40903. },
  40904. set: function (value) {
  40905. this._forcedOutputTexture = value;
  40906. },
  40907. enumerable: true,
  40908. configurable: true
  40909. });
  40910. PostProcess.prototype.getCamera = function () {
  40911. return this._camera;
  40912. };
  40913. Object.defineProperty(PostProcess.prototype, "texelSize", {
  40914. get: function () {
  40915. if (this._shareOutputWithPostProcess) {
  40916. return this._shareOutputWithPostProcess.texelSize;
  40917. }
  40918. if (this._forcedOutputTexture) {
  40919. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  40920. }
  40921. return this._texelSize;
  40922. },
  40923. enumerable: true,
  40924. configurable: true
  40925. });
  40926. PostProcess.prototype.getEngine = function () {
  40927. return this._engine;
  40928. };
  40929. PostProcess.prototype.shareOutputWith = function (postProcess) {
  40930. this._disposeTextures();
  40931. this._shareOutputWithPostProcess = postProcess;
  40932. return this;
  40933. };
  40934. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  40935. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  40936. };
  40937. PostProcess.prototype.isReusable = function () {
  40938. return this._reusable;
  40939. };
  40940. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40941. PostProcess.prototype.markTextureDirty = function () {
  40942. this.width = -1;
  40943. };
  40944. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  40945. var _this = this;
  40946. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  40947. camera = camera || this._camera;
  40948. var scene = camera.getScene();
  40949. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40950. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40951. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40952. var desiredWidth = this._options.width || requiredWidth;
  40953. var desiredHeight = this._options.height || requiredHeight;
  40954. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  40955. if (!this._options.width) {
  40956. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  40957. }
  40958. if (!this._options.height) {
  40959. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  40960. }
  40961. }
  40962. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40963. if (this._textures.length > 0) {
  40964. for (var i = 0; i < this._textures.length; i++) {
  40965. this._engine._releaseTexture(this._textures.data[i]);
  40966. }
  40967. this._textures.reset();
  40968. }
  40969. this.width = desiredWidth;
  40970. this.height = desiredHeight;
  40971. var textureSize = { width: this.width, height: this.height };
  40972. var textureOptions = {
  40973. generateMipMaps: false,
  40974. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  40975. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  40976. samplingMode: this.renderTargetSamplingMode,
  40977. type: this._textureType
  40978. };
  40979. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40980. if (this._reusable) {
  40981. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40982. }
  40983. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  40984. this.onSizeChangedObservable.notifyObservers(this);
  40985. }
  40986. this._textures.forEach(function (texture) {
  40987. if (texture.samples !== _this.samples) {
  40988. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40989. }
  40990. });
  40991. }
  40992. var target;
  40993. if (this._shareOutputWithPostProcess) {
  40994. target = this._shareOutputWithPostProcess.outputTexture;
  40995. }
  40996. else if (this._forcedOutputTexture) {
  40997. target = this._forcedOutputTexture;
  40998. }
  40999. else {
  41000. target = this.outputTexture;
  41001. }
  41002. if (this.enablePixelPerfectMode) {
  41003. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41004. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  41005. }
  41006. else {
  41007. this._scaleRatio.copyFromFloats(1, 1);
  41008. this._engine.bindFramebuffer(target);
  41009. }
  41010. this.onActivateObservable.notifyObservers(camera);
  41011. // Clear
  41012. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  41013. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  41014. }
  41015. if (this._reusable) {
  41016. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41017. }
  41018. };
  41019. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41020. get: function () {
  41021. return this._effect.isSupported;
  41022. },
  41023. enumerable: true,
  41024. configurable: true
  41025. });
  41026. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  41027. get: function () {
  41028. if (this._shareOutputWithPostProcess) {
  41029. return this._shareOutputWithPostProcess.aspectRatio;
  41030. }
  41031. if (this._forcedOutputTexture) {
  41032. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  41033. }
  41034. return this.width / this.height;
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. PostProcess.prototype.apply = function () {
  41040. // Check
  41041. if (!this._effect || !this._effect.isReady())
  41042. return null;
  41043. // States
  41044. this._engine.enableEffect(this._effect);
  41045. this._engine.setState(false);
  41046. this._engine.setDepthBuffer(false);
  41047. this._engine.setDepthWrite(false);
  41048. // Alpha
  41049. this._engine.setAlphaMode(this.alphaMode);
  41050. if (this.alphaConstants) {
  41051. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  41052. }
  41053. // Texture
  41054. var source;
  41055. if (this._shareOutputWithPostProcess) {
  41056. source = this._shareOutputWithPostProcess.outputTexture;
  41057. }
  41058. else if (this._forcedOutputTexture) {
  41059. source = this._forcedOutputTexture;
  41060. }
  41061. else {
  41062. source = this.outputTexture;
  41063. }
  41064. this._effect._bindTexture("textureSampler", source);
  41065. // Parameters
  41066. this._effect.setVector2("scale", this._scaleRatio);
  41067. this.onApplyObservable.notifyObservers(this._effect);
  41068. return this._effect;
  41069. };
  41070. PostProcess.prototype._disposeTextures = function () {
  41071. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  41072. return;
  41073. }
  41074. if (this._textures.length > 0) {
  41075. for (var i = 0; i < this._textures.length; i++) {
  41076. this._engine._releaseTexture(this._textures.data[i]);
  41077. }
  41078. }
  41079. this._textures.dispose();
  41080. };
  41081. PostProcess.prototype.dispose = function (camera) {
  41082. camera = camera || this._camera;
  41083. this._disposeTextures();
  41084. if (!camera) {
  41085. return;
  41086. }
  41087. camera.detachPostProcess(this);
  41088. var index = camera._postProcesses.indexOf(this);
  41089. if (index === 0 && camera._postProcesses.length > 0) {
  41090. this._camera._postProcesses[0].markTextureDirty();
  41091. }
  41092. this.onActivateObservable.clear();
  41093. this.onAfterRenderObservable.clear();
  41094. this.onApplyObservable.clear();
  41095. this.onBeforeRenderObservable.clear();
  41096. this.onSizeChangedObservable.clear();
  41097. };
  41098. return PostProcess;
  41099. }());
  41100. BABYLON.PostProcess = PostProcess;
  41101. })(BABYLON || (BABYLON = {}));
  41102. //# sourceMappingURL=babylon.postProcess.js.map
  41103. var BABYLON;
  41104. (function (BABYLON) {
  41105. var PassPostProcess = (function (_super) {
  41106. __extends(PassPostProcess, _super);
  41107. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41108. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41109. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41110. }
  41111. return PassPostProcess;
  41112. }(BABYLON.PostProcess));
  41113. BABYLON.PassPostProcess = PassPostProcess;
  41114. })(BABYLON || (BABYLON = {}));
  41115. //# sourceMappingURL=babylon.passPostProcess.js.map
  41116. var BABYLON;
  41117. (function (BABYLON) {
  41118. var BlurPostProcess = (function (_super) {
  41119. __extends(BlurPostProcess, _super);
  41120. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  41121. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41122. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41123. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  41124. _this.direction = direction;
  41125. _this.onApplyObservable.add(function (effect) {
  41126. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  41127. });
  41128. _this.kernel = kernel;
  41129. return _this;
  41130. }
  41131. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  41132. /**
  41133. * Gets the length in pixels of the blur sample region
  41134. */
  41135. get: function () {
  41136. return this._idealKernel;
  41137. },
  41138. /**
  41139. * Sets the length in pixels of the blur sample region
  41140. */
  41141. set: function (v) {
  41142. if (this._idealKernel === v) {
  41143. return;
  41144. }
  41145. v = Math.max(v, 1);
  41146. this._idealKernel = v;
  41147. this._kernel = this._nearestBestKernel(v);
  41148. this._updateParameters();
  41149. },
  41150. enumerable: true,
  41151. configurable: true
  41152. });
  41153. BlurPostProcess.prototype._updateParameters = function () {
  41154. // Generate sampling offsets and weights
  41155. var N = this._kernel;
  41156. var centerIndex = (N - 1) / 2;
  41157. // Generate Gaussian sampling weights over kernel
  41158. var offsets = [];
  41159. var weights = [];
  41160. var totalWeight = 0;
  41161. for (var i = 0; i < N; i++) {
  41162. var u = i / (N - 1);
  41163. var w = this._gaussianWeight(u * 2.0 - 1);
  41164. offsets[i] = (i - centerIndex);
  41165. weights[i] = w;
  41166. totalWeight += w;
  41167. }
  41168. // Normalize weights
  41169. for (var i = 0; i < weights.length; i++) {
  41170. weights[i] /= totalWeight;
  41171. }
  41172. // Optimize: combine samples to take advantage of hardware linear sampling
  41173. // Walk from left to center, combining pairs (symmetrically)
  41174. var linearSamplingWeights = [];
  41175. var linearSamplingOffsets = [];
  41176. var linearSamplingMap = [];
  41177. for (var i = 0; i <= centerIndex; i += 2) {
  41178. var j = Math.min(i + 1, Math.floor(centerIndex));
  41179. var singleCenterSample = i === j;
  41180. if (singleCenterSample) {
  41181. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41182. }
  41183. else {
  41184. var sharedCell = j === centerIndex;
  41185. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  41186. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  41187. if (offsetLinear === 0) {
  41188. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  41189. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  41190. }
  41191. else {
  41192. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  41193. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  41194. }
  41195. }
  41196. }
  41197. for (var i = 0; i < linearSamplingMap.length; i++) {
  41198. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  41199. linearSamplingWeights[i] = linearSamplingMap[i].w;
  41200. }
  41201. // Replace with optimized
  41202. offsets = linearSamplingOffsets;
  41203. weights = linearSamplingWeights;
  41204. // Generate shaders
  41205. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  41206. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  41207. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  41208. var defines = "";
  41209. for (var i = 0; i < varyingCount; i++) {
  41210. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  41211. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  41212. }
  41213. var depCount = 0;
  41214. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  41215. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  41216. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  41217. depCount++;
  41218. }
  41219. this.updateEffect(defines, null, null, {
  41220. varyingCount: varyingCount,
  41221. depCount: depCount
  41222. });
  41223. };
  41224. /**
  41225. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  41226. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41227. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41228. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41229. * The gaps between physical kernels are compensated for in the weighting of the samples
  41230. * @param idealKernel Ideal blur kernel.
  41231. * @return Nearest best kernel.
  41232. */
  41233. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41234. var v = Math.round(idealKernel);
  41235. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41236. var k = _a[_i];
  41237. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41238. return Math.max(k, 3);
  41239. }
  41240. }
  41241. return Math.max(v, 3);
  41242. };
  41243. /**
  41244. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41245. * @param x The point on the Gaussian distribution to sample.
  41246. * @return the value of the Gaussian function at x.
  41247. */
  41248. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41249. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41250. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41251. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41252. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41253. // truncated at around 1.3% of peak strength.
  41254. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41255. var sigma = (1 / 3);
  41256. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41257. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41258. var weight = (1.0 / denominator) * Math.exp(exponent);
  41259. return weight;
  41260. };
  41261. /**
  41262. * Generates a string that can be used as a floating point number in GLSL.
  41263. * @param x Value to print.
  41264. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41265. * @return GLSL float string.
  41266. */
  41267. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41268. if (decimalFigures === void 0) { decimalFigures = 8; }
  41269. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41270. };
  41271. return BlurPostProcess;
  41272. }(BABYLON.PostProcess));
  41273. BABYLON.BlurPostProcess = BlurPostProcess;
  41274. })(BABYLON || (BABYLON = {}));
  41275. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41276. var BABYLON;
  41277. (function (BABYLON) {
  41278. var FxaaPostProcess = (function (_super) {
  41279. __extends(FxaaPostProcess, _super);
  41280. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41281. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41282. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  41283. _this.onApplyObservable.add(function (effect) {
  41284. var texelSize = _this.texelSize;
  41285. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41286. });
  41287. return _this;
  41288. }
  41289. return FxaaPostProcess;
  41290. }(BABYLON.PostProcess));
  41291. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41292. })(BABYLON || (BABYLON = {}));
  41293. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41294. var BABYLON;
  41295. (function (BABYLON) {
  41296. var HighlightsPostProcess = (function (_super) {
  41297. __extends(HighlightsPostProcess, _super);
  41298. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41299. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41300. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41301. }
  41302. return HighlightsPostProcess;
  41303. }(BABYLON.PostProcess));
  41304. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41305. })(BABYLON || (BABYLON = {}));
  41306. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41307. var BABYLON;
  41308. (function (BABYLON) {
  41309. var ImageProcessingPostProcess = (function (_super) {
  41310. __extends(ImageProcessingPostProcess, _super);
  41311. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41313. var _this = _super.call(this, name, "imageProcessing", [
  41314. 'contrast',
  41315. 'vignetteSettings1',
  41316. 'vignetteSettings2',
  41317. 'cameraExposureLinear',
  41318. 'vCameraColorCurveNegative',
  41319. 'vCameraColorCurveNeutral',
  41320. 'vCameraColorCurvePositive',
  41321. 'colorTransformSettings'
  41322. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41323. _this.colorGradingWeight = 1.0;
  41324. _this.colorCurves = new BABYLON.ColorCurves();
  41325. _this._colorCurvesEnabled = true;
  41326. _this.cameraFov = 0.5;
  41327. _this.vignetteStretch = 0;
  41328. _this.vignetteCentreX = 0;
  41329. _this.vignetteCentreY = 0;
  41330. _this.vignetteWeight = 1.5;
  41331. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41332. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  41333. _this._vignetteEnabled = true;
  41334. _this.cameraContrast = 1.0;
  41335. _this.cameraExposure = 1.68;
  41336. _this._cameraToneMappingEnabled = true;
  41337. _this._fromLinearSpace = false;
  41338. _this._updateParameters();
  41339. _this.onApply = function (effect) {
  41340. var aspectRatio = _this.aspectRatio;
  41341. // Color
  41342. if (_this._colorCurvesEnabled) {
  41343. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  41344. }
  41345. if (_this._vignetteEnabled) {
  41346. // Vignette
  41347. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  41348. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41349. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41350. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  41351. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  41352. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  41353. var vignettePower = -2.0 * _this.vignetteWeight;
  41354. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  41355. }
  41356. // Contrast and exposure
  41357. effect.setFloat('contrast', _this.cameraContrast);
  41358. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  41359. // Color transform settings
  41360. if (_this._colorGradingTexture) {
  41361. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  41362. var textureSize = _this.colorGradingTexture.getSize().height;
  41363. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41364. 0.5 / textureSize, // textureOffset
  41365. textureSize, // textureSize
  41366. _this.colorGradingWeight // weight
  41367. );
  41368. }
  41369. };
  41370. return _this;
  41371. }
  41372. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41373. get: function () {
  41374. return this._colorGradingTexture;
  41375. },
  41376. set: function (value) {
  41377. if (this._colorGradingTexture === value) {
  41378. return;
  41379. }
  41380. this._colorGradingTexture = value;
  41381. this._updateParameters();
  41382. },
  41383. enumerable: true,
  41384. configurable: true
  41385. });
  41386. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41387. get: function () {
  41388. return this._vignetteBlendMode;
  41389. },
  41390. set: function (value) {
  41391. if (this._vignetteBlendMode === value) {
  41392. return;
  41393. }
  41394. this._vignetteBlendMode = value;
  41395. this._updateParameters();
  41396. },
  41397. enumerable: true,
  41398. configurable: true
  41399. });
  41400. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  41401. get: function () {
  41402. return this._colorCurvesEnabled;
  41403. },
  41404. set: function (value) {
  41405. if (this._colorCurvesEnabled === value) {
  41406. return;
  41407. }
  41408. this._colorCurvesEnabled = value;
  41409. this._updateParameters();
  41410. },
  41411. enumerable: true,
  41412. configurable: true
  41413. });
  41414. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  41415. get: function () {
  41416. return this._vignetteEnabled;
  41417. },
  41418. set: function (value) {
  41419. if (this._vignetteEnabled === value) {
  41420. return;
  41421. }
  41422. this._vignetteEnabled = value;
  41423. this._updateParameters();
  41424. },
  41425. enumerable: true,
  41426. configurable: true
  41427. });
  41428. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  41429. get: function () {
  41430. return this._fromLinearSpace;
  41431. },
  41432. set: function (value) {
  41433. if (this._fromLinearSpace === value) {
  41434. return;
  41435. }
  41436. this._fromLinearSpace = value;
  41437. this._updateParameters();
  41438. },
  41439. enumerable: true,
  41440. configurable: true
  41441. });
  41442. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  41443. get: function () {
  41444. return this._cameraToneMappingEnabled;
  41445. },
  41446. set: function (value) {
  41447. if (this._cameraToneMappingEnabled === value) {
  41448. return;
  41449. }
  41450. this._cameraToneMappingEnabled = value;
  41451. this._updateParameters();
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41457. var defines = "";
  41458. var samplers = ["textureSampler"];
  41459. if (this.colorGradingTexture) {
  41460. defines = "#define COLORGRADING\r\n";
  41461. samplers.push("txColorTransform");
  41462. }
  41463. if (this._vignetteEnabled) {
  41464. defines += "#define VIGNETTE\r\n";
  41465. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  41466. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  41467. }
  41468. else {
  41469. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  41470. }
  41471. }
  41472. if (this.cameraToneMappingEnabled) {
  41473. defines += "#define TONEMAPPING\r\n";
  41474. }
  41475. if (this._colorCurvesEnabled && this.colorCurves) {
  41476. defines += "#define COLORCURVES\r\n";
  41477. }
  41478. if (this._fromLinearSpace) {
  41479. defines += "#define FROMLINEARSPACE\r\n";
  41480. }
  41481. this.updateEffect(defines, null, samplers);
  41482. };
  41483. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  41484. get: function () {
  41485. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  41486. },
  41487. enumerable: true,
  41488. configurable: true
  41489. });
  41490. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  41491. get: function () {
  41492. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  41493. },
  41494. enumerable: true,
  41495. configurable: true
  41496. });
  41497. return ImageProcessingPostProcess;
  41498. }(BABYLON.PostProcess));
  41499. // Statics
  41500. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  41501. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  41502. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41503. })(BABYLON || (BABYLON = {}));
  41504. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41505. var BABYLON;
  41506. (function (BABYLON) {
  41507. /**
  41508. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41509. * It can help converting any input color in a desired output one. This can then be used to create effects
  41510. * from sepia, black and white to sixties or futuristic rendering...
  41511. *
  41512. * The only supported format is currently 3dl.
  41513. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41514. */
  41515. var ColorGradingTexture = (function (_super) {
  41516. __extends(ColorGradingTexture, _super);
  41517. /**
  41518. * Instantiates a ColorGradingTexture from the following parameters.
  41519. *
  41520. * @param url The location of the color gradind data (currently only supporting 3dl)
  41521. * @param scene The scene the texture will be used in
  41522. */
  41523. function ColorGradingTexture(url, scene) {
  41524. var _this = _super.call(this, scene) || this;
  41525. if (!url) {
  41526. return _this;
  41527. }
  41528. _this._textureMatrix = BABYLON.Matrix.Identity();
  41529. _this.name = url;
  41530. _this.url = url;
  41531. _this.hasAlpha = false;
  41532. _this.isCube = false;
  41533. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41534. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41535. _this.anisotropicFilteringLevel = 1;
  41536. _this._texture = _this._getFromCache(url, true);
  41537. if (!_this._texture) {
  41538. if (!scene.useDelayedTextureLoading) {
  41539. _this.loadTexture();
  41540. }
  41541. else {
  41542. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41543. }
  41544. }
  41545. return _this;
  41546. }
  41547. /**
  41548. * Returns the texture matrix used in most of the material.
  41549. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41550. */
  41551. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41552. return this._textureMatrix;
  41553. };
  41554. /**
  41555. * Occurs when the file being loaded is a .3dl LUT file.
  41556. */
  41557. ColorGradingTexture.prototype.load3dlTexture = function () {
  41558. var _this = this;
  41559. var mipLevels = 0;
  41560. var floatArrayView = null;
  41561. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41562. this._texture = texture;
  41563. var callback = function (text) {
  41564. var data;
  41565. var tempData;
  41566. var line;
  41567. var lines = text.split('\n');
  41568. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41569. var maxColor = 0;
  41570. for (var i = 0; i < lines.length; i++) {
  41571. line = lines[i];
  41572. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41573. continue;
  41574. if (line.indexOf('#') === 0)
  41575. continue;
  41576. var words = line.split(" ");
  41577. if (size === 0) {
  41578. // Number of space + one
  41579. size = words.length;
  41580. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41581. tempData = new Float32Array(size * size * size * 4);
  41582. continue;
  41583. }
  41584. if (size != 0) {
  41585. var r = Math.max(parseInt(words[0]), 0);
  41586. var g = Math.max(parseInt(words[1]), 0);
  41587. var b = Math.max(parseInt(words[2]), 0);
  41588. maxColor = Math.max(r, maxColor);
  41589. maxColor = Math.max(g, maxColor);
  41590. maxColor = Math.max(b, maxColor);
  41591. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41592. tempData[pixelStorageIndex + 0] = r;
  41593. tempData[pixelStorageIndex + 1] = g;
  41594. tempData[pixelStorageIndex + 2] = b;
  41595. tempData[pixelStorageIndex + 3] = 0;
  41596. pixelIndexSlice++;
  41597. if (pixelIndexSlice % size == 0) {
  41598. pixelIndexH++;
  41599. pixelIndexSlice = 0;
  41600. if (pixelIndexH % size == 0) {
  41601. pixelIndexW++;
  41602. pixelIndexH = 0;
  41603. }
  41604. }
  41605. }
  41606. }
  41607. for (var i = 0; i < tempData.length; i++) {
  41608. var value = tempData[i];
  41609. data[i] = (value / maxColor * 255);
  41610. }
  41611. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  41612. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41613. };
  41614. BABYLON.Tools.LoadFile(this.url, callback);
  41615. return this._texture;
  41616. };
  41617. /**
  41618. * Starts the loading process of the texture.
  41619. */
  41620. ColorGradingTexture.prototype.loadTexture = function () {
  41621. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41622. this.load3dlTexture();
  41623. }
  41624. };
  41625. /**
  41626. * Clones the color gradind texture.
  41627. */
  41628. ColorGradingTexture.prototype.clone = function () {
  41629. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41630. // Base texture
  41631. newTexture.level = this.level;
  41632. return newTexture;
  41633. };
  41634. /**
  41635. * Called during delayed load for textures.
  41636. */
  41637. ColorGradingTexture.prototype.delayLoad = function () {
  41638. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41639. return;
  41640. }
  41641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41642. this._texture = this._getFromCache(this.url, true);
  41643. if (!this._texture) {
  41644. this.loadTexture();
  41645. }
  41646. };
  41647. /**
  41648. * Binds the color grading to the shader.
  41649. * @param colorGrading The texture to bind
  41650. * @param effect The effect to bind to
  41651. */
  41652. ColorGradingTexture.Bind = function (colorGrading, effect) {
  41653. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  41654. var x = colorGrading.level; // Texture Level
  41655. var y = colorGrading.getSize().height; // Texture Size example with 8
  41656. var z = y - 1.0; // SizeMinusOne 8 - 1
  41657. var w = 1 / y; // Space of 1 slice 1 / 8
  41658. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  41659. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  41660. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  41661. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  41662. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  41663. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  41664. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  41665. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  41666. };
  41667. /**
  41668. * Prepare the list of uniforms associated with the ColorGrading effects.
  41669. * @param uniformsList The list of uniforms used in the effect
  41670. * @param samplersList The list of samplers used in the effect
  41671. */
  41672. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  41673. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  41674. samplersList.push("cameraColorGrading2DSampler");
  41675. };
  41676. /**
  41677. * Parses a color grading texture serialized by Babylon.
  41678. * @param parsedTexture The texture information being parsedTexture
  41679. * @param scene The scene to load the texture in
  41680. * @param rootUrl The root url of the data assets to load
  41681. * @return A color gradind texture
  41682. */
  41683. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41684. var texture = null;
  41685. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41686. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41687. texture.name = parsedTexture.name;
  41688. texture.level = parsedTexture.level;
  41689. }
  41690. return texture;
  41691. };
  41692. /**
  41693. * Serializes the LUT texture to json format.
  41694. */
  41695. ColorGradingTexture.prototype.serialize = function () {
  41696. if (!this.name) {
  41697. return null;
  41698. }
  41699. var serializationObject = {};
  41700. serializationObject.name = this.name;
  41701. serializationObject.level = this.level;
  41702. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41703. return serializationObject;
  41704. };
  41705. return ColorGradingTexture;
  41706. }(BABYLON.BaseTexture));
  41707. /**
  41708. * Empty line regex stored for GC.
  41709. */
  41710. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41711. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41712. })(BABYLON || (BABYLON = {}));
  41713. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41714. var BABYLON;
  41715. (function (BABYLON) {
  41716. /**
  41717. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41718. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41719. * 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;
  41720. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41721. */
  41722. var ColorCurves = (function () {
  41723. function ColorCurves() {
  41724. this._dirty = true;
  41725. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41726. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41727. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41728. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41729. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41730. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41731. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41732. this._globalHue = 30;
  41733. this._globalDensity = 0;
  41734. this._globalSaturation = 0;
  41735. this._globalExposure = 0;
  41736. this._highlightsHue = 30;
  41737. this._highlightsDensity = 0;
  41738. this._highlightsSaturation = 0;
  41739. this._highlightsExposure = 0;
  41740. this._midtonesHue = 30;
  41741. this._midtonesDensity = 0;
  41742. this._midtonesSaturation = 0;
  41743. this._midtonesExposure = 0;
  41744. this._shadowsHue = 30;
  41745. this._shadowsDensity = 0;
  41746. this._shadowsSaturation = 0;
  41747. this._shadowsExposure = 0;
  41748. }
  41749. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41750. /**
  41751. * Gets the global Hue value.
  41752. * 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).
  41753. */
  41754. get: function () {
  41755. return this._globalHue;
  41756. },
  41757. /**
  41758. * Sets the global Hue value.
  41759. * 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).
  41760. */
  41761. set: function (value) {
  41762. this._globalHue = value;
  41763. this._dirty = true;
  41764. },
  41765. enumerable: true,
  41766. configurable: true
  41767. });
  41768. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41769. /**
  41770. * Gets the global Density value.
  41771. * 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.
  41772. * Values less than zero provide a filter of opposite hue.
  41773. */
  41774. get: function () {
  41775. return this._globalDensity;
  41776. },
  41777. /**
  41778. * Sets the global Density value.
  41779. * 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.
  41780. * Values less than zero provide a filter of opposite hue.
  41781. */
  41782. set: function (value) {
  41783. this._globalDensity = value;
  41784. this._dirty = true;
  41785. },
  41786. enumerable: true,
  41787. configurable: true
  41788. });
  41789. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41790. /**
  41791. * Gets the global Saturation value.
  41792. * 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.
  41793. */
  41794. get: function () {
  41795. return this._globalSaturation;
  41796. },
  41797. /**
  41798. * Sets the global Saturation value.
  41799. * 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.
  41800. */
  41801. set: function (value) {
  41802. this._globalSaturation = value;
  41803. this._dirty = true;
  41804. },
  41805. enumerable: true,
  41806. configurable: true
  41807. });
  41808. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41809. /**
  41810. * Gets the highlights Hue value.
  41811. * 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).
  41812. */
  41813. get: function () {
  41814. return this._highlightsHue;
  41815. },
  41816. /**
  41817. * Sets the highlights Hue value.
  41818. * 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).
  41819. */
  41820. set: function (value) {
  41821. this._highlightsHue = value;
  41822. this._dirty = true;
  41823. },
  41824. enumerable: true,
  41825. configurable: true
  41826. });
  41827. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41828. /**
  41829. * Gets the highlights Density value.
  41830. * 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.
  41831. * Values less than zero provide a filter of opposite hue.
  41832. */
  41833. get: function () {
  41834. return this._highlightsDensity;
  41835. },
  41836. /**
  41837. * Sets the highlights Density value.
  41838. * 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.
  41839. * Values less than zero provide a filter of opposite hue.
  41840. */
  41841. set: function (value) {
  41842. this._highlightsDensity = value;
  41843. this._dirty = true;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41849. /**
  41850. * Gets the highlights Saturation value.
  41851. * 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.
  41852. */
  41853. get: function () {
  41854. return this._highlightsSaturation;
  41855. },
  41856. /**
  41857. * Sets the highlights Saturation value.
  41858. * 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.
  41859. */
  41860. set: function (value) {
  41861. this._highlightsSaturation = value;
  41862. this._dirty = true;
  41863. },
  41864. enumerable: true,
  41865. configurable: true
  41866. });
  41867. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41868. /**
  41869. * Gets the highlights Exposure value.
  41870. * 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.
  41871. */
  41872. get: function () {
  41873. return this._highlightsExposure;
  41874. },
  41875. /**
  41876. * Sets the highlights Exposure value.
  41877. * 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.
  41878. */
  41879. set: function (value) {
  41880. this._highlightsExposure = value;
  41881. this._dirty = true;
  41882. },
  41883. enumerable: true,
  41884. configurable: true
  41885. });
  41886. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41887. /**
  41888. * Gets the midtones Hue value.
  41889. * 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).
  41890. */
  41891. get: function () {
  41892. return this._midtonesHue;
  41893. },
  41894. /**
  41895. * Sets the midtones Hue value.
  41896. * 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).
  41897. */
  41898. set: function (value) {
  41899. this._midtonesHue = value;
  41900. this._dirty = true;
  41901. },
  41902. enumerable: true,
  41903. configurable: true
  41904. });
  41905. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41906. /**
  41907. * Gets the midtones Density value.
  41908. * 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.
  41909. * Values less than zero provide a filter of opposite hue.
  41910. */
  41911. get: function () {
  41912. return this._midtonesDensity;
  41913. },
  41914. /**
  41915. * Sets the midtones Density value.
  41916. * 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.
  41917. * Values less than zero provide a filter of opposite hue.
  41918. */
  41919. set: function (value) {
  41920. this._midtonesDensity = value;
  41921. this._dirty = true;
  41922. },
  41923. enumerable: true,
  41924. configurable: true
  41925. });
  41926. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41927. /**
  41928. * Gets the midtones Saturation value.
  41929. * 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.
  41930. */
  41931. get: function () {
  41932. return this._midtonesSaturation;
  41933. },
  41934. /**
  41935. * Sets the midtones Saturation value.
  41936. * 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.
  41937. */
  41938. set: function (value) {
  41939. this._midtonesSaturation = value;
  41940. this._dirty = true;
  41941. },
  41942. enumerable: true,
  41943. configurable: true
  41944. });
  41945. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41946. /**
  41947. * Gets the midtones Exposure value.
  41948. * 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.
  41949. */
  41950. get: function () {
  41951. return this._midtonesExposure;
  41952. },
  41953. /**
  41954. * Sets the midtones Exposure value.
  41955. * 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.
  41956. */
  41957. set: function (value) {
  41958. this._midtonesExposure = value;
  41959. this._dirty = true;
  41960. },
  41961. enumerable: true,
  41962. configurable: true
  41963. });
  41964. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41965. /**
  41966. * Gets the shadows Hue value.
  41967. * 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).
  41968. */
  41969. get: function () {
  41970. return this._shadowsHue;
  41971. },
  41972. /**
  41973. * Sets the shadows Hue value.
  41974. * 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).
  41975. */
  41976. set: function (value) {
  41977. this._shadowsHue = value;
  41978. this._dirty = true;
  41979. },
  41980. enumerable: true,
  41981. configurable: true
  41982. });
  41983. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41984. /**
  41985. * Gets the shadows Density value.
  41986. * 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.
  41987. * Values less than zero provide a filter of opposite hue.
  41988. */
  41989. get: function () {
  41990. return this._shadowsDensity;
  41991. },
  41992. /**
  41993. * Sets the shadows Density value.
  41994. * 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.
  41995. * Values less than zero provide a filter of opposite hue.
  41996. */
  41997. set: function (value) {
  41998. this._shadowsDensity = value;
  41999. this._dirty = true;
  42000. },
  42001. enumerable: true,
  42002. configurable: true
  42003. });
  42004. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  42005. /**
  42006. * Gets the shadows Saturation value.
  42007. * 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.
  42008. */
  42009. get: function () {
  42010. return this._shadowsSaturation;
  42011. },
  42012. /**
  42013. * Sets the shadows Saturation value.
  42014. * 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.
  42015. */
  42016. set: function (value) {
  42017. this._shadowsSaturation = value;
  42018. this._dirty = true;
  42019. },
  42020. enumerable: true,
  42021. configurable: true
  42022. });
  42023. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  42024. /**
  42025. * Gets the shadows Exposure value.
  42026. * 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.
  42027. */
  42028. get: function () {
  42029. return this._shadowsExposure;
  42030. },
  42031. /**
  42032. * Sets the shadows Exposure value.
  42033. * 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.
  42034. */
  42035. set: function (value) {
  42036. this._shadowsExposure = value;
  42037. this._dirty = true;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. /**
  42043. * Binds the color curves to the shader.
  42044. * @param colorCurves The color curve to bind
  42045. * @param effect The effect to bind to
  42046. */
  42047. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42048. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42049. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42050. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42051. if (colorCurves._dirty) {
  42052. colorCurves._dirty = false;
  42053. // Fill in global info.
  42054. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42055. // Compute highlights info.
  42056. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42057. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42058. // Compute midtones info.
  42059. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42060. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42061. // Compute shadows info.
  42062. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42063. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42064. // Compute deltas (neutral is midtones).
  42065. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42066. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42067. }
  42068. if (effect) {
  42069. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42070. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42071. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42072. }
  42073. };
  42074. /**
  42075. * Prepare the list of uniforms associated with the ColorCurves effects.
  42076. * @param uniformsList The list of uniforms used in the effect
  42077. */
  42078. ColorCurves.PrepareUniforms = function (uniformsList) {
  42079. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42080. };
  42081. /**
  42082. * Returns color grading data based on a hue, density, saturation and exposure value.
  42083. * @param filterHue The hue of the color filter.
  42084. * @param filterDensity The density of the color filter.
  42085. * @param saturation The saturation.
  42086. * @param exposure The exposure.
  42087. * @param result The result data container.
  42088. */
  42089. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42090. if (hue == null) {
  42091. return;
  42092. }
  42093. hue = ColorCurves.clamp(hue, 0, 360);
  42094. density = ColorCurves.clamp(density, -100, 100);
  42095. saturation = ColorCurves.clamp(saturation, -100, 100);
  42096. exposure = ColorCurves.clamp(exposure, -100, 100);
  42097. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42098. // so that the maximum filter density is only 50% control. This provides fine control
  42099. // for small values and reasonable range.
  42100. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42101. density *= 0.5;
  42102. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42103. if (density < 0) {
  42104. density *= -1;
  42105. hue = (hue + 180) % 360;
  42106. }
  42107. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42108. result.scaleToRef(2, result);
  42109. result.a = 1 + 0.01 * saturation;
  42110. };
  42111. /**
  42112. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42113. * @param value The input slider value in range [-100,100].
  42114. * @returns Adjusted value.
  42115. */
  42116. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42117. value /= 100;
  42118. var x = Math.abs(value);
  42119. x = Math.pow(x, 2);
  42120. if (value < 0) {
  42121. x *= -1;
  42122. }
  42123. x *= 100;
  42124. return x;
  42125. };
  42126. /**
  42127. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42128. * @param hue The hue (H) input.
  42129. * @param saturation The saturation (S) input.
  42130. * @param brightness The brightness (B) input.
  42131. * @result An RGBA color represented as Vector4.
  42132. */
  42133. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42134. var h = ColorCurves.clamp(hue, 0, 360);
  42135. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42136. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42137. if (s === 0) {
  42138. result.r = v;
  42139. result.g = v;
  42140. result.b = v;
  42141. }
  42142. else {
  42143. // sector 0 to 5
  42144. h /= 60;
  42145. var i = Math.floor(h);
  42146. // fractional part of h
  42147. var f = h - i;
  42148. var p = v * (1 - s);
  42149. var q = v * (1 - s * f);
  42150. var t = v * (1 - s * (1 - f));
  42151. switch (i) {
  42152. case 0:
  42153. result.r = v;
  42154. result.g = t;
  42155. result.b = p;
  42156. break;
  42157. case 1:
  42158. result.r = q;
  42159. result.g = v;
  42160. result.b = p;
  42161. break;
  42162. case 2:
  42163. result.r = p;
  42164. result.g = v;
  42165. result.b = t;
  42166. break;
  42167. case 3:
  42168. result.r = p;
  42169. result.g = q;
  42170. result.b = v;
  42171. break;
  42172. case 4:
  42173. result.r = t;
  42174. result.g = p;
  42175. result.b = v;
  42176. break;
  42177. default:
  42178. result.r = v;
  42179. result.g = p;
  42180. result.b = q;
  42181. break;
  42182. }
  42183. }
  42184. result.a = 1;
  42185. };
  42186. /**
  42187. * Returns a value clamped between min and max
  42188. * @param value The value to clamp
  42189. * @param min The minimum of value
  42190. * @param max The maximum of value
  42191. * @returns The clamped value.
  42192. */
  42193. ColorCurves.clamp = function (value, min, max) {
  42194. return Math.min(Math.max(value, min), max);
  42195. };
  42196. /**
  42197. * Clones the current color curve instance.
  42198. * @return The cloned curves
  42199. */
  42200. ColorCurves.prototype.clone = function () {
  42201. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42202. };
  42203. /**
  42204. * Serializes the current color curve instance to a json representation.
  42205. * @return a JSON representation
  42206. */
  42207. ColorCurves.prototype.serialize = function () {
  42208. return BABYLON.SerializationHelper.Serialize(this);
  42209. };
  42210. /**
  42211. * Parses the color curve from a json representation.
  42212. * @param source the JSON source to parse
  42213. * @return The parsed curves
  42214. */
  42215. ColorCurves.Parse = function (source) {
  42216. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42217. };
  42218. return ColorCurves;
  42219. }());
  42220. __decorate([
  42221. BABYLON.serialize()
  42222. ], ColorCurves.prototype, "_globalHue", void 0);
  42223. __decorate([
  42224. BABYLON.serialize()
  42225. ], ColorCurves.prototype, "_globalDensity", void 0);
  42226. __decorate([
  42227. BABYLON.serialize()
  42228. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42229. __decorate([
  42230. BABYLON.serialize()
  42231. ], ColorCurves.prototype, "_globalExposure", void 0);
  42232. __decorate([
  42233. BABYLON.serialize()
  42234. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42235. __decorate([
  42236. BABYLON.serialize()
  42237. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42238. __decorate([
  42239. BABYLON.serialize()
  42240. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42241. __decorate([
  42242. BABYLON.serialize()
  42243. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42244. __decorate([
  42245. BABYLON.serialize()
  42246. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42247. __decorate([
  42248. BABYLON.serialize()
  42249. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42250. __decorate([
  42251. BABYLON.serialize()
  42252. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42253. __decorate([
  42254. BABYLON.serialize()
  42255. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42256. BABYLON.ColorCurves = ColorCurves;
  42257. })(BABYLON || (BABYLON = {}));
  42258. //# sourceMappingURL=babylon.colorCurves.js.map
  42259. var BABYLON;
  42260. (function (BABYLON) {
  42261. var PostProcessRenderPipelineManager = (function () {
  42262. function PostProcessRenderPipelineManager() {
  42263. this._renderPipelines = {};
  42264. }
  42265. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  42266. this._renderPipelines[renderPipeline._name] = renderPipeline;
  42267. };
  42268. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  42269. var renderPipeline = this._renderPipelines[renderPipelineName];
  42270. if (!renderPipeline) {
  42271. return;
  42272. }
  42273. renderPipeline._attachCameras(cameras, unique);
  42274. };
  42275. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  42276. var renderPipeline = this._renderPipelines[renderPipelineName];
  42277. if (!renderPipeline) {
  42278. return;
  42279. }
  42280. renderPipeline._detachCameras(cameras);
  42281. };
  42282. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42283. var renderPipeline = this._renderPipelines[renderPipelineName];
  42284. if (!renderPipeline) {
  42285. return;
  42286. }
  42287. renderPipeline._enableEffect(renderEffectName, cameras);
  42288. };
  42289. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  42290. var renderPipeline = this._renderPipelines[renderPipelineName];
  42291. if (!renderPipeline) {
  42292. return;
  42293. }
  42294. renderPipeline._disableEffect(renderEffectName, cameras);
  42295. };
  42296. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  42297. var renderPipeline = this._renderPipelines[renderPipelineName];
  42298. if (!renderPipeline) {
  42299. return;
  42300. }
  42301. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  42302. };
  42303. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  42304. var renderPipeline = this._renderPipelines[renderPipelineName];
  42305. if (!renderPipeline) {
  42306. return;
  42307. }
  42308. renderPipeline._disableDisplayOnlyPass(cameras);
  42309. };
  42310. PostProcessRenderPipelineManager.prototype.update = function () {
  42311. for (var renderPipelineName in this._renderPipelines) {
  42312. var pipeline = this._renderPipelines[renderPipelineName];
  42313. if (!pipeline.isSupported) {
  42314. pipeline.dispose();
  42315. delete this._renderPipelines[renderPipelineName];
  42316. }
  42317. else {
  42318. pipeline._update();
  42319. }
  42320. }
  42321. };
  42322. return PostProcessRenderPipelineManager;
  42323. }());
  42324. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  42325. })(BABYLON || (BABYLON = {}));
  42326. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  42327. var BABYLON;
  42328. (function (BABYLON) {
  42329. var PostProcessRenderPass = (function () {
  42330. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  42331. this._enabled = true;
  42332. this._refCount = 0;
  42333. this._name = name;
  42334. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  42335. this.setRenderList(renderList);
  42336. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  42337. this._renderTexture.onAfterRenderObservable.add(afterRender);
  42338. this._scene = scene;
  42339. this._renderList = renderList;
  42340. }
  42341. // private
  42342. PostProcessRenderPass.prototype._incRefCount = function () {
  42343. if (this._refCount === 0) {
  42344. this._scene.customRenderTargets.push(this._renderTexture);
  42345. }
  42346. return ++this._refCount;
  42347. };
  42348. PostProcessRenderPass.prototype._decRefCount = function () {
  42349. this._refCount--;
  42350. if (this._refCount <= 0) {
  42351. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  42352. }
  42353. return this._refCount;
  42354. };
  42355. PostProcessRenderPass.prototype._update = function () {
  42356. this.setRenderList(this._renderList);
  42357. };
  42358. // public
  42359. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  42360. this._renderTexture.renderList = renderList;
  42361. };
  42362. PostProcessRenderPass.prototype.getRenderTexture = function () {
  42363. return this._renderTexture;
  42364. };
  42365. return PostProcessRenderPass;
  42366. }());
  42367. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  42368. })(BABYLON || (BABYLON = {}));
  42369. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  42370. var BABYLON;
  42371. (function (BABYLON) {
  42372. var PostProcessRenderEffect = (function () {
  42373. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  42374. this._engine = engine;
  42375. this._name = name;
  42376. this._singleInstance = singleInstance || true;
  42377. this._getPostProcess = getPostProcess;
  42378. this._cameras = [];
  42379. this._indicesForCamera = [];
  42380. this._postProcesses = {};
  42381. this._renderPasses = {};
  42382. this._renderEffectAsPasses = {};
  42383. }
  42384. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  42385. get: function () {
  42386. for (var index in this._postProcesses) {
  42387. if (!this._postProcesses[index].isSupported) {
  42388. return false;
  42389. }
  42390. }
  42391. return true;
  42392. },
  42393. enumerable: true,
  42394. configurable: true
  42395. });
  42396. PostProcessRenderEffect.prototype._update = function () {
  42397. for (var renderPassName in this._renderPasses) {
  42398. this._renderPasses[renderPassName]._update();
  42399. }
  42400. };
  42401. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  42402. this._renderPasses[renderPass._name] = renderPass;
  42403. this._linkParameters();
  42404. };
  42405. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  42406. delete this._renderPasses[renderPass._name];
  42407. this._linkParameters();
  42408. };
  42409. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  42410. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  42411. this._linkParameters();
  42412. };
  42413. PostProcessRenderEffect.prototype.getPass = function (passName) {
  42414. for (var renderPassName in this._renderPasses) {
  42415. if (renderPassName === passName) {
  42416. return this._renderPasses[passName];
  42417. }
  42418. }
  42419. };
  42420. PostProcessRenderEffect.prototype.emptyPasses = function () {
  42421. this._renderPasses = {};
  42422. this._linkParameters();
  42423. };
  42424. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  42425. var cameraKey;
  42426. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42427. for (var i = 0; i < _cam.length; i++) {
  42428. var camera = _cam[i];
  42429. var cameraName = camera.name;
  42430. if (this._singleInstance) {
  42431. cameraKey = 0;
  42432. }
  42433. else {
  42434. cameraKey = cameraName;
  42435. }
  42436. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  42437. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  42438. if (!this._indicesForCamera[cameraName]) {
  42439. this._indicesForCamera[cameraName] = [];
  42440. }
  42441. this._indicesForCamera[cameraName].push(index);
  42442. if (this._cameras.indexOf(camera) === -1) {
  42443. this._cameras[cameraName] = camera;
  42444. }
  42445. for (var passName in this._renderPasses) {
  42446. this._renderPasses[passName]._incRefCount();
  42447. }
  42448. }
  42449. this._linkParameters();
  42450. };
  42451. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  42452. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42453. for (var i = 0; i < _cam.length; i++) {
  42454. var camera = _cam[i];
  42455. var cameraName = camera.name;
  42456. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42457. var index = this._cameras.indexOf(cameraName);
  42458. this._indicesForCamera.splice(index, 1);
  42459. this._cameras.splice(index, 1);
  42460. for (var passName in this._renderPasses) {
  42461. this._renderPasses[passName]._decRefCount();
  42462. }
  42463. }
  42464. };
  42465. PostProcessRenderEffect.prototype._enable = function (cameras) {
  42466. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42467. for (var i = 0; i < _cam.length; i++) {
  42468. var camera = _cam[i];
  42469. var cameraName = camera.name;
  42470. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  42471. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  42472. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  42473. }
  42474. }
  42475. for (var passName in this._renderPasses) {
  42476. this._renderPasses[passName]._incRefCount();
  42477. }
  42478. }
  42479. };
  42480. PostProcessRenderEffect.prototype._disable = function (cameras) {
  42481. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42482. for (var i = 0; i < _cam.length; i++) {
  42483. var camera = _cam[i];
  42484. var cameraName = camera.Name;
  42485. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  42486. for (var passName in this._renderPasses) {
  42487. this._renderPasses[passName]._decRefCount();
  42488. }
  42489. }
  42490. };
  42491. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  42492. if (this._singleInstance) {
  42493. return this._postProcesses[0];
  42494. }
  42495. else {
  42496. return this._postProcesses[camera.name];
  42497. }
  42498. };
  42499. PostProcessRenderEffect.prototype._linkParameters = function () {
  42500. var _this = this;
  42501. for (var index in this._postProcesses) {
  42502. if (this.applyParameters) {
  42503. this.applyParameters(this._postProcesses[index]);
  42504. }
  42505. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  42506. _this._linkTextures(effect);
  42507. });
  42508. }
  42509. };
  42510. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  42511. for (var renderPassName in this._renderPasses) {
  42512. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  42513. }
  42514. for (var renderEffectName in this._renderEffectAsPasses) {
  42515. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  42516. }
  42517. };
  42518. return PostProcessRenderEffect;
  42519. }());
  42520. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  42521. })(BABYLON || (BABYLON = {}));
  42522. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  42523. var BABYLON;
  42524. (function (BABYLON) {
  42525. var PostProcessRenderPipeline = (function () {
  42526. function PostProcessRenderPipeline(engine, name) {
  42527. this._engine = engine;
  42528. this._name = name;
  42529. this._renderEffects = new Array();
  42530. this._renderEffectsForIsolatedPass = new Array();
  42531. this._cameras = [];
  42532. }
  42533. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  42534. get: function () {
  42535. for (var renderEffectName in this._renderEffects) {
  42536. if (!this._renderEffects[renderEffectName].isSupported) {
  42537. return false;
  42538. }
  42539. }
  42540. return true;
  42541. },
  42542. enumerable: true,
  42543. configurable: true
  42544. });
  42545. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  42546. this._renderEffects[renderEffect._name] = renderEffect;
  42547. };
  42548. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  42549. var renderEffects = this._renderEffects[renderEffectName];
  42550. if (!renderEffects) {
  42551. return;
  42552. }
  42553. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42554. };
  42555. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  42556. var renderEffects = this._renderEffects[renderEffectName];
  42557. if (!renderEffects) {
  42558. return;
  42559. }
  42560. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  42561. };
  42562. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  42563. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42564. var indicesToDelete = [];
  42565. var i;
  42566. for (i = 0; i < _cam.length; i++) {
  42567. var camera = _cam[i];
  42568. var cameraName = camera.name;
  42569. if (this._cameras.indexOf(camera) === -1) {
  42570. this._cameras[cameraName] = camera;
  42571. }
  42572. else if (unique) {
  42573. indicesToDelete.push(i);
  42574. }
  42575. }
  42576. for (i = 0; i < indicesToDelete.length; i++) {
  42577. cameras.splice(indicesToDelete[i], 1);
  42578. }
  42579. for (var renderEffectName in this._renderEffects) {
  42580. this._renderEffects[renderEffectName]._attachCameras(_cam);
  42581. }
  42582. };
  42583. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  42584. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42585. for (var renderEffectName in this._renderEffects) {
  42586. this._renderEffects[renderEffectName]._detachCameras(_cam);
  42587. }
  42588. for (var i = 0; i < _cam.length; i++) {
  42589. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  42590. }
  42591. };
  42592. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  42593. var _this = this;
  42594. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42595. var pass = null;
  42596. var renderEffectName;
  42597. for (renderEffectName in this._renderEffects) {
  42598. pass = this._renderEffects[renderEffectName].getPass(passName);
  42599. if (pass != null) {
  42600. break;
  42601. }
  42602. }
  42603. if (pass === null) {
  42604. return;
  42605. }
  42606. for (renderEffectName in this._renderEffects) {
  42607. this._renderEffects[renderEffectName]._disable(_cam);
  42608. }
  42609. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  42610. for (var i = 0; i < _cam.length; i++) {
  42611. var camera = _cam[i];
  42612. var cameraName = camera.name;
  42613. 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); });
  42614. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  42615. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  42616. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  42617. }
  42618. };
  42619. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  42620. var _this = this;
  42621. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  42622. for (var i = 0; i < _cam.length; i++) {
  42623. var camera = _cam[i];
  42624. var cameraName = camera.name;
  42625. 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); });
  42626. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  42627. }
  42628. for (var renderEffectName in this._renderEffects) {
  42629. this._renderEffects[renderEffectName]._enable(_cam);
  42630. }
  42631. };
  42632. PostProcessRenderPipeline.prototype._update = function () {
  42633. for (var renderEffectName in this._renderEffects) {
  42634. this._renderEffects[renderEffectName]._update();
  42635. }
  42636. for (var i = 0; i < this._cameras.length; i++) {
  42637. var cameraName = this._cameras[i].name;
  42638. if (this._renderEffectsForIsolatedPass[cameraName]) {
  42639. this._renderEffectsForIsolatedPass[cameraName]._update();
  42640. }
  42641. }
  42642. };
  42643. PostProcessRenderPipeline.prototype._reset = function () {
  42644. this._renderEffects = new Array();
  42645. this._renderEffectsForIsolatedPass = new Array();
  42646. };
  42647. PostProcessRenderPipeline.prototype.dispose = function () {
  42648. // Must be implemented by children
  42649. };
  42650. return PostProcessRenderPipeline;
  42651. }());
  42652. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  42653. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  42654. __decorate([
  42655. BABYLON.serialize()
  42656. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  42657. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  42658. })(BABYLON || (BABYLON = {}));
  42659. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  42660. var BABYLON;
  42661. (function (BABYLON) {
  42662. var DefaultRenderingPipeline = (function (_super) {
  42663. __extends(DefaultRenderingPipeline, _super);
  42664. /**
  42665. * @constructor
  42666. * @param {string} name - The rendering pipeline name
  42667. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  42668. * @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)
  42669. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  42670. */
  42671. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  42672. var _this = _super.call(this, scene.getEngine(), name) || this;
  42673. _this.PassPostProcessId = "PassPostProcessEffect";
  42674. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  42675. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  42676. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  42677. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  42678. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  42679. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  42680. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  42681. // IAnimatable
  42682. _this.animations = [];
  42683. // Values
  42684. _this._bloomEnabled = false;
  42685. _this._fxaaEnabled = false;
  42686. _this._imageProcessingEnabled = true;
  42687. _this._bloomScale = 0.6;
  42688. /**
  42689. * Specifies the size of the bloom blur kernel, relative to the final output size
  42690. */
  42691. _this.bloomKernel = 64;
  42692. /**
  42693. * Specifies the weight of the bloom in the final rendering
  42694. */
  42695. _this._bloomWeight = 0.15;
  42696. _this._cameras = cameras || [];
  42697. // Initialize
  42698. _this._hdr = hdr;
  42699. _this._scene = scene;
  42700. // Misc
  42701. _this._defaultPipelineTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  42702. // Attach
  42703. scene.postProcessRenderPipelineManager.addPipeline(_this);
  42704. _this._buildPipeline();
  42705. return _this;
  42706. }
  42707. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  42708. get: function () {
  42709. return this._bloomWeight;
  42710. },
  42711. set: function (value) {
  42712. if (this._bloomWeight === value) {
  42713. return;
  42714. }
  42715. this._bloomWeight = value;
  42716. if (this._hdr && this.copyBack) {
  42717. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  42718. }
  42719. },
  42720. enumerable: true,
  42721. configurable: true
  42722. });
  42723. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  42724. get: function () {
  42725. return this._bloomScale;
  42726. },
  42727. set: function (value) {
  42728. if (this._bloomScale === value) {
  42729. return;
  42730. }
  42731. this._bloomScale = value;
  42732. this._buildPipeline();
  42733. },
  42734. enumerable: true,
  42735. configurable: true
  42736. });
  42737. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  42738. get: function () {
  42739. return this._bloomEnabled;
  42740. },
  42741. set: function (enabled) {
  42742. if (this._bloomEnabled === enabled) {
  42743. return;
  42744. }
  42745. this._bloomEnabled = enabled;
  42746. this._buildPipeline();
  42747. },
  42748. enumerable: true,
  42749. configurable: true
  42750. });
  42751. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  42752. get: function () {
  42753. return this._fxaaEnabled;
  42754. },
  42755. set: function (enabled) {
  42756. if (this._fxaaEnabled === enabled) {
  42757. return;
  42758. }
  42759. this._fxaaEnabled = enabled;
  42760. this._buildPipeline();
  42761. },
  42762. enumerable: true,
  42763. configurable: true
  42764. });
  42765. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  42766. get: function () {
  42767. return this._imageProcessingEnabled;
  42768. },
  42769. set: function (enabled) {
  42770. if (this._imageProcessingEnabled === enabled) {
  42771. return;
  42772. }
  42773. this._imageProcessingEnabled = enabled;
  42774. this._buildPipeline();
  42775. },
  42776. enumerable: true,
  42777. configurable: true
  42778. });
  42779. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  42780. var _this = this;
  42781. var engine = this._scene.getEngine();
  42782. this._disposePostProcesses();
  42783. this._reset();
  42784. if (this.bloomEnabled) {
  42785. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42786. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  42787. if (!this._hdr) {
  42788. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42789. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  42790. this.highlights.autoClear = false;
  42791. this.highlights.alwaysForcePOT = true;
  42792. }
  42793. 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);
  42794. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  42795. this.blurX.alwaysForcePOT = true;
  42796. this.blurX.autoClear = false;
  42797. this.blurX.onActivateObservable.add(function () {
  42798. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  42799. _this.blurX.kernel = _this.bloomKernel * dw;
  42800. });
  42801. 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);
  42802. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  42803. this.blurY.alwaysForcePOT = true;
  42804. this.blurY.autoClear = false;
  42805. this.blurY.onActivateObservable.add(function () {
  42806. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  42807. _this.blurY.kernel = _this.bloomKernel * dh;
  42808. });
  42809. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42810. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  42811. this.copyBack.alwaysForcePOT = true;
  42812. if (this._hdr) {
  42813. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  42814. var w = this.bloomWeight;
  42815. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  42816. }
  42817. else {
  42818. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  42819. }
  42820. this.copyBack.autoClear = false;
  42821. }
  42822. if (this._imageProcessingEnabled) {
  42823. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42824. if (this._hdr) {
  42825. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  42826. }
  42827. }
  42828. if (this.fxaaEnabled) {
  42829. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42830. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  42831. this.fxaa.autoClear = !this.bloomEnabled && !this.imageProcessing;
  42832. }
  42833. else {
  42834. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  42835. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  42836. this.finalMerge.autoClear = !this.bloomEnabled && !this.imageProcessing;
  42837. }
  42838. if (this.bloomEnabled) {
  42839. if (this._hdr) {
  42840. this.copyBack.shareOutputWith(this.blurX);
  42841. if (this.imageProcessing) {
  42842. this.imageProcessing.shareOutputWith(this.pass);
  42843. this.imageProcessing.autoClear = false;
  42844. }
  42845. else if (this.fxaa) {
  42846. this.fxaa.shareOutputWith(this.pass);
  42847. }
  42848. else {
  42849. this.finalMerge.shareOutputWith(this.pass);
  42850. }
  42851. }
  42852. else {
  42853. if (this.fxaa) {
  42854. this.fxaa.shareOutputWith(this.pass);
  42855. }
  42856. else {
  42857. this.finalMerge.shareOutputWith(this.pass);
  42858. }
  42859. }
  42860. }
  42861. if (this._cameras !== null) {
  42862. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  42863. }
  42864. };
  42865. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  42866. for (var i = 0; i < this._cameras.length; i++) {
  42867. var camera = this._cameras[i];
  42868. if (this.pass) {
  42869. this.pass.dispose(camera);
  42870. this.pass = null;
  42871. }
  42872. if (this.highlights) {
  42873. this.highlights.dispose(camera);
  42874. this.highlights = null;
  42875. }
  42876. if (this.blurX) {
  42877. this.blurX.dispose(camera);
  42878. this.blurX = null;
  42879. }
  42880. if (this.blurY) {
  42881. this.blurY.dispose(camera);
  42882. this.blurY = null;
  42883. }
  42884. if (this.copyBack) {
  42885. this.copyBack.dispose(camera);
  42886. this.copyBack = null;
  42887. }
  42888. if (this.imageProcessing) {
  42889. this.imageProcessing.dispose(camera);
  42890. this.imageProcessing = null;
  42891. }
  42892. if (this.fxaa) {
  42893. this.fxaa.dispose(camera);
  42894. this.fxaa = null;
  42895. }
  42896. if (this.finalMerge) {
  42897. this.finalMerge.dispose(camera);
  42898. this.finalMerge = null;
  42899. }
  42900. }
  42901. };
  42902. // Dispose
  42903. DefaultRenderingPipeline.prototype.dispose = function () {
  42904. this._disposePostProcesses();
  42905. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  42906. _super.prototype.dispose.call(this);
  42907. };
  42908. // Serialize rendering pipeline
  42909. DefaultRenderingPipeline.prototype.serialize = function () {
  42910. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42911. serializationObject.customType = "DefaultRenderingPipeline";
  42912. return serializationObject;
  42913. };
  42914. // Parse serialized pipeline
  42915. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  42916. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  42917. };
  42918. return DefaultRenderingPipeline;
  42919. }(BABYLON.PostProcessRenderPipeline));
  42920. __decorate([
  42921. BABYLON.serialize()
  42922. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  42923. __decorate([
  42924. BABYLON.serialize()
  42925. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  42926. __decorate([
  42927. BABYLON.serialize()
  42928. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  42929. __decorate([
  42930. BABYLON.serialize()
  42931. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  42932. __decorate([
  42933. BABYLON.serialize()
  42934. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  42935. __decorate([
  42936. BABYLON.serialize()
  42937. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  42938. __decorate([
  42939. BABYLON.serialize()
  42940. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  42944. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  42945. })(BABYLON || (BABYLON = {}));
  42946. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  42947. BABYLON.Effect.ShadersStore={"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<shadowsVertexDeclaration>[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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\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#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef 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<shadowsVertexDeclaration>[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#include<fresnelFunction>\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\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\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\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\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\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 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\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\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\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\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\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=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\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}","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}","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]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\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;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst float LinearEncodePowerApprox=2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\n#ifndef FROMLINEARSPACE\n\nresult.rgb=pow(result.rgb,vec3(LinearEncodePowerApprox));\n#endif\nresult.rgb*=cameraExposureLinear;\n#ifdef VIGNETTE\n\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 \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\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}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}"};
  42948. 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","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","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(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"mat3 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}","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};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\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};","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\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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-darkness,0.,1.); \nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\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))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\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-darkness,0.,1.); \n\n\n\n\n\nreturn esm;\n}\n#endif","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\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,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,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,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 SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{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);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{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);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\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","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#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\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 vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\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/(kPi*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 specularColor,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); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \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 diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\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{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","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.0001));\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 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=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  42949. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  42950. module.exports = BABYLON;
  42951. };