babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2(1, 1)
  845. */
  846. Vector2.One = function () {
  847. return new Vector2(1, 1);
  848. };
  849. /**
  850. * Returns a new Vector2 set from the passed index element of the passed array.
  851. */
  852. Vector2.FromArray = function (array, offset) {
  853. if (offset === void 0) { offset = 0; }
  854. return new Vector2(array[offset], array[offset + 1]);
  855. };
  856. /**
  857. * Sets "result" from the passed index element of the passed array.
  858. */
  859. Vector2.FromArrayToRef = function (array, offset, result) {
  860. result.x = array[offset];
  861. result.y = array[offset + 1];
  862. };
  863. /**
  864. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  865. */
  866. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  867. var squared = amount * amount;
  868. var cubed = amount * squared;
  869. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  870. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  871. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  872. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  873. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  874. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  875. return new Vector2(x, y);
  876. };
  877. /**
  878. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  879. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  880. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  881. */
  882. Vector2.Clamp = function (value, min, max) {
  883. var x = value.x;
  884. x = (x > max.x) ? max.x : x;
  885. x = (x < min.x) ? min.x : x;
  886. var y = value.y;
  887. y = (y > max.y) ? max.y : y;
  888. y = (y < min.y) ? min.y : y;
  889. return new Vector2(x, y);
  890. };
  891. /**
  892. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  893. */
  894. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  895. var squared = amount * amount;
  896. var cubed = amount * squared;
  897. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  898. var part2 = (-2.0 * cubed) + (3.0 * squared);
  899. var part3 = (cubed - (2.0 * squared)) + amount;
  900. var part4 = cubed - squared;
  901. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  902. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  907. */
  908. Vector2.Lerp = function (start, end, amount) {
  909. var x = start.x + ((end.x - start.x) * amount);
  910. var y = start.y + ((end.y - start.y) * amount);
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns the dot product (float) of the vector "left" and the vector "right".
  915. */
  916. Vector2.Dot = function (left, right) {
  917. return left.x * right.x + left.y * right.y;
  918. };
  919. /**
  920. * Returns a new Vector2 equal to the normalized passed vector.
  921. */
  922. Vector2.Normalize = function (vector) {
  923. var newVector = vector.clone();
  924. newVector.normalize();
  925. return newVector;
  926. };
  927. /**
  928. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  929. */
  930. Vector2.Minimize = function (left, right) {
  931. var x = (left.x < right.x) ? left.x : right.x;
  932. var y = (left.y < right.y) ? left.y : right.y;
  933. return new Vector2(x, y);
  934. };
  935. /**
  936. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  937. */
  938. Vector2.Maximize = function (left, right) {
  939. var x = (left.x > right.x) ? left.x : right.x;
  940. var y = (left.y > right.y) ? left.y : right.y;
  941. return new Vector2(x, y);
  942. };
  943. /**
  944. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  945. */
  946. Vector2.Transform = function (vector, transformation) {
  947. var r = Vector2.Zero();
  948. Vector2.TransformToRef(vector, transformation, r);
  949. return r;
  950. };
  951. /**
  952. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  953. */
  954. Vector2.TransformToRef = function (vector, transformation, result) {
  955. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  956. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  957. result.x = x;
  958. result.y = y;
  959. };
  960. /**
  961. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  962. */
  963. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  964. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  965. var sign = a < 0 ? -1 : 1;
  966. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  967. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  968. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  969. };
  970. /**
  971. * Returns the distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.Distance = function (value1, value2) {
  974. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  975. };
  976. /**
  977. * Returns the squared distance (float) between the vectors "value1" and "value2".
  978. */
  979. Vector2.DistanceSquared = function (value1, value2) {
  980. var x = value1.x - value2.x;
  981. var y = value1.y - value2.y;
  982. return (x * x) + (y * y);
  983. };
  984. /**
  985. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  986. */
  987. Vector2.Center = function (value1, value2) {
  988. var center = value1.add(value2);
  989. center.scaleInPlace(0.5);
  990. return center;
  991. };
  992. /**
  993. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  994. */
  995. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  996. var l2 = Vector2.DistanceSquared(segA, segB);
  997. if (l2 === 0.0) {
  998. return Vector2.Distance(p, segA);
  999. }
  1000. var v = segB.subtract(segA);
  1001. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1002. var proj = segA.add(v.multiplyByFloats(t, t));
  1003. return Vector2.Distance(p, proj);
  1004. };
  1005. return Vector2;
  1006. }());
  1007. BABYLON.Vector2 = Vector2;
  1008. var Vector3 = (function () {
  1009. /**
  1010. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1011. * A Vector3 is the main object used in 3D geometry.
  1012. * It can represent etiher the coordinates of a point the space, either a direction.
  1013. */
  1014. function Vector3(x, y, z) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. }
  1019. /**
  1020. * Returns a string with the Vector3 coordinates.
  1021. */
  1022. Vector3.prototype.toString = function () {
  1023. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1024. };
  1025. /**
  1026. * Returns the string "Vector3"
  1027. */
  1028. Vector3.prototype.getClassName = function () {
  1029. return "Vector3";
  1030. };
  1031. /**
  1032. * Returns the Vector hash code.
  1033. */
  1034. Vector3.prototype.getHashCode = function () {
  1035. var hash = this.x || 0;
  1036. hash = (hash * 397) ^ (this.y || 0);
  1037. hash = (hash * 397) ^ (this.z || 0);
  1038. return hash;
  1039. };
  1040. // Operators
  1041. /**
  1042. * Returns a new array with three elements : the coordinates the Vector3.
  1043. */
  1044. Vector3.prototype.asArray = function () {
  1045. var result = [];
  1046. this.toArray(result, 0);
  1047. return result;
  1048. };
  1049. /**
  1050. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1051. * Returns the Vector3.
  1052. */
  1053. Vector3.prototype.toArray = function (array, index) {
  1054. if (index === void 0) { index = 0; }
  1055. array[index] = this.x;
  1056. array[index + 1] = this.y;
  1057. array[index + 2] = this.z;
  1058. return this;
  1059. };
  1060. /**
  1061. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1062. */
  1063. Vector3.prototype.toQuaternion = function () {
  1064. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1065. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1066. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1067. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1068. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1069. var cosy = Math.cos(this.y * 0.5);
  1070. var siny = Math.sin(this.y * 0.5);
  1071. result.x = coszMinusx * siny;
  1072. result.y = -sinzMinusx * siny;
  1073. result.z = sinxPlusz * cosy;
  1074. result.w = cosxPlusz * cosy;
  1075. return result;
  1076. };
  1077. /**
  1078. * Adds the passed vector to the current Vector3.
  1079. * Returns the updated Vector3.
  1080. */
  1081. Vector3.prototype.addInPlace = function (otherVector) {
  1082. this.x += otherVector.x;
  1083. this.y += otherVector.y;
  1084. this.z += otherVector.z;
  1085. return this;
  1086. };
  1087. /**
  1088. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1089. */
  1090. Vector3.prototype.add = function (otherVector) {
  1091. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1092. };
  1093. /**
  1094. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1095. * Returns the current Vector3.
  1096. */
  1097. Vector3.prototype.addToRef = function (otherVector, result) {
  1098. result.x = this.x + otherVector.x;
  1099. result.y = this.y + otherVector.y;
  1100. result.z = this.z + otherVector.z;
  1101. return this;
  1102. };
  1103. /**
  1104. * Subtract the passed vector from the current Vector3.
  1105. * Returns the updated Vector3.
  1106. */
  1107. Vector3.prototype.subtractInPlace = function (otherVector) {
  1108. this.x -= otherVector.x;
  1109. this.y -= otherVector.y;
  1110. this.z -= otherVector.z;
  1111. return this;
  1112. };
  1113. /**
  1114. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1115. */
  1116. Vector3.prototype.subtract = function (otherVector) {
  1117. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1118. };
  1119. /**
  1120. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1121. * Returns the current Vector3.
  1122. */
  1123. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1124. result.x = this.x - otherVector.x;
  1125. result.y = this.y - otherVector.y;
  1126. result.z = this.z - otherVector.z;
  1127. return this;
  1128. };
  1129. /**
  1130. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1131. */
  1132. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1133. return new Vector3(this.x - x, this.y - y, this.z - z);
  1134. };
  1135. /**
  1136. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1137. * Returns the current Vector3.
  1138. */
  1139. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1140. result.x = this.x - x;
  1141. result.y = this.y - y;
  1142. result.z = this.z - z;
  1143. return this;
  1144. };
  1145. /**
  1146. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1147. */
  1148. Vector3.prototype.negate = function () {
  1149. return new Vector3(-this.x, -this.y, -this.z);
  1150. };
  1151. /**
  1152. * Multiplies the Vector3 coordinates by the float "scale".
  1153. * Returns the updated Vector3.
  1154. */
  1155. Vector3.prototype.scaleInPlace = function (scale) {
  1156. this.x *= scale;
  1157. this.y *= scale;
  1158. this.z *= scale;
  1159. return this;
  1160. };
  1161. /**
  1162. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1163. */
  1164. Vector3.prototype.scale = function (scale) {
  1165. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1166. };
  1167. /**
  1168. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1169. * Returns the current Vector3.
  1170. */
  1171. Vector3.prototype.scaleToRef = function (scale, result) {
  1172. result.x = this.x * scale;
  1173. result.y = this.y * scale;
  1174. result.z = this.z * scale;
  1175. return this;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1179. */
  1180. Vector3.prototype.equals = function (otherVector) {
  1181. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1182. };
  1183. /**
  1184. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1185. */
  1186. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1187. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1188. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1189. };
  1190. /**
  1191. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1192. */
  1193. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1194. return this.x === x && this.y === y && this.z === z;
  1195. };
  1196. /**
  1197. * Muliplies the current Vector3 coordinates by the passed ones.
  1198. * Returns the updated Vector3.
  1199. */
  1200. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1201. this.x *= otherVector.x;
  1202. this.y *= otherVector.y;
  1203. this.z *= otherVector.z;
  1204. return this;
  1205. };
  1206. /**
  1207. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1208. */
  1209. Vector3.prototype.multiply = function (otherVector) {
  1210. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1211. };
  1212. /**
  1213. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1214. * Returns the current Vector3.
  1215. */
  1216. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1217. result.x = this.x * otherVector.x;
  1218. result.y = this.y * otherVector.y;
  1219. result.z = this.z * otherVector.z;
  1220. return this;
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1224. */
  1225. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1226. return new Vector3(this.x * x, this.y * y, this.z * z);
  1227. };
  1228. /**
  1229. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1230. */
  1231. Vector3.prototype.divide = function (otherVector) {
  1232. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1233. };
  1234. /**
  1235. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1236. * Returns the current Vector3.
  1237. */
  1238. Vector3.prototype.divideToRef = function (otherVector, result) {
  1239. result.x = this.x / otherVector.x;
  1240. result.y = this.y / otherVector.y;
  1241. result.z = this.z / otherVector.z;
  1242. return this;
  1243. };
  1244. /**
  1245. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1246. * Returns the updated Vector3.
  1247. */
  1248. Vector3.prototype.MinimizeInPlace = function (other) {
  1249. if (other.x < this.x)
  1250. this.x = other.x;
  1251. if (other.y < this.y)
  1252. this.y = other.y;
  1253. if (other.z < this.z)
  1254. this.z = other.z;
  1255. return this;
  1256. };
  1257. /**
  1258. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1259. * Returns the updated Vector3.
  1260. */
  1261. Vector3.prototype.MaximizeInPlace = function (other) {
  1262. if (other.x > this.x)
  1263. this.x = other.x;
  1264. if (other.y > this.y)
  1265. this.y = other.y;
  1266. if (other.z > this.z)
  1267. this.z = other.z;
  1268. return this;
  1269. };
  1270. // Properties
  1271. /**
  1272. * Returns the length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.length = function () {
  1275. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. /**
  1278. * Returns the squared length of the Vector3 (float).
  1279. */
  1280. Vector3.prototype.lengthSquared = function () {
  1281. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1282. };
  1283. // Methods
  1284. /**
  1285. * Normalize the current Vector3.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.normalize = function () {
  1289. var len = this.length();
  1290. if (len === 0 || len === 1.0)
  1291. return this;
  1292. var num = 1.0 / len;
  1293. this.x *= num;
  1294. this.y *= num;
  1295. this.z *= num;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new Vector3 copied from the current Vector3.
  1300. */
  1301. Vector3.prototype.clone = function () {
  1302. return new Vector3(this.x, this.y, this.z);
  1303. };
  1304. /**
  1305. * Copies the passed vector coordinates to the current Vector3 ones.
  1306. * Returns the updated Vector3.
  1307. */
  1308. Vector3.prototype.copyFrom = function (source) {
  1309. this.x = source.x;
  1310. this.y = source.y;
  1311. this.z = source.z;
  1312. return this;
  1313. };
  1314. /**
  1315. * Copies the passed floats to the current Vector3 coordinates.
  1316. * Returns the updated Vector3.
  1317. */
  1318. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. return this;
  1323. };
  1324. /**
  1325. * Copies the passed floats to the current Vector3 coordinates.
  1326. * Returns the updated Vector3.
  1327. */
  1328. Vector3.prototype.set = function (x, y, z) {
  1329. return this.copyFromFloats(x, y, z);
  1330. };
  1331. // Statics
  1332. /**
  1333. *
  1334. */
  1335. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1336. var d0 = Vector3.Dot(vector0, axis) - size;
  1337. var d1 = Vector3.Dot(vector1, axis) - size;
  1338. var s = d0 / (d0 - d1);
  1339. return s;
  1340. };
  1341. /**
  1342. * Returns a new Vector3 set from the index "offset" of the passed array.
  1343. */
  1344. Vector3.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1352. * This function is deprecated. Use FromArray instead.
  1353. */
  1354. Vector3.FromFloatArray = function (array, offset) {
  1355. return Vector3.FromArray(array, offset);
  1356. };
  1357. /**
  1358. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1359. */
  1360. Vector3.FromArrayToRef = function (array, offset, result) {
  1361. result.x = array[offset];
  1362. result.y = array[offset + 1];
  1363. result.z = array[offset + 2];
  1364. };
  1365. /**
  1366. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1367. * This function is deprecated. Use FromArrayToRef instead.
  1368. */
  1369. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1370. return Vector3.FromArrayToRef(array, offset, result);
  1371. };
  1372. /**
  1373. * Sets the passed vector "result" with the passed floats.
  1374. */
  1375. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1376. result.x = x;
  1377. result.y = y;
  1378. result.z = z;
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1382. */
  1383. Vector3.Zero = function () {
  1384. return new Vector3(0.0, 0.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1388. */
  1389. Vector3.One = function () {
  1390. return new Vector3(1.0, 1.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1394. */
  1395. Vector3.Up = function () {
  1396. return new Vector3(0.0, 1.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1400. */
  1401. Vector3.Forward = function () {
  1402. return new Vector3(0.0, 0.0, 1.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1406. */
  1407. Vector3.Right = function () {
  1408. return new Vector3(1.0, 0.0, 0.0);
  1409. };
  1410. /**
  1411. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1412. */
  1413. Vector3.Left = function () {
  1414. return new Vector3(-1.0, 0.0, 0.0);
  1415. };
  1416. /**
  1417. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1418. * This method computes tranformed coordinates only, not transformed direction vectors.
  1419. */
  1420. Vector3.TransformCoordinates = function (vector, transformation) {
  1421. var result = Vector3.Zero();
  1422. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1423. return result;
  1424. };
  1425. /**
  1426. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1427. * This method computes tranformed coordinates only, not transformed direction vectors.
  1428. */
  1429. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1430. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1431. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1432. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1433. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1434. result.x = x / w;
  1435. result.y = y / w;
  1436. result.z = z / w;
  1437. };
  1438. /**
  1439. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1440. * This method computes tranformed coordinates only, not transformed direction vectors.
  1441. */
  1442. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1443. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1444. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1445. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1446. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1447. result.x = rx / rw;
  1448. result.y = ry / rw;
  1449. result.z = rz / rw;
  1450. };
  1451. /**
  1452. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1453. * This methods computes transformed normalized direction vectors only.
  1454. */
  1455. Vector3.TransformNormal = function (vector, transformation) {
  1456. var result = Vector3.Zero();
  1457. Vector3.TransformNormalToRef(vector, transformation, result);
  1458. return result;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1465. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1466. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1467. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1468. result.x = x;
  1469. result.y = y;
  1470. result.z = z;
  1471. };
  1472. /**
  1473. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1474. * This methods computes transformed normalized direction vectors only.
  1475. */
  1476. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1477. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1478. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1479. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1480. };
  1481. /**
  1482. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1483. */
  1484. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1485. var squared = amount * amount;
  1486. var cubed = amount * squared;
  1487. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1488. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1489. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1490. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1491. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1492. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1493. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1494. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1495. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1496. return new Vector3(x, y, z);
  1497. };
  1498. /**
  1499. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1500. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1501. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1502. */
  1503. Vector3.Clamp = function (value, min, max) {
  1504. var x = value.x;
  1505. x = (x > max.x) ? max.x : x;
  1506. x = (x < min.x) ? min.x : x;
  1507. var y = value.y;
  1508. y = (y > max.y) ? max.y : y;
  1509. y = (y < min.y) ? min.y : y;
  1510. var z = value.z;
  1511. z = (z > max.z) ? max.z : z;
  1512. z = (z < min.z) ? min.z : z;
  1513. return new Vector3(x, y, z);
  1514. };
  1515. /**
  1516. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1517. */
  1518. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1519. var squared = amount * amount;
  1520. var cubed = amount * squared;
  1521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1523. var part3 = (cubed - (2.0 * squared)) + amount;
  1524. var part4 = cubed - squared;
  1525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1527. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1528. return new Vector3(x, y, z);
  1529. };
  1530. /**
  1531. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1532. */
  1533. Vector3.Lerp = function (start, end, amount) {
  1534. var result = new Vector3(0, 0, 0);
  1535. Vector3.LerpToRef(start, end, amount, result);
  1536. return result;
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1540. */
  1541. Vector3.LerpToRef = function (start, end, amount, result) {
  1542. result.x = start.x + ((end.x - start.x) * amount);
  1543. result.y = start.y + ((end.y - start.y) * amount);
  1544. result.z = start.z + ((end.z - start.z) * amount);
  1545. };
  1546. /**
  1547. * Returns the dot product (float) between the vectors "left" and "right".
  1548. */
  1549. Vector3.Dot = function (left, right) {
  1550. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1551. };
  1552. /**
  1553. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1554. * The cross product is then orthogonal to both "left" and "right".
  1555. */
  1556. Vector3.Cross = function (left, right) {
  1557. var result = Vector3.Zero();
  1558. Vector3.CrossToRef(left, right, result);
  1559. return result;
  1560. };
  1561. /**
  1562. * Sets the passed vector "result" with the cross product of "left" and "right".
  1563. * The cross product is then orthogonal to both "left" and "right".
  1564. */
  1565. Vector3.CrossToRef = function (left, right, result) {
  1566. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1567. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1568. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1569. result.copyFrom(MathTmp.Vector3[0]);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 as the normalization of the passed vector.
  1573. */
  1574. Vector3.Normalize = function (vector) {
  1575. var result = Vector3.Zero();
  1576. Vector3.NormalizeToRef(vector, result);
  1577. return result;
  1578. };
  1579. /**
  1580. * Sets the passed vector "result" with the normalization of the passed first vector.
  1581. */
  1582. Vector3.NormalizeToRef = function (vector, result) {
  1583. result.copyFrom(vector);
  1584. result.normalize();
  1585. };
  1586. Vector3.Project = function (vector, world, transform, viewport) {
  1587. var cw = viewport.width;
  1588. var ch = viewport.height;
  1589. var cx = viewport.x;
  1590. var cy = viewport.y;
  1591. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1592. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1593. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1594. world.multiplyToRef(transform, matrix);
  1595. matrix.multiplyToRef(viewportMatrix, matrix);
  1596. return Vector3.TransformCoordinates(vector, matrix);
  1597. };
  1598. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1599. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1600. world.multiplyToRef(transform, matrix);
  1601. matrix.invert();
  1602. source.x = source.x / viewportWidth * 2 - 1;
  1603. source.y = -(source.y / viewportHeight * 2 - 1);
  1604. var vector = Vector3.TransformCoordinates(source, matrix);
  1605. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1606. if (MathTools.WithinEpsilon(num, 1.0)) {
  1607. vector = vector.scale(1.0 / num);
  1608. }
  1609. return vector;
  1610. };
  1611. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1612. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1613. world.multiplyToRef(view, matrix);
  1614. matrix.multiplyToRef(projection, matrix);
  1615. matrix.invert();
  1616. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1617. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1618. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1619. if (MathTools.WithinEpsilon(num, 1.0)) {
  1620. vector = vector.scale(1.0 / num);
  1621. }
  1622. return vector;
  1623. };
  1624. Vector3.Minimize = function (left, right) {
  1625. var min = left.clone();
  1626. min.MinimizeInPlace(right);
  1627. return min;
  1628. };
  1629. Vector3.Maximize = function (left, right) {
  1630. var max = left.clone();
  1631. max.MaximizeInPlace(right);
  1632. return max;
  1633. };
  1634. /**
  1635. * Returns the distance (float) between the vectors "value1" and "value2".
  1636. */
  1637. Vector3.Distance = function (value1, value2) {
  1638. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1639. };
  1640. /**
  1641. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1642. */
  1643. Vector3.DistanceSquared = function (value1, value2) {
  1644. var x = value1.x - value2.x;
  1645. var y = value1.y - value2.y;
  1646. var z = value1.z - value2.z;
  1647. return (x * x) + (y * y) + (z * z);
  1648. };
  1649. /**
  1650. * Returns a new Vector3 located at the center between "value1" and "value2".
  1651. */
  1652. Vector3.Center = function (value1, value2) {
  1653. var center = value1.add(value2);
  1654. center.scaleInPlace(0.5);
  1655. return center;
  1656. };
  1657. /**
  1658. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1659. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1660. * to something in order to rotate it from its local system to the given target system.
  1661. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1662. * Returns a new Vector3.
  1663. */
  1664. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1665. var rotation = Vector3.Zero();
  1666. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1667. return rotation;
  1668. };
  1669. /**
  1670. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1671. */
  1672. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1673. var quat = MathTmp.Quaternion[0];
  1674. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1675. quat.toEulerAnglesToRef(ref);
  1676. };
  1677. return Vector3;
  1678. }());
  1679. BABYLON.Vector3 = Vector3;
  1680. //Vector4 class created for EulerAngle class conversion to Quaternion
  1681. var Vector4 = (function () {
  1682. /**
  1683. * Creates a Vector4 object from the passed floats.
  1684. */
  1685. function Vector4(x, y, z, w) {
  1686. this.x = x;
  1687. this.y = y;
  1688. this.z = z;
  1689. this.w = w;
  1690. }
  1691. /**
  1692. * Returns the string with the Vector4 coordinates.
  1693. */
  1694. Vector4.prototype.toString = function () {
  1695. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1696. };
  1697. /**
  1698. * Returns the string "Vector4".
  1699. */
  1700. Vector4.prototype.getClassName = function () {
  1701. return "Vector4";
  1702. };
  1703. /**
  1704. * Returns the Vector4 hash code.
  1705. */
  1706. Vector4.prototype.getHashCode = function () {
  1707. var hash = this.x || 0;
  1708. hash = (hash * 397) ^ (this.y || 0);
  1709. hash = (hash * 397) ^ (this.z || 0);
  1710. hash = (hash * 397) ^ (this.w || 0);
  1711. return hash;
  1712. };
  1713. // Operators
  1714. /**
  1715. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1716. */
  1717. Vector4.prototype.asArray = function () {
  1718. var result = [];
  1719. this.toArray(result, 0);
  1720. return result;
  1721. };
  1722. /**
  1723. * Populates the passed array from the passed index with the Vector4 coordinates.
  1724. * Returns the Vector4.
  1725. */
  1726. Vector4.prototype.toArray = function (array, index) {
  1727. if (index === undefined) {
  1728. index = 0;
  1729. }
  1730. array[index] = this.x;
  1731. array[index + 1] = this.y;
  1732. array[index + 2] = this.z;
  1733. array[index + 3] = this.w;
  1734. return this;
  1735. };
  1736. /**
  1737. * Adds the passed vector to the current Vector4.
  1738. * Returns the updated Vector4.
  1739. */
  1740. Vector4.prototype.addInPlace = function (otherVector) {
  1741. this.x += otherVector.x;
  1742. this.y += otherVector.y;
  1743. this.z += otherVector.z;
  1744. this.w += otherVector.w;
  1745. return this;
  1746. };
  1747. /**
  1748. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1749. */
  1750. Vector4.prototype.add = function (otherVector) {
  1751. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1752. };
  1753. /**
  1754. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1755. * Returns the current Vector4.
  1756. */
  1757. Vector4.prototype.addToRef = function (otherVector, result) {
  1758. result.x = this.x + otherVector.x;
  1759. result.y = this.y + otherVector.y;
  1760. result.z = this.z + otherVector.z;
  1761. result.w = this.w + otherVector.w;
  1762. return this;
  1763. };
  1764. /**
  1765. * Subtract in place the passed vector from the current Vector4.
  1766. * Returns the updated Vector4.
  1767. */
  1768. Vector4.prototype.subtractInPlace = function (otherVector) {
  1769. this.x -= otherVector.x;
  1770. this.y -= otherVector.y;
  1771. this.z -= otherVector.z;
  1772. this.w -= otherVector.w;
  1773. return this;
  1774. };
  1775. /**
  1776. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1777. */
  1778. Vector4.prototype.subtract = function (otherVector) {
  1779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1780. };
  1781. /**
  1782. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1783. * Returns the current Vector4.
  1784. */
  1785. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1786. result.x = this.x - otherVector.x;
  1787. result.y = this.y - otherVector.y;
  1788. result.z = this.z - otherVector.z;
  1789. result.w = this.w - otherVector.w;
  1790. return this;
  1791. };
  1792. /**
  1793. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1794. */
  1795. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1796. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1797. };
  1798. /**
  1799. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1800. * Returns the current Vector4.
  1801. */
  1802. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1803. result.x = this.x - x;
  1804. result.y = this.y - y;
  1805. result.z = this.z - z;
  1806. result.w = this.w - w;
  1807. return this;
  1808. };
  1809. /**
  1810. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1811. */
  1812. Vector4.prototype.negate = function () {
  1813. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1814. };
  1815. /**
  1816. * Multiplies the current Vector4 coordinates by scale (float).
  1817. * Returns the updated Vector4.
  1818. */
  1819. Vector4.prototype.scaleInPlace = function (scale) {
  1820. this.x *= scale;
  1821. this.y *= scale;
  1822. this.z *= scale;
  1823. this.w *= scale;
  1824. return this;
  1825. };
  1826. /**
  1827. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1828. */
  1829. Vector4.prototype.scale = function (scale) {
  1830. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1831. };
  1832. /**
  1833. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1834. * Returns the current Vector4.
  1835. */
  1836. Vector4.prototype.scaleToRef = function (scale, result) {
  1837. result.x = this.x * scale;
  1838. result.y = this.y * scale;
  1839. result.z = this.z * scale;
  1840. result.w = this.w * scale;
  1841. return this;
  1842. };
  1843. /**
  1844. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1845. */
  1846. Vector4.prototype.equals = function (otherVector) {
  1847. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1848. };
  1849. /**
  1850. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1851. */
  1852. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1853. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1854. return otherVector
  1855. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1856. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1857. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1858. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1859. };
  1860. /**
  1861. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1862. */
  1863. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1864. return this.x === x && this.y === y && this.z === z && this.w === w;
  1865. };
  1866. /**
  1867. * Multiplies in place the current Vector4 by the passed one.
  1868. * Returns the updated Vector4.
  1869. */
  1870. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1871. this.x *= otherVector.x;
  1872. this.y *= otherVector.y;
  1873. this.z *= otherVector.z;
  1874. this.w *= otherVector.w;
  1875. return this;
  1876. };
  1877. /**
  1878. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1879. */
  1880. Vector4.prototype.multiply = function (otherVector) {
  1881. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1882. };
  1883. /**
  1884. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1885. * Returns the current Vector4.
  1886. */
  1887. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1888. result.x = this.x * otherVector.x;
  1889. result.y = this.y * otherVector.y;
  1890. result.z = this.z * otherVector.z;
  1891. result.w = this.w * otherVector.w;
  1892. return this;
  1893. };
  1894. /**
  1895. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1896. */
  1897. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1898. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1899. };
  1900. /**
  1901. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1902. */
  1903. Vector4.prototype.divide = function (otherVector) {
  1904. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1905. };
  1906. /**
  1907. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1908. * Returns the current Vector4.
  1909. */
  1910. Vector4.prototype.divideToRef = function (otherVector, result) {
  1911. result.x = this.x / otherVector.x;
  1912. result.y = this.y / otherVector.y;
  1913. result.z = this.z / otherVector.z;
  1914. result.w = this.w / otherVector.w;
  1915. return this;
  1916. };
  1917. /**
  1918. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1919. */
  1920. Vector4.prototype.MinimizeInPlace = function (other) {
  1921. if (other.x < this.x)
  1922. this.x = other.x;
  1923. if (other.y < this.y)
  1924. this.y = other.y;
  1925. if (other.z < this.z)
  1926. this.z = other.z;
  1927. if (other.w < this.w)
  1928. this.w = other.w;
  1929. return this;
  1930. };
  1931. /**
  1932. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1933. */
  1934. Vector4.prototype.MaximizeInPlace = function (other) {
  1935. if (other.x > this.x)
  1936. this.x = other.x;
  1937. if (other.y > this.y)
  1938. this.y = other.y;
  1939. if (other.z > this.z)
  1940. this.z = other.z;
  1941. if (other.w > this.w)
  1942. this.w = other.w;
  1943. return this;
  1944. };
  1945. // Properties
  1946. /**
  1947. * Returns the Vector4 length (float).
  1948. */
  1949. Vector4.prototype.length = function () {
  1950. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1951. };
  1952. /**
  1953. * Returns the Vector4 squared length (float).
  1954. */
  1955. Vector4.prototype.lengthSquared = function () {
  1956. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1957. };
  1958. // Methods
  1959. /**
  1960. * Normalizes in place the Vector4.
  1961. * Returns the updated Vector4.
  1962. */
  1963. Vector4.prototype.normalize = function () {
  1964. var len = this.length();
  1965. if (len === 0)
  1966. return this;
  1967. var num = 1.0 / len;
  1968. this.x *= num;
  1969. this.y *= num;
  1970. this.z *= num;
  1971. this.w *= num;
  1972. return this;
  1973. };
  1974. /**
  1975. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1976. */
  1977. Vector4.prototype.toVector3 = function () {
  1978. return new Vector3(this.x, this.y, this.z);
  1979. };
  1980. /**
  1981. * Returns a new Vector4 copied from the current one.
  1982. */
  1983. Vector4.prototype.clone = function () {
  1984. return new Vector4(this.x, this.y, this.z, this.w);
  1985. };
  1986. /**
  1987. * Updates the current Vector4 with the passed one coordinates.
  1988. * Returns the updated Vector4.
  1989. */
  1990. Vector4.prototype.copyFrom = function (source) {
  1991. this.x = source.x;
  1992. this.y = source.y;
  1993. this.z = source.z;
  1994. this.w = source.w;
  1995. return this;
  1996. };
  1997. /**
  1998. * Updates the current Vector4 coordinates with the passed floats.
  1999. * Returns the updated Vector4.
  2000. */
  2001. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2002. this.x = x;
  2003. this.y = y;
  2004. this.z = z;
  2005. this.w = w;
  2006. return this;
  2007. };
  2008. /**
  2009. * Updates the current Vector4 coordinates with the passed floats.
  2010. * Returns the updated Vector4.
  2011. */
  2012. Vector4.prototype.set = function (x, y, z, w) {
  2013. return this.copyFromFloats(x, y, z, w);
  2014. };
  2015. // Statics
  2016. /**
  2017. * Returns a new Vector4 set from the starting index of the passed array.
  2018. */
  2019. Vector4.FromArray = function (array, offset) {
  2020. if (!offset) {
  2021. offset = 0;
  2022. }
  2023. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2024. };
  2025. /**
  2026. * Updates the passed vector "result" from the starting index of the passed array.
  2027. */
  2028. Vector4.FromArrayToRef = function (array, offset, result) {
  2029. result.x = array[offset];
  2030. result.y = array[offset + 1];
  2031. result.z = array[offset + 2];
  2032. result.w = array[offset + 3];
  2033. };
  2034. /**
  2035. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2036. */
  2037. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2038. Vector4.FromArrayToRef(array, offset, result);
  2039. };
  2040. /**
  2041. * Updates the passed vector "result" coordinates from the passed floats.
  2042. */
  2043. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2044. result.x = x;
  2045. result.y = y;
  2046. result.z = z;
  2047. result.w = w;
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2051. */
  2052. Vector4.Zero = function () {
  2053. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2054. };
  2055. /**
  2056. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2057. */
  2058. Vector4.One = function () {
  2059. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2060. };
  2061. /**
  2062. * Returns a new normalized Vector4 from the passed one.
  2063. */
  2064. Vector4.Normalize = function (vector) {
  2065. var result = Vector4.Zero();
  2066. Vector4.NormalizeToRef(vector, result);
  2067. return result;
  2068. };
  2069. /**
  2070. * Updates the passed vector "result" from the normalization of the passed one.
  2071. */
  2072. Vector4.NormalizeToRef = function (vector, result) {
  2073. result.copyFrom(vector);
  2074. result.normalize();
  2075. };
  2076. Vector4.Minimize = function (left, right) {
  2077. var min = left.clone();
  2078. min.MinimizeInPlace(right);
  2079. return min;
  2080. };
  2081. Vector4.Maximize = function (left, right) {
  2082. var max = left.clone();
  2083. max.MaximizeInPlace(right);
  2084. return max;
  2085. };
  2086. /**
  2087. * Returns the distance (float) between the vectors "value1" and "value2".
  2088. */
  2089. Vector4.Distance = function (value1, value2) {
  2090. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2091. };
  2092. /**
  2093. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2094. */
  2095. Vector4.DistanceSquared = function (value1, value2) {
  2096. var x = value1.x - value2.x;
  2097. var y = value1.y - value2.y;
  2098. var z = value1.z - value2.z;
  2099. var w = value1.w - value2.w;
  2100. return (x * x) + (y * y) + (z * z) + (w * w);
  2101. };
  2102. /**
  2103. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2104. */
  2105. Vector4.Center = function (value1, value2) {
  2106. var center = value1.add(value2);
  2107. center.scaleInPlace(0.5);
  2108. return center;
  2109. };
  2110. /**
  2111. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2112. * This methods computes transformed normalized direction vectors only.
  2113. */
  2114. Vector4.TransformNormal = function (vector, transformation) {
  2115. var result = Vector4.Zero();
  2116. Vector4.TransformNormalToRef(vector, transformation, result);
  2117. return result;
  2118. };
  2119. /**
  2120. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2121. * This methods computes transformed normalized direction vectors only.
  2122. */
  2123. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2124. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2125. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2126. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2127. result.x = x;
  2128. result.y = y;
  2129. result.z = z;
  2130. result.w = vector.w;
  2131. };
  2132. /**
  2133. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2134. * This methods computes transformed normalized direction vectors only.
  2135. */
  2136. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2137. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2138. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2139. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2140. result.w = w;
  2141. };
  2142. return Vector4;
  2143. }());
  2144. BABYLON.Vector4 = Vector4;
  2145. var Size = (function () {
  2146. /**
  2147. * Creates a Size object from the passed width and height (floats).
  2148. */
  2149. function Size(width, height) {
  2150. this.width = width;
  2151. this.height = height;
  2152. }
  2153. // Returns a string with the Size width and height.
  2154. Size.prototype.toString = function () {
  2155. return "{W: " + this.width + ", H: " + this.height + "}";
  2156. };
  2157. /**
  2158. * Returns the string "Size"
  2159. */
  2160. Size.prototype.getClassName = function () {
  2161. return "Size";
  2162. };
  2163. /**
  2164. * Returns the Size hash code.
  2165. */
  2166. Size.prototype.getHashCode = function () {
  2167. var hash = this.width || 0;
  2168. hash = (hash * 397) ^ (this.height || 0);
  2169. return hash;
  2170. };
  2171. /**
  2172. * Updates the current size from the passed one.
  2173. * Returns the updated Size.
  2174. */
  2175. Size.prototype.copyFrom = function (src) {
  2176. this.width = src.width;
  2177. this.height = src.height;
  2178. };
  2179. /**
  2180. * Updates in place the current Size from the passed floats.
  2181. * Returns the updated Size.
  2182. */
  2183. Size.prototype.copyFromFloats = function (width, height) {
  2184. this.width = width;
  2185. this.height = height;
  2186. return this;
  2187. };
  2188. /**
  2189. * Updates in place the current Size from the passed floats.
  2190. * Returns the updated Size.
  2191. */
  2192. Size.prototype.set = function (width, height) {
  2193. return this.copyFromFloats(width, height);
  2194. };
  2195. /**
  2196. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2197. */
  2198. Size.prototype.multiplyByFloats = function (w, h) {
  2199. return new Size(this.width * w, this.height * h);
  2200. };
  2201. /**
  2202. * Returns a new Size copied from the passed one.
  2203. */
  2204. Size.prototype.clone = function () {
  2205. return new Size(this.width, this.height);
  2206. };
  2207. /**
  2208. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2209. */
  2210. Size.prototype.equals = function (other) {
  2211. if (!other) {
  2212. return false;
  2213. }
  2214. return (this.width === other.width) && (this.height === other.height);
  2215. };
  2216. Object.defineProperty(Size.prototype, "surface", {
  2217. /**
  2218. * Returns the surface of the Size : width * height (float).
  2219. */
  2220. get: function () {
  2221. return this.width * this.height;
  2222. },
  2223. enumerable: true,
  2224. configurable: true
  2225. });
  2226. /**
  2227. * Returns a new Size set to (0.0, 0.0)
  2228. */
  2229. Size.Zero = function () {
  2230. return new Size(0.0, 0.0);
  2231. };
  2232. /**
  2233. * Returns a new Size set as the addition result of the current Size and the passed one.
  2234. */
  2235. Size.prototype.add = function (otherSize) {
  2236. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2237. return r;
  2238. };
  2239. /**
  2240. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2241. */
  2242. Size.prototype.subtract = function (otherSize) {
  2243. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2244. return r;
  2245. };
  2246. /**
  2247. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2248. */
  2249. Size.Lerp = function (start, end, amount) {
  2250. var w = start.width + ((end.width - start.width) * amount);
  2251. var h = start.height + ((end.height - start.height) * amount);
  2252. return new Size(w, h);
  2253. };
  2254. return Size;
  2255. }());
  2256. BABYLON.Size = Size;
  2257. var Quaternion = (function () {
  2258. /**
  2259. * Creates a new Quaternion from the passed floats.
  2260. */
  2261. function Quaternion(x, y, z, w) {
  2262. if (x === void 0) { x = 0.0; }
  2263. if (y === void 0) { y = 0.0; }
  2264. if (z === void 0) { z = 0.0; }
  2265. if (w === void 0) { w = 1.0; }
  2266. this.x = x;
  2267. this.y = y;
  2268. this.z = z;
  2269. this.w = w;
  2270. }
  2271. /**
  2272. * Returns a string with the Quaternion coordinates.
  2273. */
  2274. Quaternion.prototype.toString = function () {
  2275. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2276. };
  2277. /**
  2278. * Returns the string "Quaternion".
  2279. */
  2280. Quaternion.prototype.getClassName = function () {
  2281. return "Quaternion";
  2282. };
  2283. /**
  2284. * Returns the Quaternion hash code.
  2285. */
  2286. Quaternion.prototype.getHashCode = function () {
  2287. var hash = this.x || 0;
  2288. hash = (hash * 397) ^ (this.y || 0);
  2289. hash = (hash * 397) ^ (this.z || 0);
  2290. hash = (hash * 397) ^ (this.w || 0);
  2291. return hash;
  2292. };
  2293. /**
  2294. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2295. */
  2296. Quaternion.prototype.asArray = function () {
  2297. return [this.x, this.y, this.z, this.w];
  2298. };
  2299. /**
  2300. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2301. */
  2302. Quaternion.prototype.equals = function (otherQuaternion) {
  2303. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2304. };
  2305. /**
  2306. * Returns a new Quaternion copied from the current one.
  2307. */
  2308. Quaternion.prototype.clone = function () {
  2309. return new Quaternion(this.x, this.y, this.z, this.w);
  2310. };
  2311. /**
  2312. * Updates the current Quaternion from the passed one coordinates.
  2313. * Returns the updated Quaterion.
  2314. */
  2315. Quaternion.prototype.copyFrom = function (other) {
  2316. this.x = other.x;
  2317. this.y = other.y;
  2318. this.z = other.z;
  2319. this.w = other.w;
  2320. return this;
  2321. };
  2322. /**
  2323. * Updates the current Quaternion from the passed float coordinates.
  2324. * Returns the updated Quaterion.
  2325. */
  2326. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2327. this.x = x;
  2328. this.y = y;
  2329. this.z = z;
  2330. this.w = w;
  2331. return this;
  2332. };
  2333. /**
  2334. * Updates the current Quaternion from the passed float coordinates.
  2335. * Returns the updated Quaterion.
  2336. */
  2337. Quaternion.prototype.set = function (x, y, z, w) {
  2338. return this.copyFromFloats(x, y, z, w);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2342. */
  2343. Quaternion.prototype.add = function (other) {
  2344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2345. };
  2346. /**
  2347. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2348. */
  2349. Quaternion.prototype.subtract = function (other) {
  2350. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2351. };
  2352. /**
  2353. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2354. */
  2355. Quaternion.prototype.scale = function (value) {
  2356. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2357. };
  2358. /**
  2359. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2360. */
  2361. Quaternion.prototype.multiply = function (q1) {
  2362. var result = new Quaternion(0, 0, 0, 1.0);
  2363. this.multiplyToRef(q1, result);
  2364. return result;
  2365. };
  2366. /**
  2367. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2368. * Returns the current Quaternion.
  2369. */
  2370. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2371. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2372. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2373. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2374. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2375. result.copyFromFloats(x, y, z, w);
  2376. return this;
  2377. };
  2378. /**
  2379. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2380. * Returns the updated Quaternion.
  2381. */
  2382. Quaternion.prototype.multiplyInPlace = function (q1) {
  2383. this.multiplyToRef(q1, this);
  2384. return this;
  2385. };
  2386. /**
  2387. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2388. * Returns the current Quaternion.
  2389. */
  2390. Quaternion.prototype.conjugateToRef = function (ref) {
  2391. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2392. return this;
  2393. };
  2394. /**
  2395. * Conjugates in place the current Quaternion.
  2396. * Returns the updated Quaternion.
  2397. */
  2398. Quaternion.prototype.conjugateInPlace = function () {
  2399. this.x *= -1;
  2400. this.y *= -1;
  2401. this.z *= -1;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2406. */
  2407. Quaternion.prototype.conjugate = function () {
  2408. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2409. return result;
  2410. };
  2411. /**
  2412. * Returns the Quaternion length (float).
  2413. */
  2414. Quaternion.prototype.length = function () {
  2415. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2416. };
  2417. /**
  2418. * Normalize in place the current Quaternion.
  2419. * Returns the updated Quaternion.
  2420. */
  2421. Quaternion.prototype.normalize = function () {
  2422. var length = 1.0 / this.length();
  2423. this.x *= length;
  2424. this.y *= length;
  2425. this.z *= length;
  2426. this.w *= length;
  2427. return this;
  2428. };
  2429. /**
  2430. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2431. */
  2432. Quaternion.prototype.toEulerAngles = function (order) {
  2433. if (order === void 0) { order = "YZX"; }
  2434. var result = Vector3.Zero();
  2435. this.toEulerAnglesToRef(result, order);
  2436. return result;
  2437. };
  2438. /**
  2439. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2440. * Returns the current Quaternion.
  2441. */
  2442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2443. if (order === void 0) { order = "YZX"; }
  2444. var qz = this.z;
  2445. var qx = this.x;
  2446. var qy = this.y;
  2447. var qw = this.w;
  2448. var sqw = qw * qw;
  2449. var sqz = qz * qz;
  2450. var sqx = qx * qx;
  2451. var sqy = qy * qy;
  2452. var zAxisY = qy * qz - qx * qw;
  2453. var limit = .4999999;
  2454. if (zAxisY < -limit) {
  2455. result.y = 2 * Math.atan2(qy, qw);
  2456. result.x = Math.PI / 2;
  2457. result.z = 0;
  2458. }
  2459. else if (zAxisY > limit) {
  2460. result.y = 2 * Math.atan2(qy, qw);
  2461. result.x = -Math.PI / 2;
  2462. result.z = 0;
  2463. }
  2464. else {
  2465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2468. }
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the passed rotation matrix with the current Quaternion values.
  2473. * Returns the current Quaternion.
  2474. */
  2475. Quaternion.prototype.toRotationMatrix = function (result) {
  2476. var xx = this.x * this.x;
  2477. var yy = this.y * this.y;
  2478. var zz = this.z * this.z;
  2479. var xy = this.x * this.y;
  2480. var zw = this.z * this.w;
  2481. var zx = this.z * this.x;
  2482. var yw = this.y * this.w;
  2483. var yz = this.y * this.z;
  2484. var xw = this.x * this.w;
  2485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2486. result.m[1] = 2.0 * (xy + zw);
  2487. result.m[2] = 2.0 * (zx - yw);
  2488. result.m[3] = 0;
  2489. result.m[4] = 2.0 * (xy - zw);
  2490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2491. result.m[6] = 2.0 * (yz + xw);
  2492. result.m[7] = 0;
  2493. result.m[8] = 2.0 * (zx + yw);
  2494. result.m[9] = 2.0 * (yz - xw);
  2495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2496. result.m[11] = 0;
  2497. result.m[12] = 0;
  2498. result.m[13] = 0;
  2499. result.m[14] = 0;
  2500. result.m[15] = 1.0;
  2501. result._markAsUpdated();
  2502. return this;
  2503. };
  2504. /**
  2505. * Updates the current Quaternion from the passed rotation matrix values.
  2506. * Returns the updated Quaternion.
  2507. */
  2508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2509. Quaternion.FromRotationMatrixToRef(matrix, this);
  2510. return this;
  2511. };
  2512. // Statics
  2513. /**
  2514. * Returns a new Quaternion set from the passed rotation matrix values.
  2515. */
  2516. Quaternion.FromRotationMatrix = function (matrix) {
  2517. var result = new Quaternion();
  2518. Quaternion.FromRotationMatrixToRef(matrix, result);
  2519. return result;
  2520. };
  2521. /**
  2522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2523. */
  2524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2525. var data = matrix.m;
  2526. var m11 = data[0], m12 = data[4], m13 = data[8];
  2527. var m21 = data[1], m22 = data[5], m23 = data[9];
  2528. var m31 = data[2], m32 = data[6], m33 = data[10];
  2529. var trace = m11 + m22 + m33;
  2530. var s;
  2531. if (trace > 0) {
  2532. s = 0.5 / Math.sqrt(trace + 1.0);
  2533. result.w = 0.25 / s;
  2534. result.x = (m32 - m23) * s;
  2535. result.y = (m13 - m31) * s;
  2536. result.z = (m21 - m12) * s;
  2537. }
  2538. else if (m11 > m22 && m11 > m33) {
  2539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2540. result.w = (m32 - m23) / s;
  2541. result.x = 0.25 * s;
  2542. result.y = (m12 + m21) / s;
  2543. result.z = (m13 + m31) / s;
  2544. }
  2545. else if (m22 > m33) {
  2546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2547. result.w = (m13 - m31) / s;
  2548. result.x = (m12 + m21) / s;
  2549. result.y = 0.25 * s;
  2550. result.z = (m23 + m32) / s;
  2551. }
  2552. else {
  2553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2554. result.w = (m21 - m12) / s;
  2555. result.x = (m13 + m31) / s;
  2556. result.y = (m23 + m32) / s;
  2557. result.z = 0.25 * s;
  2558. }
  2559. };
  2560. /**
  2561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2562. */
  2563. Quaternion.Zero = function () {
  2564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion as the inverted current Quaternion.
  2568. */
  2569. Quaternion.Inverse = function (q) {
  2570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2571. };
  2572. /**
  2573. * Returns the identity Quaternion.
  2574. */
  2575. Quaternion.Identity = function () {
  2576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2577. };
  2578. Quaternion.IsIdentity = function (quaternion) {
  2579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2580. };
  2581. /**
  2582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2583. */
  2584. Quaternion.RotationAxis = function (axis, angle) {
  2585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2586. };
  2587. /**
  2588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2589. */
  2590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2591. var sin = Math.sin(angle / 2);
  2592. axis.normalize();
  2593. result.w = Math.cos(angle / 2);
  2594. result.x = axis.x * sin;
  2595. result.y = axis.y * sin;
  2596. result.z = axis.z * sin;
  2597. return result;
  2598. };
  2599. /**
  2600. * Retuns a new Quaternion set from the starting index of the passed array.
  2601. */
  2602. Quaternion.FromArray = function (array, offset) {
  2603. if (!offset) {
  2604. offset = 0;
  2605. }
  2606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2607. };
  2608. /**
  2609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2610. */
  2611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2612. var q = new Quaternion();
  2613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2614. return q;
  2615. };
  2616. /**
  2617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2618. */
  2619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2621. var halfRoll = roll * 0.5;
  2622. var halfPitch = pitch * 0.5;
  2623. var halfYaw = yaw * 0.5;
  2624. var sinRoll = Math.sin(halfRoll);
  2625. var cosRoll = Math.cos(halfRoll);
  2626. var sinPitch = Math.sin(halfPitch);
  2627. var cosPitch = Math.cos(halfPitch);
  2628. var sinYaw = Math.sin(halfYaw);
  2629. var cosYaw = Math.cos(halfYaw);
  2630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2634. };
  2635. /**
  2636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2637. */
  2638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2639. var result = new Quaternion();
  2640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2641. return result;
  2642. };
  2643. /**
  2644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2645. */
  2646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2647. // Produces a quaternion from Euler angles in the z-x-z orientation
  2648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2650. var halfBeta = beta * 0.5;
  2651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2655. };
  2656. /**
  2657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2658. * cf to Vector3.RotationFromAxis() documentation.
  2659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2660. */
  2661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2664. return quat;
  2665. };
  2666. /**
  2667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2668. * cf to Vector3.RotationFromAxis() documentation.
  2669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2670. */
  2671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2672. var rotMat = MathTmp.Matrix[0];
  2673. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2674. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2675. };
  2676. Quaternion.Slerp = function (left, right, amount) {
  2677. var result = Quaternion.Identity();
  2678. Quaternion.SlerpToRef(left, right, amount, result);
  2679. return result;
  2680. };
  2681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2682. var num2;
  2683. var num3;
  2684. var num = amount;
  2685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2686. var flag = false;
  2687. if (num4 < 0) {
  2688. flag = true;
  2689. num4 = -num4;
  2690. }
  2691. if (num4 > 0.999999) {
  2692. num3 = 1 - num;
  2693. num2 = flag ? -num : num;
  2694. }
  2695. else {
  2696. var num5 = Math.acos(num4);
  2697. var num6 = (1.0 / Math.sin(num5));
  2698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2700. }
  2701. result.x = (num3 * left.x) + (num2 * right.x);
  2702. result.y = (num3 * left.y) + (num2 * right.y);
  2703. result.z = (num3 * left.z) + (num2 * right.z);
  2704. result.w = (num3 * left.w) + (num2 * right.w);
  2705. };
  2706. /**
  2707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2708. */
  2709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2710. var squared = amount * amount;
  2711. var cubed = amount * squared;
  2712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2714. var part3 = (cubed - (2.0 * squared)) + amount;
  2715. var part4 = cubed - squared;
  2716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2720. return new Quaternion(x, y, z, w);
  2721. };
  2722. return Quaternion;
  2723. }());
  2724. BABYLON.Quaternion = Quaternion;
  2725. var Matrix = (function () {
  2726. function Matrix() {
  2727. this.m = new Float32Array(16);
  2728. this._markAsUpdated();
  2729. }
  2730. Matrix.prototype._markAsUpdated = function () {
  2731. this.updateFlag = Matrix._updateFlagSeed++;
  2732. };
  2733. // Properties
  2734. /**
  2735. * Boolean : True is the matrix is the identity matrix
  2736. */
  2737. Matrix.prototype.isIdentity = function () {
  2738. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2739. return false;
  2740. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2741. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2742. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2743. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2744. return false;
  2745. return true;
  2746. };
  2747. /**
  2748. * Returns the matrix determinant (float).
  2749. */
  2750. Matrix.prototype.determinant = function () {
  2751. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2752. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2753. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2754. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2755. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2756. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2757. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2758. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2759. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2760. };
  2761. // Methods
  2762. /**
  2763. * Returns the matrix underlying array.
  2764. */
  2765. Matrix.prototype.toArray = function () {
  2766. return this.m;
  2767. };
  2768. /**
  2769. * Returns the matrix underlying array.
  2770. */
  2771. Matrix.prototype.asArray = function () {
  2772. return this.toArray();
  2773. };
  2774. /**
  2775. * Inverts in place the Matrix.
  2776. * Returns the Matrix inverted.
  2777. */
  2778. Matrix.prototype.invert = function () {
  2779. this.invertToRef(this);
  2780. return this;
  2781. };
  2782. /**
  2783. * Sets all the matrix elements to zero.
  2784. * Returns the Matrix.
  2785. */
  2786. Matrix.prototype.reset = function () {
  2787. for (var index = 0; index < 16; index++) {
  2788. this.m[index] = 0.0;
  2789. }
  2790. this._markAsUpdated();
  2791. return this;
  2792. };
  2793. /**
  2794. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2795. */
  2796. Matrix.prototype.add = function (other) {
  2797. var result = new Matrix();
  2798. this.addToRef(other, result);
  2799. return result;
  2800. };
  2801. /**
  2802. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2803. * Returns the Matrix.
  2804. */
  2805. Matrix.prototype.addToRef = function (other, result) {
  2806. for (var index = 0; index < 16; index++) {
  2807. result.m[index] = this.m[index] + other.m[index];
  2808. }
  2809. result._markAsUpdated();
  2810. return this;
  2811. };
  2812. /**
  2813. * Adds in place the passed matrix to the current Matrix.
  2814. * Returns the updated Matrix.
  2815. */
  2816. Matrix.prototype.addToSelf = function (other) {
  2817. for (var index = 0; index < 16; index++) {
  2818. this.m[index] += other.m[index];
  2819. }
  2820. this._markAsUpdated();
  2821. return this;
  2822. };
  2823. /**
  2824. * Sets the passed matrix with the current inverted Matrix.
  2825. * Returns the unmodified current Matrix.
  2826. */
  2827. Matrix.prototype.invertToRef = function (other) {
  2828. var l1 = this.m[0];
  2829. var l2 = this.m[1];
  2830. var l3 = this.m[2];
  2831. var l4 = this.m[3];
  2832. var l5 = this.m[4];
  2833. var l6 = this.m[5];
  2834. var l7 = this.m[6];
  2835. var l8 = this.m[7];
  2836. var l9 = this.m[8];
  2837. var l10 = this.m[9];
  2838. var l11 = this.m[10];
  2839. var l12 = this.m[11];
  2840. var l13 = this.m[12];
  2841. var l14 = this.m[13];
  2842. var l15 = this.m[14];
  2843. var l16 = this.m[15];
  2844. var l17 = (l11 * l16) - (l12 * l15);
  2845. var l18 = (l10 * l16) - (l12 * l14);
  2846. var l19 = (l10 * l15) - (l11 * l14);
  2847. var l20 = (l9 * l16) - (l12 * l13);
  2848. var l21 = (l9 * l15) - (l11 * l13);
  2849. var l22 = (l9 * l14) - (l10 * l13);
  2850. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2851. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2852. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2853. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2854. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2855. var l28 = (l7 * l16) - (l8 * l15);
  2856. var l29 = (l6 * l16) - (l8 * l14);
  2857. var l30 = (l6 * l15) - (l7 * l14);
  2858. var l31 = (l5 * l16) - (l8 * l13);
  2859. var l32 = (l5 * l15) - (l7 * l13);
  2860. var l33 = (l5 * l14) - (l6 * l13);
  2861. var l34 = (l7 * l12) - (l8 * l11);
  2862. var l35 = (l6 * l12) - (l8 * l10);
  2863. var l36 = (l6 * l11) - (l7 * l10);
  2864. var l37 = (l5 * l12) - (l8 * l9);
  2865. var l38 = (l5 * l11) - (l7 * l9);
  2866. var l39 = (l5 * l10) - (l6 * l9);
  2867. other.m[0] = l23 * l27;
  2868. other.m[4] = l24 * l27;
  2869. other.m[8] = l25 * l27;
  2870. other.m[12] = l26 * l27;
  2871. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2872. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2873. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2874. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2875. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2876. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2877. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2878. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2879. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2880. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2881. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2882. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2883. other._markAsUpdated();
  2884. return this;
  2885. };
  2886. /**
  2887. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2888. * Returns the updated Matrix.
  2889. */
  2890. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2891. this.m[12] = x;
  2892. this.m[13] = y;
  2893. this.m[14] = z;
  2894. this._markAsUpdated();
  2895. return this;
  2896. };
  2897. /**
  2898. * Inserts the translation vector in the current Matrix.
  2899. * Returns the updated Matrix.
  2900. */
  2901. Matrix.prototype.setTranslation = function (vector3) {
  2902. this.m[12] = vector3.x;
  2903. this.m[13] = vector3.y;
  2904. this.m[14] = vector3.z;
  2905. this._markAsUpdated();
  2906. return this;
  2907. };
  2908. /**
  2909. * Returns a new Vector3 as the extracted translation from the Matrix.
  2910. */
  2911. Matrix.prototype.getTranslation = function () {
  2912. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2913. };
  2914. /**
  2915. * Fill a Vector3 with the extracted translation from the Matrix.
  2916. */
  2917. Matrix.prototype.getTranslationToRef = function (result) {
  2918. result.x = this.m[12];
  2919. result.y = this.m[13];
  2920. result.z = this.m[14];
  2921. return this;
  2922. };
  2923. /**
  2924. * Remove rotation and scaling part from the Matrix.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.removeRotationAndScaling = function () {
  2928. this.setRowFromFloats(0, 1, 0, 0, 0);
  2929. this.setRowFromFloats(1, 0, 1, 0, 0);
  2930. this.setRowFromFloats(2, 0, 0, 1, 0);
  2931. return this;
  2932. };
  2933. /**
  2934. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2935. */
  2936. Matrix.prototype.multiply = function (other) {
  2937. var result = new Matrix();
  2938. this.multiplyToRef(other, result);
  2939. return result;
  2940. };
  2941. /**
  2942. * Updates the current Matrix from the passed one values.
  2943. * Returns the updated Matrix.
  2944. */
  2945. Matrix.prototype.copyFrom = function (other) {
  2946. for (var index = 0; index < 16; index++) {
  2947. this.m[index] = other.m[index];
  2948. }
  2949. this._markAsUpdated();
  2950. return this;
  2951. };
  2952. /**
  2953. * Populates the passed array from the starting index with the Matrix values.
  2954. * Returns the Matrix.
  2955. */
  2956. Matrix.prototype.copyToArray = function (array, offset) {
  2957. if (offset === void 0) { offset = 0; }
  2958. for (var index = 0; index < 16; index++) {
  2959. array[offset + index] = this.m[index];
  2960. }
  2961. return this;
  2962. };
  2963. /**
  2964. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2965. */
  2966. Matrix.prototype.multiplyToRef = function (other, result) {
  2967. this.multiplyToArray(other, result.m, 0);
  2968. result._markAsUpdated();
  2969. return this;
  2970. };
  2971. /**
  2972. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2973. */
  2974. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2975. var tm0 = this.m[0];
  2976. var tm1 = this.m[1];
  2977. var tm2 = this.m[2];
  2978. var tm3 = this.m[3];
  2979. var tm4 = this.m[4];
  2980. var tm5 = this.m[5];
  2981. var tm6 = this.m[6];
  2982. var tm7 = this.m[7];
  2983. var tm8 = this.m[8];
  2984. var tm9 = this.m[9];
  2985. var tm10 = this.m[10];
  2986. var tm11 = this.m[11];
  2987. var tm12 = this.m[12];
  2988. var tm13 = this.m[13];
  2989. var tm14 = this.m[14];
  2990. var tm15 = this.m[15];
  2991. var om0 = other.m[0];
  2992. var om1 = other.m[1];
  2993. var om2 = other.m[2];
  2994. var om3 = other.m[3];
  2995. var om4 = other.m[4];
  2996. var om5 = other.m[5];
  2997. var om6 = other.m[6];
  2998. var om7 = other.m[7];
  2999. var om8 = other.m[8];
  3000. var om9 = other.m[9];
  3001. var om10 = other.m[10];
  3002. var om11 = other.m[11];
  3003. var om12 = other.m[12];
  3004. var om13 = other.m[13];
  3005. var om14 = other.m[14];
  3006. var om15 = other.m[15];
  3007. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3008. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3009. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3010. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3011. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3012. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3013. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3014. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3015. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3016. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3017. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3018. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3019. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3020. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3021. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3022. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3023. return this;
  3024. };
  3025. /**
  3026. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3027. */
  3028. Matrix.prototype.equals = function (value) {
  3029. return value &&
  3030. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3031. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3032. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3033. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3034. };
  3035. /**
  3036. * Returns a new Matrix from the current Matrix.
  3037. */
  3038. Matrix.prototype.clone = function () {
  3039. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3040. };
  3041. /**
  3042. * Returns the string "Matrix"
  3043. */
  3044. Matrix.prototype.getClassName = function () {
  3045. return "Matrix";
  3046. };
  3047. /**
  3048. * Returns the Matrix hash code.
  3049. */
  3050. Matrix.prototype.getHashCode = function () {
  3051. var hash = this.m[0] || 0;
  3052. for (var i = 1; i < 16; i++) {
  3053. hash = (hash * 397) ^ (this.m[i] || 0);
  3054. }
  3055. return hash;
  3056. };
  3057. /**
  3058. * Decomposes the current Matrix into :
  3059. * - a scale vector3 passed as a reference to update,
  3060. * - a rotation quaternion passed as a reference to update,
  3061. * - a translation vector3 passed as a reference to update.
  3062. * Returns the boolean `true`.
  3063. */
  3064. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3065. translation.x = this.m[12];
  3066. translation.y = this.m[13];
  3067. translation.z = this.m[14];
  3068. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3069. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3070. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3071. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3072. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3073. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3074. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3075. rotation.x = 0;
  3076. rotation.y = 0;
  3077. rotation.z = 0;
  3078. rotation.w = 1;
  3079. return false;
  3080. }
  3081. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3082. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3083. return true;
  3084. };
  3085. /**
  3086. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3087. */
  3088. Matrix.prototype.getRotationMatrix = function () {
  3089. var result = Matrix.Identity();
  3090. this.getRotationMatrixToRef(result);
  3091. return result;
  3092. };
  3093. /**
  3094. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3095. * Returns the current Matrix.
  3096. */
  3097. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3098. var m = this.m;
  3099. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3100. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3101. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3102. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3103. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3104. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3105. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3106. return this;
  3107. };
  3108. // Statics
  3109. /**
  3110. * Returns a new Matrix set from the starting index of the passed array.
  3111. */
  3112. Matrix.FromArray = function (array, offset) {
  3113. var result = new Matrix();
  3114. if (!offset) {
  3115. offset = 0;
  3116. }
  3117. Matrix.FromArrayToRef(array, offset, result);
  3118. return result;
  3119. };
  3120. /**
  3121. * Sets the passed "result" matrix from the starting index of the passed array.
  3122. */
  3123. Matrix.FromArrayToRef = function (array, offset, result) {
  3124. for (var index = 0; index < 16; index++) {
  3125. result.m[index] = array[index + offset];
  3126. }
  3127. result._markAsUpdated();
  3128. };
  3129. /**
  3130. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3131. */
  3132. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3133. for (var index = 0; index < 16; index++) {
  3134. result.m[index] = array[index + offset] * scale;
  3135. }
  3136. result._markAsUpdated();
  3137. };
  3138. /**
  3139. * Sets the passed matrix "result" with the 16 passed floats.
  3140. */
  3141. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3142. result.m[0] = initialM11;
  3143. result.m[1] = initialM12;
  3144. result.m[2] = initialM13;
  3145. result.m[3] = initialM14;
  3146. result.m[4] = initialM21;
  3147. result.m[5] = initialM22;
  3148. result.m[6] = initialM23;
  3149. result.m[7] = initialM24;
  3150. result.m[8] = initialM31;
  3151. result.m[9] = initialM32;
  3152. result.m[10] = initialM33;
  3153. result.m[11] = initialM34;
  3154. result.m[12] = initialM41;
  3155. result.m[13] = initialM42;
  3156. result.m[14] = initialM43;
  3157. result.m[15] = initialM44;
  3158. result._markAsUpdated();
  3159. };
  3160. /**
  3161. * Returns the index-th row of the current matrix as a new Vector4.
  3162. */
  3163. Matrix.prototype.getRow = function (index) {
  3164. if (index < 0 || index > 3) {
  3165. return null;
  3166. }
  3167. var i = index * 4;
  3168. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3169. };
  3170. /**
  3171. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3172. * Returns the updated Matrix.
  3173. */
  3174. Matrix.prototype.setRow = function (index, row) {
  3175. if (index < 0 || index > 3) {
  3176. return this;
  3177. }
  3178. var i = index * 4;
  3179. this.m[i + 0] = row.x;
  3180. this.m[i + 1] = row.y;
  3181. this.m[i + 2] = row.z;
  3182. this.m[i + 3] = row.w;
  3183. this._markAsUpdated();
  3184. return this;
  3185. };
  3186. /**
  3187. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3188. * Returns the updated Matrix.
  3189. */
  3190. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3191. if (index < 0 || index > 3) {
  3192. return this;
  3193. }
  3194. var i = index * 4;
  3195. this.m[i + 0] = x;
  3196. this.m[i + 1] = y;
  3197. this.m[i + 2] = z;
  3198. this.m[i + 3] = w;
  3199. this._markAsUpdated();
  3200. return this;
  3201. };
  3202. /**
  3203. * Returns a new Matrix set from the 16 passed floats.
  3204. */
  3205. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3206. var result = new Matrix();
  3207. result.m[0] = initialM11;
  3208. result.m[1] = initialM12;
  3209. result.m[2] = initialM13;
  3210. result.m[3] = initialM14;
  3211. result.m[4] = initialM21;
  3212. result.m[5] = initialM22;
  3213. result.m[6] = initialM23;
  3214. result.m[7] = initialM24;
  3215. result.m[8] = initialM31;
  3216. result.m[9] = initialM32;
  3217. result.m[10] = initialM33;
  3218. result.m[11] = initialM34;
  3219. result.m[12] = initialM41;
  3220. result.m[13] = initialM42;
  3221. result.m[14] = initialM43;
  3222. result.m[15] = initialM44;
  3223. return result;
  3224. };
  3225. /**
  3226. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3227. */
  3228. Matrix.Compose = function (scale, rotation, translation) {
  3229. var result = Matrix.Identity();
  3230. Matrix.ComposeToRef(scale, rotation, translation, result);
  3231. return result;
  3232. };
  3233. /**
  3234. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3235. */
  3236. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3237. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3238. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3239. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3240. result.setTranslation(translation);
  3241. };
  3242. /**
  3243. * Returns a new indentity Matrix.
  3244. */
  3245. Matrix.Identity = function () {
  3246. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3247. };
  3248. /**
  3249. * Sets the passed "result" as an identity matrix.
  3250. */
  3251. Matrix.IdentityToRef = function (result) {
  3252. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3253. };
  3254. /**
  3255. * Returns a new zero Matrix.
  3256. */
  3257. Matrix.Zero = function () {
  3258. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3259. };
  3260. /**
  3261. * Returns a new rotation matrix for "angle" radians around the X axis.
  3262. */
  3263. Matrix.RotationX = function (angle) {
  3264. var result = new Matrix();
  3265. Matrix.RotationXToRef(angle, result);
  3266. return result;
  3267. };
  3268. /**
  3269. * Returns a new Matrix as the passed inverted one.
  3270. */
  3271. Matrix.Invert = function (source) {
  3272. var result = new Matrix();
  3273. source.invertToRef(result);
  3274. return result;
  3275. };
  3276. /**
  3277. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3278. */
  3279. Matrix.RotationXToRef = function (angle, result) {
  3280. var s = Math.sin(angle);
  3281. var c = Math.cos(angle);
  3282. result.m[0] = 1.0;
  3283. result.m[15] = 1.0;
  3284. result.m[5] = c;
  3285. result.m[10] = c;
  3286. result.m[9] = -s;
  3287. result.m[6] = s;
  3288. result.m[1] = 0.0;
  3289. result.m[2] = 0.0;
  3290. result.m[3] = 0.0;
  3291. result.m[4] = 0.0;
  3292. result.m[7] = 0.0;
  3293. result.m[8] = 0.0;
  3294. result.m[11] = 0.0;
  3295. result.m[12] = 0.0;
  3296. result.m[13] = 0.0;
  3297. result.m[14] = 0.0;
  3298. result._markAsUpdated();
  3299. };
  3300. /**
  3301. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3302. */
  3303. Matrix.RotationY = function (angle) {
  3304. var result = new Matrix();
  3305. Matrix.RotationYToRef(angle, result);
  3306. return result;
  3307. };
  3308. /**
  3309. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3310. */
  3311. Matrix.RotationYToRef = function (angle, result) {
  3312. var s = Math.sin(angle);
  3313. var c = Math.cos(angle);
  3314. result.m[5] = 1.0;
  3315. result.m[15] = 1.0;
  3316. result.m[0] = c;
  3317. result.m[2] = -s;
  3318. result.m[8] = s;
  3319. result.m[10] = c;
  3320. result.m[1] = 0.0;
  3321. result.m[3] = 0.0;
  3322. result.m[4] = 0.0;
  3323. result.m[6] = 0.0;
  3324. result.m[7] = 0.0;
  3325. result.m[9] = 0.0;
  3326. result.m[11] = 0.0;
  3327. result.m[12] = 0.0;
  3328. result.m[13] = 0.0;
  3329. result.m[14] = 0.0;
  3330. result._markAsUpdated();
  3331. };
  3332. /**
  3333. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3334. */
  3335. Matrix.RotationZ = function (angle) {
  3336. var result = new Matrix();
  3337. Matrix.RotationZToRef(angle, result);
  3338. return result;
  3339. };
  3340. /**
  3341. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3342. */
  3343. Matrix.RotationZToRef = function (angle, result) {
  3344. var s = Math.sin(angle);
  3345. var c = Math.cos(angle);
  3346. result.m[10] = 1.0;
  3347. result.m[15] = 1.0;
  3348. result.m[0] = c;
  3349. result.m[1] = s;
  3350. result.m[4] = -s;
  3351. result.m[5] = c;
  3352. result.m[2] = 0.0;
  3353. result.m[3] = 0.0;
  3354. result.m[6] = 0.0;
  3355. result.m[7] = 0.0;
  3356. result.m[8] = 0.0;
  3357. result.m[9] = 0.0;
  3358. result.m[11] = 0.0;
  3359. result.m[12] = 0.0;
  3360. result.m[13] = 0.0;
  3361. result.m[14] = 0.0;
  3362. result._markAsUpdated();
  3363. };
  3364. /**
  3365. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3366. */
  3367. Matrix.RotationAxis = function (axis, angle) {
  3368. var result = Matrix.Zero();
  3369. Matrix.RotationAxisToRef(axis, angle, result);
  3370. return result;
  3371. };
  3372. /**
  3373. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3374. */
  3375. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3376. var s = Math.sin(-angle);
  3377. var c = Math.cos(-angle);
  3378. var c1 = 1 - c;
  3379. axis.normalize();
  3380. result.m[0] = (axis.x * axis.x) * c1 + c;
  3381. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3382. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3383. result.m[3] = 0.0;
  3384. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3385. result.m[5] = (axis.y * axis.y) * c1 + c;
  3386. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3387. result.m[7] = 0.0;
  3388. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3389. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3390. result.m[10] = (axis.z * axis.z) * c1 + c;
  3391. result.m[11] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3397. */
  3398. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3399. var result = new Matrix();
  3400. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3405. */
  3406. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3407. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3408. this._tempQuaternion.toRotationMatrix(result);
  3409. };
  3410. /**
  3411. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3412. */
  3413. Matrix.Scaling = function (x, y, z) {
  3414. var result = Matrix.Zero();
  3415. Matrix.ScalingToRef(x, y, z, result);
  3416. return result;
  3417. };
  3418. /**
  3419. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3420. */
  3421. Matrix.ScalingToRef = function (x, y, z, result) {
  3422. result.m[0] = x;
  3423. result.m[1] = 0.0;
  3424. result.m[2] = 0.0;
  3425. result.m[3] = 0.0;
  3426. result.m[4] = 0.0;
  3427. result.m[5] = y;
  3428. result.m[6] = 0.0;
  3429. result.m[7] = 0.0;
  3430. result.m[8] = 0.0;
  3431. result.m[9] = 0.0;
  3432. result.m[10] = z;
  3433. result.m[11] = 0.0;
  3434. result.m[12] = 0.0;
  3435. result.m[13] = 0.0;
  3436. result.m[14] = 0.0;
  3437. result.m[15] = 1.0;
  3438. result._markAsUpdated();
  3439. };
  3440. /**
  3441. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3442. */
  3443. Matrix.Translation = function (x, y, z) {
  3444. var result = Matrix.Identity();
  3445. Matrix.TranslationToRef(x, y, z, result);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3450. */
  3451. Matrix.TranslationToRef = function (x, y, z, result) {
  3452. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3453. };
  3454. /**
  3455. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3456. */
  3457. Matrix.Lerp = function (startValue, endValue, gradient) {
  3458. var result = Matrix.Zero();
  3459. for (var index = 0; index < 16; index++) {
  3460. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3461. }
  3462. result._markAsUpdated();
  3463. return result;
  3464. };
  3465. /**
  3466. * Returns a new Matrix whose values are computed by :
  3467. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3468. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3469. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3470. */
  3471. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3472. var startScale = new Vector3(0, 0, 0);
  3473. var startRotation = new Quaternion();
  3474. var startTranslation = new Vector3(0, 0, 0);
  3475. startValue.decompose(startScale, startRotation, startTranslation);
  3476. var endScale = new Vector3(0, 0, 0);
  3477. var endRotation = new Quaternion();
  3478. var endTranslation = new Vector3(0, 0, 0);
  3479. endValue.decompose(endScale, endRotation, endTranslation);
  3480. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3481. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3482. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3483. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3484. };
  3485. /**
  3486. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3487. * This methods works for a Left-Handed system.
  3488. */
  3489. Matrix.LookAtLH = function (eye, target, up) {
  3490. var result = Matrix.Zero();
  3491. Matrix.LookAtLHToRef(eye, target, up, result);
  3492. return result;
  3493. };
  3494. /**
  3495. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3496. * This methods works for a Left-Handed system.
  3497. */
  3498. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3499. // Z axis
  3500. target.subtractToRef(eye, this._zAxis);
  3501. this._zAxis.normalize();
  3502. // X axis
  3503. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3504. if (this._xAxis.lengthSquared() === 0) {
  3505. this._xAxis.x = 1.0;
  3506. }
  3507. else {
  3508. this._xAxis.normalize();
  3509. }
  3510. // Y axis
  3511. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3512. this._yAxis.normalize();
  3513. // Eye angles
  3514. var ex = -Vector3.Dot(this._xAxis, eye);
  3515. var ey = -Vector3.Dot(this._yAxis, eye);
  3516. var ez = -Vector3.Dot(this._zAxis, eye);
  3517. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3518. };
  3519. /**
  3520. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3521. * This methods works for a Right-Handed system.
  3522. */
  3523. Matrix.LookAtRH = function (eye, target, up) {
  3524. var result = Matrix.Zero();
  3525. Matrix.LookAtRHToRef(eye, target, up, result);
  3526. return result;
  3527. };
  3528. /**
  3529. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3530. * This methods works for a Left-Handed system.
  3531. */
  3532. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3533. // Z axis
  3534. eye.subtractToRef(target, this._zAxis);
  3535. this._zAxis.normalize();
  3536. // X axis
  3537. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3538. if (this._xAxis.lengthSquared() === 0) {
  3539. this._xAxis.x = 1.0;
  3540. }
  3541. else {
  3542. this._xAxis.normalize();
  3543. }
  3544. // Y axis
  3545. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3546. this._yAxis.normalize();
  3547. // Eye angles
  3548. var ex = -Vector3.Dot(this._xAxis, eye);
  3549. var ey = -Vector3.Dot(this._yAxis, eye);
  3550. var ez = -Vector3.Dot(this._zAxis, eye);
  3551. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3552. };
  3553. /**
  3554. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3555. */
  3556. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3557. var matrix = Matrix.Zero();
  3558. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3559. return matrix;
  3560. };
  3561. /**
  3562. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3563. */
  3564. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3565. var n = znear;
  3566. var f = zfar;
  3567. var a = 2.0 / width;
  3568. var b = 2.0 / height;
  3569. var c = 2.0 / (f - n);
  3570. var d = -(f + n) / (f - n);
  3571. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3572. };
  3573. /**
  3574. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3575. */
  3576. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3577. var matrix = Matrix.Zero();
  3578. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3579. return matrix;
  3580. };
  3581. /**
  3582. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3583. */
  3584. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3585. var n = znear;
  3586. var f = zfar;
  3587. var a = 2.0 / (right - left);
  3588. var b = 2.0 / (top - bottom);
  3589. var c = 2.0 / (f - n);
  3590. var d = -(f + n) / (f - n);
  3591. var i0 = (left + right) / (left - right);
  3592. var i1 = (top + bottom) / (bottom - top);
  3593. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3594. };
  3595. /**
  3596. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3597. */
  3598. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3599. var matrix = Matrix.Zero();
  3600. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3601. return matrix;
  3602. };
  3603. /**
  3604. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3605. */
  3606. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3607. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3608. result.m[10] *= -1.0;
  3609. };
  3610. /**
  3611. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3612. */
  3613. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3614. var matrix = Matrix.Zero();
  3615. var n = znear;
  3616. var f = zfar;
  3617. var a = 2.0 * n / width;
  3618. var b = 2.0 * n / height;
  3619. var c = (f + n) / (f - n);
  3620. var d = -2.0 * f * n / (f - n);
  3621. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3622. return matrix;
  3623. };
  3624. /**
  3625. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3626. */
  3627. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3628. var matrix = Matrix.Zero();
  3629. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3630. return matrix;
  3631. };
  3632. /**
  3633. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3634. */
  3635. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3636. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3637. var n = znear;
  3638. var f = zfar;
  3639. var t = 1.0 / (Math.tan(fov * 0.5));
  3640. var a = isVerticalFovFixed ? (t / aspect) : t;
  3641. var b = isVerticalFovFixed ? t : (t * aspect);
  3642. var c = (f + n) / (f - n);
  3643. var d = -2.0 * f * n / (f - n);
  3644. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3645. };
  3646. /**
  3647. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3648. */
  3649. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3650. var matrix = Matrix.Zero();
  3651. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3652. return matrix;
  3653. };
  3654. /**
  3655. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3656. */
  3657. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3658. //alternatively this could be expressed as:
  3659. // m = PerspectiveFovLHToRef
  3660. // m[10] *= -1.0;
  3661. // m[11] *= -1.0;
  3662. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3663. var n = znear;
  3664. var f = zfar;
  3665. var t = 1.0 / (Math.tan(fov * 0.5));
  3666. var a = isVerticalFovFixed ? (t / aspect) : t;
  3667. var b = isVerticalFovFixed ? t : (t * aspect);
  3668. var c = -(f + n) / (f - n);
  3669. var d = -2 * f * n / (f - n);
  3670. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3674. */
  3675. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3676. if (rightHanded === void 0) { rightHanded = false; }
  3677. var rightHandedFactor = rightHanded ? -1 : 1;
  3678. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3679. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3680. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3681. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3682. var xScale = 2.0 / (leftTan + rightTan);
  3683. var yScale = 2.0 / (upTan + downTan);
  3684. result.m[0] = xScale;
  3685. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3686. result.m[5] = yScale;
  3687. result.m[6] = result.m[7] = 0.0;
  3688. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3689. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3690. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3691. result.m[10] = -zfar / (znear - zfar);
  3692. result.m[11] = 1.0 * rightHandedFactor;
  3693. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3694. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3695. // result.m[14] = (znear * zfar) / (znear - zfar);
  3696. result._markAsUpdated();
  3697. };
  3698. /**
  3699. * Returns the final transformation matrix : world * view * projection * viewport
  3700. */
  3701. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3702. var cw = viewport.width;
  3703. var ch = viewport.height;
  3704. var cx = viewport.x;
  3705. var cy = viewport.y;
  3706. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3707. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3708. };
  3709. /**
  3710. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3711. */
  3712. Matrix.GetAsMatrix2x2 = function (matrix) {
  3713. return new Float32Array([
  3714. matrix.m[0], matrix.m[1],
  3715. matrix.m[4], matrix.m[5]
  3716. ]);
  3717. };
  3718. /**
  3719. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3720. */
  3721. Matrix.GetAsMatrix3x3 = function (matrix) {
  3722. return new Float32Array([
  3723. matrix.m[0], matrix.m[1], matrix.m[2],
  3724. matrix.m[4], matrix.m[5], matrix.m[6],
  3725. matrix.m[8], matrix.m[9], matrix.m[10]
  3726. ]);
  3727. };
  3728. /**
  3729. * Compute the transpose of the passed Matrix.
  3730. * Returns a new Matrix.
  3731. */
  3732. Matrix.Transpose = function (matrix) {
  3733. var result = new Matrix();
  3734. result.m[0] = matrix.m[0];
  3735. result.m[1] = matrix.m[4];
  3736. result.m[2] = matrix.m[8];
  3737. result.m[3] = matrix.m[12];
  3738. result.m[4] = matrix.m[1];
  3739. result.m[5] = matrix.m[5];
  3740. result.m[6] = matrix.m[9];
  3741. result.m[7] = matrix.m[13];
  3742. result.m[8] = matrix.m[2];
  3743. result.m[9] = matrix.m[6];
  3744. result.m[10] = matrix.m[10];
  3745. result.m[11] = matrix.m[14];
  3746. result.m[12] = matrix.m[3];
  3747. result.m[13] = matrix.m[7];
  3748. result.m[14] = matrix.m[11];
  3749. result.m[15] = matrix.m[15];
  3750. return result;
  3751. };
  3752. /**
  3753. * Returns a new Matrix as the reflection matrix across the passed plane.
  3754. */
  3755. Matrix.Reflection = function (plane) {
  3756. var matrix = new Matrix();
  3757. Matrix.ReflectionToRef(plane, matrix);
  3758. return matrix;
  3759. };
  3760. /**
  3761. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3762. */
  3763. Matrix.ReflectionToRef = function (plane, result) {
  3764. plane.normalize();
  3765. var x = plane.normal.x;
  3766. var y = plane.normal.y;
  3767. var z = plane.normal.z;
  3768. var temp = -2 * x;
  3769. var temp2 = -2 * y;
  3770. var temp3 = -2 * z;
  3771. result.m[0] = (temp * x) + 1;
  3772. result.m[1] = temp2 * x;
  3773. result.m[2] = temp3 * x;
  3774. result.m[3] = 0.0;
  3775. result.m[4] = temp * y;
  3776. result.m[5] = (temp2 * y) + 1;
  3777. result.m[6] = temp3 * y;
  3778. result.m[7] = 0.0;
  3779. result.m[8] = temp * z;
  3780. result.m[9] = temp2 * z;
  3781. result.m[10] = (temp3 * z) + 1;
  3782. result.m[11] = 0.0;
  3783. result.m[12] = temp * plane.d;
  3784. result.m[13] = temp2 * plane.d;
  3785. result.m[14] = temp3 * plane.d;
  3786. result.m[15] = 1.0;
  3787. result._markAsUpdated();
  3788. };
  3789. /**
  3790. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3791. */
  3792. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3793. result.m[0] = xaxis.x;
  3794. result.m[1] = xaxis.y;
  3795. result.m[2] = xaxis.z;
  3796. result.m[3] = 0.0;
  3797. result.m[4] = yaxis.x;
  3798. result.m[5] = yaxis.y;
  3799. result.m[6] = yaxis.z;
  3800. result.m[7] = 0.0;
  3801. result.m[8] = zaxis.x;
  3802. result.m[9] = zaxis.y;
  3803. result.m[10] = zaxis.z;
  3804. result.m[11] = 0.0;
  3805. result.m[12] = 0.0;
  3806. result.m[13] = 0.0;
  3807. result.m[14] = 0.0;
  3808. result.m[15] = 1.0;
  3809. result._markAsUpdated();
  3810. };
  3811. /**
  3812. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3813. */
  3814. Matrix.FromQuaternionToRef = function (quat, result) {
  3815. var xx = quat.x * quat.x;
  3816. var yy = quat.y * quat.y;
  3817. var zz = quat.z * quat.z;
  3818. var xy = quat.x * quat.y;
  3819. var zw = quat.z * quat.w;
  3820. var zx = quat.z * quat.x;
  3821. var yw = quat.y * quat.w;
  3822. var yz = quat.y * quat.z;
  3823. var xw = quat.x * quat.w;
  3824. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3825. result.m[1] = 2.0 * (xy + zw);
  3826. result.m[2] = 2.0 * (zx - yw);
  3827. result.m[3] = 0.0;
  3828. result.m[4] = 2.0 * (xy - zw);
  3829. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3830. result.m[6] = 2.0 * (yz + xw);
  3831. result.m[7] = 0.0;
  3832. result.m[8] = 2.0 * (zx + yw);
  3833. result.m[9] = 2.0 * (yz - xw);
  3834. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3835. result.m[11] = 0.0;
  3836. result.m[12] = 0.0;
  3837. result.m[13] = 0.0;
  3838. result.m[14] = 0.0;
  3839. result.m[15] = 1.0;
  3840. result._markAsUpdated();
  3841. };
  3842. return Matrix;
  3843. }());
  3844. Matrix._tempQuaternion = new Quaternion();
  3845. Matrix._xAxis = Vector3.Zero();
  3846. Matrix._yAxis = Vector3.Zero();
  3847. Matrix._zAxis = Vector3.Zero();
  3848. Matrix._updateFlagSeed = 0;
  3849. BABYLON.Matrix = Matrix;
  3850. var Plane = (function () {
  3851. /**
  3852. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3853. */
  3854. function Plane(a, b, c, d) {
  3855. this.normal = new Vector3(a, b, c);
  3856. this.d = d;
  3857. }
  3858. /**
  3859. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3860. */
  3861. Plane.prototype.asArray = function () {
  3862. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3863. };
  3864. // Methods
  3865. /**
  3866. * Returns a new plane copied from the current Plane.
  3867. */
  3868. Plane.prototype.clone = function () {
  3869. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3870. };
  3871. /**
  3872. * Returns the string "Plane".
  3873. */
  3874. Plane.prototype.getClassName = function () {
  3875. return "Plane";
  3876. };
  3877. /**
  3878. * Returns the Plane hash code.
  3879. */
  3880. Plane.prototype.getHashCode = function () {
  3881. var hash = this.normal.getHashCode();
  3882. hash = (hash * 397) ^ (this.d || 0);
  3883. return hash;
  3884. };
  3885. /**
  3886. * Normalize the current Plane in place.
  3887. * Returns the updated Plane.
  3888. */
  3889. Plane.prototype.normalize = function () {
  3890. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3891. var magnitude = 0.0;
  3892. if (norm !== 0) {
  3893. magnitude = 1.0 / norm;
  3894. }
  3895. this.normal.x *= magnitude;
  3896. this.normal.y *= magnitude;
  3897. this.normal.z *= magnitude;
  3898. this.d *= magnitude;
  3899. return this;
  3900. };
  3901. /**
  3902. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3903. */
  3904. Plane.prototype.transform = function (transformation) {
  3905. var transposedMatrix = Matrix.Transpose(transformation);
  3906. var x = this.normal.x;
  3907. var y = this.normal.y;
  3908. var z = this.normal.z;
  3909. var d = this.d;
  3910. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3911. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3912. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3913. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3914. return new Plane(normalX, normalY, normalZ, finalD);
  3915. };
  3916. /**
  3917. * Returns the dot product (float) of the point coordinates and the plane normal.
  3918. */
  3919. Plane.prototype.dotCoordinate = function (point) {
  3920. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3921. };
  3922. /**
  3923. * Updates the current Plane from the plane defined by the three passed points.
  3924. * Returns the updated Plane.
  3925. */
  3926. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3927. var x1 = point2.x - point1.x;
  3928. var y1 = point2.y - point1.y;
  3929. var z1 = point2.z - point1.z;
  3930. var x2 = point3.x - point1.x;
  3931. var y2 = point3.y - point1.y;
  3932. var z2 = point3.z - point1.z;
  3933. var yz = (y1 * z2) - (z1 * y2);
  3934. var xz = (z1 * x2) - (x1 * z2);
  3935. var xy = (x1 * y2) - (y1 * x2);
  3936. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3937. var invPyth;
  3938. if (pyth !== 0) {
  3939. invPyth = 1.0 / pyth;
  3940. }
  3941. else {
  3942. invPyth = 0.0;
  3943. }
  3944. this.normal.x = yz * invPyth;
  3945. this.normal.y = xz * invPyth;
  3946. this.normal.z = xy * invPyth;
  3947. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3948. return this;
  3949. };
  3950. /**
  3951. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3952. */
  3953. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3954. var dot = Vector3.Dot(this.normal, direction);
  3955. return (dot <= epsilon);
  3956. };
  3957. /**
  3958. * Returns the signed distance (float) from the passed point to the Plane.
  3959. */
  3960. Plane.prototype.signedDistanceTo = function (point) {
  3961. return Vector3.Dot(point, this.normal) + this.d;
  3962. };
  3963. // Statics
  3964. /**
  3965. * Returns a new Plane from the passed array.
  3966. */
  3967. Plane.FromArray = function (array) {
  3968. return new Plane(array[0], array[1], array[2], array[3]);
  3969. };
  3970. /**
  3971. * Returns a new Plane defined by the three passed points.
  3972. */
  3973. Plane.FromPoints = function (point1, point2, point3) {
  3974. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3975. result.copyFromPoints(point1, point2, point3);
  3976. return result;
  3977. };
  3978. /**
  3979. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3980. * Note : the vector "normal" is updated because normalized.
  3981. */
  3982. Plane.FromPositionAndNormal = function (origin, normal) {
  3983. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3984. normal.normalize();
  3985. result.normal = normal;
  3986. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3987. return result;
  3988. };
  3989. /**
  3990. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3991. */
  3992. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3993. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3994. return Vector3.Dot(point, normal) + d;
  3995. };
  3996. return Plane;
  3997. }());
  3998. BABYLON.Plane = Plane;
  3999. var Viewport = (function () {
  4000. /**
  4001. * Creates a Viewport object located at (x, y) and sized (width, height).
  4002. */
  4003. function Viewport(x, y, width, height) {
  4004. this.x = x;
  4005. this.y = y;
  4006. this.width = width;
  4007. this.height = height;
  4008. }
  4009. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  4010. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4011. };
  4012. /**
  4013. * Returns a new Viewport copied from the current one.
  4014. */
  4015. Viewport.prototype.clone = function () {
  4016. return new Viewport(this.x, this.y, this.width, this.height);
  4017. };
  4018. return Viewport;
  4019. }());
  4020. BABYLON.Viewport = Viewport;
  4021. var Frustum = (function () {
  4022. function Frustum() {
  4023. }
  4024. /**
  4025. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4026. */
  4027. Frustum.GetPlanes = function (transform) {
  4028. var frustumPlanes = [];
  4029. for (var index = 0; index < 6; index++) {
  4030. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4031. }
  4032. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4033. return frustumPlanes;
  4034. };
  4035. /**
  4036. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4037. */
  4038. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4039. // Near
  4040. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4041. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4042. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4043. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4044. frustumPlanes[0].normalize();
  4045. // Far
  4046. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4047. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4048. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4049. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4050. frustumPlanes[1].normalize();
  4051. // Left
  4052. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4053. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4054. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4055. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4056. frustumPlanes[2].normalize();
  4057. // Right
  4058. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4059. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4060. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4061. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4062. frustumPlanes[3].normalize();
  4063. // Top
  4064. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4065. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4066. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4067. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4068. frustumPlanes[4].normalize();
  4069. // Bottom
  4070. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4071. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4072. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4073. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4074. frustumPlanes[5].normalize();
  4075. };
  4076. return Frustum;
  4077. }());
  4078. BABYLON.Frustum = Frustum;
  4079. var Space;
  4080. (function (Space) {
  4081. Space[Space["LOCAL"] = 0] = "LOCAL";
  4082. Space[Space["WORLD"] = 1] = "WORLD";
  4083. Space[Space["BONE"] = 2] = "BONE";
  4084. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4085. var Axis = (function () {
  4086. function Axis() {
  4087. }
  4088. return Axis;
  4089. }());
  4090. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4091. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4092. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4093. BABYLON.Axis = Axis;
  4094. ;
  4095. var BezierCurve = (function () {
  4096. function BezierCurve() {
  4097. }
  4098. /**
  4099. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4100. */
  4101. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4102. // Extract X (which is equal to time here)
  4103. var f0 = 1 - 3 * x2 + 3 * x1;
  4104. var f1 = 3 * x2 - 6 * x1;
  4105. var f2 = 3 * x1;
  4106. var refinedT = t;
  4107. for (var i = 0; i < 5; i++) {
  4108. var refinedT2 = refinedT * refinedT;
  4109. var refinedT3 = refinedT2 * refinedT;
  4110. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4111. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4112. refinedT -= (x - t) * slope;
  4113. refinedT = Math.min(1, Math.max(0, refinedT));
  4114. }
  4115. // Resolve cubic bezier for the given x
  4116. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4117. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4118. Math.pow(refinedT, 3);
  4119. };
  4120. return BezierCurve;
  4121. }());
  4122. BABYLON.BezierCurve = BezierCurve;
  4123. var Orientation;
  4124. (function (Orientation) {
  4125. Orientation[Orientation["CW"] = 0] = "CW";
  4126. Orientation[Orientation["CCW"] = 1] = "CCW";
  4127. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4128. var Angle = (function () {
  4129. /**
  4130. * Creates an Angle object of "radians" radians (float).
  4131. */
  4132. function Angle(radians) {
  4133. var _this = this;
  4134. /**
  4135. * Returns the Angle value in degrees (float).
  4136. */
  4137. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4138. /**
  4139. * Returns the Angle value in radians (float).
  4140. */
  4141. this.radians = function () { return _this._radians; };
  4142. this._radians = radians;
  4143. if (this._radians < 0.0)
  4144. this._radians += (2.0 * Math.PI);
  4145. }
  4146. /**
  4147. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4148. */
  4149. Angle.BetweenTwoPoints = function (a, b) {
  4150. var delta = b.subtract(a);
  4151. var theta = Math.atan2(delta.y, delta.x);
  4152. return new Angle(theta);
  4153. };
  4154. /**
  4155. * Returns a new Angle object from the passed float in radians.
  4156. */
  4157. Angle.FromRadians = function (radians) {
  4158. return new Angle(radians);
  4159. };
  4160. /**
  4161. * Returns a new Angle object from the passed float in degrees.
  4162. */
  4163. Angle.FromDegrees = function (degrees) {
  4164. return new Angle(degrees * Math.PI / 180.0);
  4165. };
  4166. return Angle;
  4167. }());
  4168. BABYLON.Angle = Angle;
  4169. var Arc2 = (function () {
  4170. /**
  4171. * Creates an Arc object from the three passed points : start, middle and end.
  4172. */
  4173. function Arc2(startPoint, midPoint, endPoint) {
  4174. this.startPoint = startPoint;
  4175. this.midPoint = midPoint;
  4176. this.endPoint = endPoint;
  4177. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4178. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4179. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4180. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4181. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4182. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4183. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4184. var a1 = this.startAngle.degrees();
  4185. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4186. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4187. // angles correction
  4188. if (a2 - a1 > +180.0)
  4189. a2 -= 360.0;
  4190. if (a2 - a1 < -180.0)
  4191. a2 += 360.0;
  4192. if (a3 - a2 > +180.0)
  4193. a3 -= 360.0;
  4194. if (a3 - a2 < -180.0)
  4195. a3 += 360.0;
  4196. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4197. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4198. }
  4199. return Arc2;
  4200. }());
  4201. BABYLON.Arc2 = Arc2;
  4202. var Path2 = (function () {
  4203. /**
  4204. * Creates a Path2 object from the starting 2D coordinates x and y.
  4205. */
  4206. function Path2(x, y) {
  4207. this._points = new Array();
  4208. this._length = 0.0;
  4209. this.closed = false;
  4210. this._points.push(new Vector2(x, y));
  4211. }
  4212. /**
  4213. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4214. * Returns the updated Path2.
  4215. */
  4216. Path2.prototype.addLineTo = function (x, y) {
  4217. if (closed) {
  4218. //Tools.Error("cannot add lines to closed paths");
  4219. return this;
  4220. }
  4221. var newPoint = new Vector2(x, y);
  4222. var previousPoint = this._points[this._points.length - 1];
  4223. this._points.push(newPoint);
  4224. this._length += newPoint.subtract(previousPoint).length();
  4225. return this;
  4226. };
  4227. /**
  4228. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4229. * Returns the updated Path2.
  4230. */
  4231. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4232. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4233. if (closed) {
  4234. //Tools.Error("cannot add arcs to closed paths");
  4235. return this;
  4236. }
  4237. var startPoint = this._points[this._points.length - 1];
  4238. var midPoint = new Vector2(midX, midY);
  4239. var endPoint = new Vector2(endX, endY);
  4240. var arc = new Arc2(startPoint, midPoint, endPoint);
  4241. var increment = arc.angle.radians() / numberOfSegments;
  4242. if (arc.orientation === Orientation.CW)
  4243. increment *= -1;
  4244. var currentAngle = arc.startAngle.radians() + increment;
  4245. for (var i = 0; i < numberOfSegments; i++) {
  4246. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4247. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4248. this.addLineTo(x, y);
  4249. currentAngle += increment;
  4250. }
  4251. return this;
  4252. };
  4253. /**
  4254. * Closes the Path2.
  4255. * Returns the Path2.
  4256. */
  4257. Path2.prototype.close = function () {
  4258. this.closed = true;
  4259. return this;
  4260. };
  4261. /**
  4262. * Returns the Path2 total length (float).
  4263. */
  4264. Path2.prototype.length = function () {
  4265. var result = this._length;
  4266. if (!this.closed) {
  4267. var lastPoint = this._points[this._points.length - 1];
  4268. var firstPoint = this._points[0];
  4269. result += (firstPoint.subtract(lastPoint).length());
  4270. }
  4271. return result;
  4272. };
  4273. /**
  4274. * Returns the Path2 internal array of points.
  4275. */
  4276. Path2.prototype.getPoints = function () {
  4277. return this._points;
  4278. };
  4279. /**
  4280. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4281. */
  4282. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4283. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4284. //Tools.Error("normalized length position should be between 0 and 1.");
  4285. return Vector2.Zero();
  4286. }
  4287. var lengthPosition = normalizedLengthPosition * this.length();
  4288. var previousOffset = 0;
  4289. for (var i = 0; i < this._points.length; i++) {
  4290. var j = (i + 1) % this._points.length;
  4291. var a = this._points[i];
  4292. var b = this._points[j];
  4293. var bToA = b.subtract(a);
  4294. var nextOffset = (bToA.length() + previousOffset);
  4295. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4296. var dir = bToA.normalize();
  4297. var localOffset = lengthPosition - previousOffset;
  4298. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4299. }
  4300. previousOffset = nextOffset;
  4301. }
  4302. //Tools.Error("internal error");
  4303. return Vector2.Zero();
  4304. };
  4305. /**
  4306. * Returns a new Path2 starting at the coordinates (x, y).
  4307. */
  4308. Path2.StartingAt = function (x, y) {
  4309. return new Path2(x, y);
  4310. };
  4311. return Path2;
  4312. }());
  4313. BABYLON.Path2 = Path2;
  4314. var Path3D = (function () {
  4315. /**
  4316. * new Path3D(path, normal, raw)
  4317. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4318. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4319. * path : an array of Vector3, the curve axis of the Path3D
  4320. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4321. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4322. */
  4323. function Path3D(path, firstNormal, raw) {
  4324. this.path = path;
  4325. this._curve = new Array();
  4326. this._distances = new Array();
  4327. this._tangents = new Array();
  4328. this._normals = new Array();
  4329. this._binormals = new Array();
  4330. for (var p = 0; p < path.length; p++) {
  4331. this._curve[p] = path[p].clone(); // hard copy
  4332. }
  4333. this._raw = raw || false;
  4334. this._compute(firstNormal);
  4335. }
  4336. /**
  4337. * Returns the Path3D array of successive Vector3 designing its curve.
  4338. */
  4339. Path3D.prototype.getCurve = function () {
  4340. return this._curve;
  4341. };
  4342. /**
  4343. * Returns an array populated with tangent vectors on each Path3D curve point.
  4344. */
  4345. Path3D.prototype.getTangents = function () {
  4346. return this._tangents;
  4347. };
  4348. /**
  4349. * Returns an array populated with normal vectors on each Path3D curve point.
  4350. */
  4351. Path3D.prototype.getNormals = function () {
  4352. return this._normals;
  4353. };
  4354. /**
  4355. * Returns an array populated with binormal vectors on each Path3D curve point.
  4356. */
  4357. Path3D.prototype.getBinormals = function () {
  4358. return this._binormals;
  4359. };
  4360. /**
  4361. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4362. */
  4363. Path3D.prototype.getDistances = function () {
  4364. return this._distances;
  4365. };
  4366. /**
  4367. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4368. * Returns the same object updated.
  4369. */
  4370. Path3D.prototype.update = function (path, firstNormal) {
  4371. for (var p = 0; p < path.length; p++) {
  4372. this._curve[p].x = path[p].x;
  4373. this._curve[p].y = path[p].y;
  4374. this._curve[p].z = path[p].z;
  4375. }
  4376. this._compute(firstNormal);
  4377. return this;
  4378. };
  4379. // private function compute() : computes tangents, normals and binormals
  4380. Path3D.prototype._compute = function (firstNormal) {
  4381. var l = this._curve.length;
  4382. // first and last tangents
  4383. this._tangents[0] = this._getFirstNonNullVector(0);
  4384. if (!this._raw) {
  4385. this._tangents[0].normalize();
  4386. }
  4387. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4388. if (!this._raw) {
  4389. this._tangents[l - 1].normalize();
  4390. }
  4391. // normals and binormals at first point : arbitrary vector with _normalVector()
  4392. var tg0 = this._tangents[0];
  4393. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4394. this._normals[0] = pp0;
  4395. if (!this._raw) {
  4396. this._normals[0].normalize();
  4397. }
  4398. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4399. if (!this._raw) {
  4400. this._binormals[0].normalize();
  4401. }
  4402. this._distances[0] = 0.0;
  4403. // normals and binormals : next points
  4404. var prev; // previous vector (segment)
  4405. var cur; // current vector (segment)
  4406. var curTang; // current tangent
  4407. // previous normal
  4408. var prevBinor; // previous binormal
  4409. for (var i = 1; i < l; i++) {
  4410. // tangents
  4411. prev = this._getLastNonNullVector(i);
  4412. if (i < l - 1) {
  4413. cur = this._getFirstNonNullVector(i);
  4414. this._tangents[i] = prev.add(cur);
  4415. this._tangents[i].normalize();
  4416. }
  4417. this._distances[i] = this._distances[i - 1] + prev.length();
  4418. // normals and binormals
  4419. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4420. curTang = this._tangents[i];
  4421. prevBinor = this._binormals[i - 1];
  4422. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4423. if (!this._raw) {
  4424. this._normals[i].normalize();
  4425. }
  4426. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4427. if (!this._raw) {
  4428. this._binormals[i].normalize();
  4429. }
  4430. }
  4431. };
  4432. // private function getFirstNonNullVector(index)
  4433. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4434. Path3D.prototype._getFirstNonNullVector = function (index) {
  4435. var i = 1;
  4436. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4437. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4438. i++;
  4439. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4440. }
  4441. return nNVector;
  4442. };
  4443. // private function getLastNonNullVector(index)
  4444. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4445. Path3D.prototype._getLastNonNullVector = function (index) {
  4446. var i = 1;
  4447. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4448. while (nLVector.length() === 0 && index > i + 1) {
  4449. i++;
  4450. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4451. }
  4452. return nLVector;
  4453. };
  4454. // private function normalVector(v0, vt, va) :
  4455. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4456. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4457. Path3D.prototype._normalVector = function (v0, vt, va) {
  4458. var normal0;
  4459. var tgl = vt.length();
  4460. if (tgl === 0.0) {
  4461. tgl = 1.0;
  4462. }
  4463. if (va === undefined || va === null) {
  4464. var point;
  4465. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4466. point = new Vector3(0.0, -1.0, 0.0);
  4467. }
  4468. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4469. point = new Vector3(1.0, 0.0, 0.0);
  4470. }
  4471. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4472. point = new Vector3(0.0, 0.0, 1.0);
  4473. }
  4474. normal0 = Vector3.Cross(vt, point);
  4475. }
  4476. else {
  4477. normal0 = Vector3.Cross(vt, va);
  4478. Vector3.CrossToRef(normal0, vt, normal0);
  4479. }
  4480. normal0.normalize();
  4481. return normal0;
  4482. };
  4483. return Path3D;
  4484. }());
  4485. BABYLON.Path3D = Path3D;
  4486. var Curve3 = (function () {
  4487. /**
  4488. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4489. * A Curve3 is designed from a series of successive Vector3.
  4490. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4491. */
  4492. function Curve3(points) {
  4493. this._length = 0.0;
  4494. this._points = points;
  4495. this._length = this._computeLength(points);
  4496. }
  4497. /**
  4498. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4499. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4500. * @param v1 (Vector3) the control point
  4501. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4502. * @param nbPoints (integer) the wanted number of points in the curve
  4503. */
  4504. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4505. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4506. var bez = new Array();
  4507. var equation = function (t, val0, val1, val2) {
  4508. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4509. return res;
  4510. };
  4511. for (var i = 0; i <= nbPoints; i++) {
  4512. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4513. }
  4514. return new Curve3(bez);
  4515. };
  4516. /**
  4517. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4518. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4519. * @param v1 (Vector3) the first control point
  4520. * @param v2 (Vector3) the second control point
  4521. * @param v3 (Vector3) the end point of the Cubic Bezier
  4522. * @param nbPoints (integer) the wanted number of points in the curve
  4523. */
  4524. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4525. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4526. var bez = new Array();
  4527. var equation = function (t, val0, val1, val2, val3) {
  4528. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4529. return res;
  4530. };
  4531. for (var i = 0; i <= nbPoints; i++) {
  4532. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4533. }
  4534. return new Curve3(bez);
  4535. };
  4536. /**
  4537. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4538. * @param p1 (Vector3) the origin point of the Hermite Spline
  4539. * @param t1 (Vector3) the tangent vector at the origin point
  4540. * @param p2 (Vector3) the end point of the Hermite Spline
  4541. * @param t2 (Vector3) the tangent vector at the end point
  4542. * @param nbPoints (integer) the wanted number of points in the curve
  4543. */
  4544. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4545. var hermite = new Array();
  4546. var step = 1.0 / nbPoints;
  4547. for (var i = 0; i <= nbPoints; i++) {
  4548. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4549. }
  4550. return new Curve3(hermite);
  4551. };
  4552. /**
  4553. * Returns a Curve3 object along a CatmullRom Spline curve :
  4554. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4555. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4556. */
  4557. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4558. var totalPoints = new Array();
  4559. totalPoints.push(points[0].clone());
  4560. Array.prototype.push.apply(totalPoints, points);
  4561. totalPoints.push(points[points.length - 1].clone());
  4562. var catmullRom = new Array();
  4563. var step = 1.0 / nbPoints;
  4564. for (var i = 0; i < totalPoints.length - 3; i++) {
  4565. var amount = 0.0;
  4566. for (var c = 0; c < nbPoints; c++) {
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. amount += step;
  4569. }
  4570. }
  4571. i--;
  4572. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4573. return new Curve3(catmullRom);
  4574. };
  4575. /**
  4576. * Returns the Curve3 stored array of successive Vector3
  4577. */
  4578. Curve3.prototype.getPoints = function () {
  4579. return this._points;
  4580. };
  4581. /**
  4582. * Returns the computed length (float) of the curve.
  4583. */
  4584. Curve3.prototype.length = function () {
  4585. return this._length;
  4586. };
  4587. /**
  4588. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4589. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4590. * curveA and curveB keep unchanged.
  4591. */
  4592. Curve3.prototype.continue = function (curve) {
  4593. var lastPoint = this._points[this._points.length - 1];
  4594. var continuedPoints = this._points.slice();
  4595. var curvePoints = curve.getPoints();
  4596. for (var i = 1; i < curvePoints.length; i++) {
  4597. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4598. }
  4599. var continuedCurve = new Curve3(continuedPoints);
  4600. return continuedCurve;
  4601. };
  4602. Curve3.prototype._computeLength = function (path) {
  4603. var l = 0;
  4604. for (var i = 1; i < path.length; i++) {
  4605. l += (path[i].subtract(path[i - 1])).length();
  4606. }
  4607. return l;
  4608. };
  4609. return Curve3;
  4610. }());
  4611. BABYLON.Curve3 = Curve3;
  4612. // SphericalHarmonics
  4613. var SphericalHarmonics = (function () {
  4614. function SphericalHarmonics() {
  4615. this.L00 = Vector3.Zero();
  4616. this.L1_1 = Vector3.Zero();
  4617. this.L10 = Vector3.Zero();
  4618. this.L11 = Vector3.Zero();
  4619. this.L2_2 = Vector3.Zero();
  4620. this.L2_1 = Vector3.Zero();
  4621. this.L20 = Vector3.Zero();
  4622. this.L21 = Vector3.Zero();
  4623. this.L22 = Vector3.Zero();
  4624. }
  4625. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4626. var colorVector = new Vector3(color.r, color.g, color.b);
  4627. var c = colorVector.scale(deltaSolidAngle);
  4628. this.L00 = this.L00.add(c.scale(0.282095));
  4629. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4630. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4631. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4632. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4633. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4634. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4635. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4636. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4637. };
  4638. SphericalHarmonics.prototype.scale = function (scale) {
  4639. this.L00 = this.L00.scale(scale);
  4640. this.L1_1 = this.L1_1.scale(scale);
  4641. this.L10 = this.L10.scale(scale);
  4642. this.L11 = this.L11.scale(scale);
  4643. this.L2_2 = this.L2_2.scale(scale);
  4644. this.L2_1 = this.L2_1.scale(scale);
  4645. this.L20 = this.L20.scale(scale);
  4646. this.L21 = this.L21.scale(scale);
  4647. this.L22 = this.L22.scale(scale);
  4648. };
  4649. return SphericalHarmonics;
  4650. }());
  4651. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4652. // SphericalPolynomial
  4653. var SphericalPolynomial = (function () {
  4654. function SphericalPolynomial() {
  4655. this.x = Vector3.Zero();
  4656. this.y = Vector3.Zero();
  4657. this.z = Vector3.Zero();
  4658. this.xx = Vector3.Zero();
  4659. this.yy = Vector3.Zero();
  4660. this.zz = Vector3.Zero();
  4661. this.xy = Vector3.Zero();
  4662. this.yz = Vector3.Zero();
  4663. this.zx = Vector3.Zero();
  4664. }
  4665. SphericalPolynomial.prototype.addAmbient = function (color) {
  4666. var colorVector = new Vector3(color.r, color.g, color.b);
  4667. this.xx = this.xx.add(colorVector);
  4668. this.yy = this.yy.add(colorVector);
  4669. this.zz = this.zz.add(colorVector);
  4670. };
  4671. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4672. var result = new SphericalPolynomial();
  4673. result.x = harmonics.L11.scale(1.02333);
  4674. result.y = harmonics.L1_1.scale(1.02333);
  4675. result.z = harmonics.L10.scale(1.02333);
  4676. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4677. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4678. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4679. result.yz = harmonics.L2_1.scale(0.858086);
  4680. result.zx = harmonics.L21.scale(0.858086);
  4681. result.xy = harmonics.L2_2.scale(0.858086);
  4682. return result;
  4683. };
  4684. return SphericalPolynomial;
  4685. }());
  4686. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4687. // Vertex formats
  4688. var PositionNormalVertex = (function () {
  4689. function PositionNormalVertex(position, normal) {
  4690. if (position === void 0) { position = Vector3.Zero(); }
  4691. if (normal === void 0) { normal = Vector3.Up(); }
  4692. this.position = position;
  4693. this.normal = normal;
  4694. }
  4695. PositionNormalVertex.prototype.clone = function () {
  4696. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4697. };
  4698. return PositionNormalVertex;
  4699. }());
  4700. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4701. var PositionNormalTextureVertex = (function () {
  4702. function PositionNormalTextureVertex(position, normal, uv) {
  4703. if (position === void 0) { position = Vector3.Zero(); }
  4704. if (normal === void 0) { normal = Vector3.Up(); }
  4705. if (uv === void 0) { uv = Vector2.Zero(); }
  4706. this.position = position;
  4707. this.normal = normal;
  4708. this.uv = uv;
  4709. }
  4710. PositionNormalTextureVertex.prototype.clone = function () {
  4711. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4712. };
  4713. return PositionNormalTextureVertex;
  4714. }());
  4715. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4716. // Temporary pre-allocated objects for engine internal use
  4717. // usage in any internal function :
  4718. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4719. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4720. var Tmp = (function () {
  4721. function Tmp() {
  4722. }
  4723. return Tmp;
  4724. }());
  4725. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4726. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4727. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4728. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4729. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4730. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4731. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4732. Matrix.Zero(), Matrix.Zero(),
  4733. Matrix.Zero(), Matrix.Zero(),
  4734. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4735. BABYLON.Tmp = Tmp;
  4736. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4737. var MathTmp = (function () {
  4738. function MathTmp() {
  4739. }
  4740. return MathTmp;
  4741. }());
  4742. MathTmp.Vector3 = [Vector3.Zero()];
  4743. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4744. MathTmp.Quaternion = [Quaternion.Zero()];
  4745. })(BABYLON || (BABYLON = {}));
  4746. //# sourceMappingURL=babylon.math.js.map
  4747. //# sourceMappingURL=babylon.mixins.js.map
  4748. var BABYLON;
  4749. (function (BABYLON) {
  4750. function generateSerializableMember(type, sourceName) {
  4751. return function (target, propertyKey) {
  4752. if (!target.__serializableMembers) {
  4753. target.__serializableMembers = {};
  4754. }
  4755. if (!target.__serializableMembers[propertyKey]) {
  4756. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4757. }
  4758. };
  4759. }
  4760. function generateExpandMember(setCallback, targetKey) {
  4761. return function (target, propertyKey) {
  4762. var key = targetKey || ("_" + propertyKey);
  4763. Object.defineProperty(target, propertyKey, {
  4764. get: function () {
  4765. return this[key];
  4766. },
  4767. set: function (value) {
  4768. if (this[key] === value) {
  4769. return;
  4770. }
  4771. this[key] = value;
  4772. target[setCallback].apply(this);
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. };
  4778. }
  4779. function expandToProperty(callback, targetKey) {
  4780. return generateExpandMember(callback, targetKey);
  4781. }
  4782. BABYLON.expandToProperty = expandToProperty;
  4783. function serialize(sourceName) {
  4784. return generateSerializableMember(0, sourceName); // value member
  4785. }
  4786. BABYLON.serialize = serialize;
  4787. function serializeAsTexture(sourceName) {
  4788. return generateSerializableMember(1, sourceName); // texture member
  4789. }
  4790. BABYLON.serializeAsTexture = serializeAsTexture;
  4791. function serializeAsColor3(sourceName) {
  4792. return generateSerializableMember(2, sourceName); // color3 member
  4793. }
  4794. BABYLON.serializeAsColor3 = serializeAsColor3;
  4795. function serializeAsFresnelParameters(sourceName) {
  4796. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4797. }
  4798. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4799. function serializeAsVector2(sourceName) {
  4800. return generateSerializableMember(4, sourceName); // vector2 member
  4801. }
  4802. BABYLON.serializeAsVector2 = serializeAsVector2;
  4803. function serializeAsVector3(sourceName) {
  4804. return generateSerializableMember(5, sourceName); // vector3 member
  4805. }
  4806. BABYLON.serializeAsVector3 = serializeAsVector3;
  4807. function serializeAsMeshReference(sourceName) {
  4808. return generateSerializableMember(6, sourceName); // mesh reference member
  4809. }
  4810. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4811. function serializeAsColorCurves(sourceName) {
  4812. return generateSerializableMember(7, sourceName); // color curves
  4813. }
  4814. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4815. function serializeAsColor4(sourceName) {
  4816. return generateSerializableMember(8, sourceName); // color 4
  4817. }
  4818. BABYLON.serializeAsColor4 = serializeAsColor4;
  4819. function serializeAsImageProcessingConfiguration(sourceName) {
  4820. return generateSerializableMember(9, sourceName); // image processing
  4821. }
  4822. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  4823. var SerializationHelper = (function () {
  4824. function SerializationHelper() {
  4825. }
  4826. SerializationHelper.Serialize = function (entity, serializationObject) {
  4827. if (!serializationObject) {
  4828. serializationObject = {};
  4829. }
  4830. // Tags
  4831. if (BABYLON.Tags) {
  4832. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4833. }
  4834. // Properties
  4835. for (var property in entity.__serializableMembers) {
  4836. var propertyDescriptor = entity.__serializableMembers[property];
  4837. var targetPropertyName = propertyDescriptor.sourceName || property;
  4838. var propertyType = propertyDescriptor.type;
  4839. var sourceProperty = entity[property];
  4840. if (sourceProperty !== undefined && sourceProperty !== null) {
  4841. switch (propertyType) {
  4842. case 0:
  4843. serializationObject[targetPropertyName] = sourceProperty;
  4844. break;
  4845. case 1:
  4846. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4847. break;
  4848. case 2:
  4849. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4850. break;
  4851. case 3:
  4852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4853. break;
  4854. case 4:
  4855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4856. break;
  4857. case 5:
  4858. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4859. break;
  4860. case 6:
  4861. serializationObject[targetPropertyName] = sourceProperty.id;
  4862. break;
  4863. case 7:
  4864. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4865. break;
  4866. case 8:
  4867. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4868. break;
  4869. case 9:
  4870. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. return serializationObject;
  4876. };
  4877. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4878. var destination = creationFunction();
  4879. // Tags
  4880. if (BABYLON.Tags) {
  4881. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4882. }
  4883. // Properties
  4884. for (var property in destination.__serializableMembers) {
  4885. var propertyDescriptor = destination.__serializableMembers[property];
  4886. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4887. var propertyType = propertyDescriptor.type;
  4888. if (sourceProperty !== undefined && sourceProperty !== null) {
  4889. switch (propertyType) {
  4890. case 0:
  4891. destination[property] = sourceProperty;
  4892. break;
  4893. case 1:
  4894. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4895. break;
  4896. case 2:
  4897. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4898. break;
  4899. case 3:
  4900. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4901. break;
  4902. case 4:
  4903. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4904. break;
  4905. case 5:
  4906. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4907. break;
  4908. case 6:
  4909. destination[property] = scene.getLastMeshByID(sourceProperty);
  4910. break;
  4911. case 7:
  4912. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4913. break;
  4914. case 8:
  4915. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  4916. break;
  4917. case 9:
  4918. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  4919. break;
  4920. }
  4921. }
  4922. }
  4923. return destination;
  4924. };
  4925. SerializationHelper.Clone = function (creationFunction, source) {
  4926. var destination = creationFunction();
  4927. // Tags
  4928. if (BABYLON.Tags) {
  4929. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4930. }
  4931. // Properties
  4932. for (var property in destination.__serializableMembers) {
  4933. var propertyDescriptor = destination.__serializableMembers[property];
  4934. var sourceProperty = source[property];
  4935. var propertyType = propertyDescriptor.type;
  4936. if (sourceProperty !== undefined && sourceProperty !== null) {
  4937. switch (propertyType) {
  4938. case 0: // Value
  4939. case 6:
  4940. destination[property] = sourceProperty;
  4941. break;
  4942. case 1: // Texture
  4943. case 2: // Color3
  4944. case 3: // FresnelParameters
  4945. case 4: // Vector2
  4946. case 5: // Vector3
  4947. case 7:
  4948. destination[property] = sourceProperty.clone();
  4949. break;
  4950. }
  4951. }
  4952. }
  4953. return destination;
  4954. };
  4955. return SerializationHelper;
  4956. }());
  4957. BABYLON.SerializationHelper = SerializationHelper;
  4958. })(BABYLON || (BABYLON = {}));
  4959. //# sourceMappingURL=babylon.decorators.js.map
  4960. var BABYLON;
  4961. (function (BABYLON) {
  4962. /**
  4963. * A class serves as a medium between the observable and its observers
  4964. */
  4965. var EventState = (function () {
  4966. /**
  4967. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4968. */
  4969. function EventState(mask, skipNextObservers) {
  4970. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4971. this.initalize(mask, skipNextObservers);
  4972. }
  4973. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4974. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4975. this.mask = mask;
  4976. this.skipNextObservers = skipNextObservers;
  4977. return this;
  4978. };
  4979. return EventState;
  4980. }());
  4981. BABYLON.EventState = EventState;
  4982. /**
  4983. * Represent an Observer registered to a given Observable object.
  4984. */
  4985. var Observer = (function () {
  4986. function Observer(callback, mask) {
  4987. this.callback = callback;
  4988. this.mask = mask;
  4989. }
  4990. return Observer;
  4991. }());
  4992. BABYLON.Observer = Observer;
  4993. /**
  4994. * The Observable class is a simple implementation of the Observable pattern.
  4995. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4996. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4997. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4998. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4999. */
  5000. var Observable = (function () {
  5001. function Observable() {
  5002. this._observers = new Array();
  5003. this._eventState = new EventState(0);
  5004. }
  5005. /**
  5006. * Create a new Observer with the specified callback
  5007. * @param callback the callback that will be executed for that Observer
  5008. * @param mask the mask used to filter observers
  5009. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5010. */
  5011. Observable.prototype.add = function (callback, mask, insertFirst) {
  5012. if (mask === void 0) { mask = -1; }
  5013. if (insertFirst === void 0) { insertFirst = false; }
  5014. if (!callback) {
  5015. return null;
  5016. }
  5017. var observer = new Observer(callback, mask);
  5018. if (insertFirst) {
  5019. this._observers.unshift(observer);
  5020. }
  5021. else {
  5022. this._observers.push(observer);
  5023. }
  5024. return observer;
  5025. };
  5026. /**
  5027. * Remove an Observer from the Observable object
  5028. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5029. */
  5030. Observable.prototype.remove = function (observer) {
  5031. var index = this._observers.indexOf(observer);
  5032. if (index !== -1) {
  5033. this._observers.splice(index, 1);
  5034. return true;
  5035. }
  5036. return false;
  5037. };
  5038. /**
  5039. * Remove a callback from the Observable object
  5040. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5041. */
  5042. Observable.prototype.removeCallback = function (callback) {
  5043. for (var index = 0; index < this._observers.length; index++) {
  5044. if (this._observers[index].callback === callback) {
  5045. this._observers.splice(index, 1);
  5046. return true;
  5047. }
  5048. }
  5049. return false;
  5050. };
  5051. /**
  5052. * Notify all Observers by calling their respective callback with the given data
  5053. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5054. * @param eventData
  5055. * @param mask
  5056. */
  5057. Observable.prototype.notifyObservers = function (eventData, mask) {
  5058. if (mask === void 0) { mask = -1; }
  5059. var state = this._eventState;
  5060. state.mask = mask;
  5061. state.skipNextObservers = false;
  5062. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5063. var obs = _a[_i];
  5064. if (obs.mask & mask) {
  5065. obs.callback(eventData, state);
  5066. }
  5067. if (state.skipNextObservers) {
  5068. return false;
  5069. }
  5070. }
  5071. return true;
  5072. };
  5073. /**
  5074. * return true is the Observable has at least one Observer registered
  5075. */
  5076. Observable.prototype.hasObservers = function () {
  5077. return this._observers.length > 0;
  5078. };
  5079. /**
  5080. * Clear the list of observers
  5081. */
  5082. Observable.prototype.clear = function () {
  5083. this._observers = new Array();
  5084. };
  5085. /**
  5086. * Clone the current observable
  5087. */
  5088. Observable.prototype.clone = function () {
  5089. var result = new Observable();
  5090. result._observers = this._observers.slice(0);
  5091. return result;
  5092. };
  5093. /**
  5094. * Does this observable handles observer registered with a given mask
  5095. * @param {number} trigger - the mask to be tested
  5096. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5097. **/
  5098. Observable.prototype.hasSpecificMask = function (mask) {
  5099. if (mask === void 0) { mask = -1; }
  5100. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5101. var obs = _a[_i];
  5102. if (obs.mask & mask && obs.mask === mask) {
  5103. return true;
  5104. }
  5105. }
  5106. return false;
  5107. };
  5108. return Observable;
  5109. }());
  5110. BABYLON.Observable = Observable;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.observable.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. var SmartArray = (function () {
  5116. function SmartArray(capacity) {
  5117. this.length = 0;
  5118. this._duplicateId = 0;
  5119. this.data = new Array(capacity);
  5120. this._id = SmartArray._GlobalId++;
  5121. }
  5122. SmartArray.prototype.push = function (value) {
  5123. this.data[this.length++] = value;
  5124. if (this.length > this.data.length) {
  5125. this.data.length *= 2;
  5126. }
  5127. if (!value.__smartArrayFlags) {
  5128. value.__smartArrayFlags = {};
  5129. }
  5130. value.__smartArrayFlags[this._id] = this._duplicateId;
  5131. };
  5132. SmartArray.prototype.forEach = function (func) {
  5133. for (var index = 0; index < this.length; index++) {
  5134. func(this.data[index]);
  5135. }
  5136. };
  5137. SmartArray.prototype.pushNoDuplicate = function (value) {
  5138. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5139. return false;
  5140. }
  5141. this.push(value);
  5142. return true;
  5143. };
  5144. SmartArray.prototype.sort = function (compareFn) {
  5145. this.data.sort(compareFn);
  5146. };
  5147. SmartArray.prototype.reset = function () {
  5148. this.length = 0;
  5149. this._duplicateId++;
  5150. };
  5151. SmartArray.prototype.dispose = function () {
  5152. this.reset();
  5153. this.data.length = 0;
  5154. };
  5155. SmartArray.prototype.concat = function (array) {
  5156. if (array.length === 0) {
  5157. return;
  5158. }
  5159. if (this.length + array.length > this.data.length) {
  5160. this.data.length = (this.length + array.length) * 2;
  5161. }
  5162. for (var index = 0; index < array.length; index++) {
  5163. this.data[this.length++] = (array.data || array)[index];
  5164. }
  5165. };
  5166. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5167. if (array.length === 0) {
  5168. return;
  5169. }
  5170. if (this.length + array.length > this.data.length) {
  5171. this.data.length = (this.length + array.length) * 2;
  5172. }
  5173. for (var index = 0; index < array.length; index++) {
  5174. var item = (array.data || array)[index];
  5175. this.pushNoDuplicate(item);
  5176. }
  5177. };
  5178. SmartArray.prototype.indexOf = function (value) {
  5179. var position = this.data.indexOf(value);
  5180. if (position >= this.length) {
  5181. return -1;
  5182. }
  5183. return position;
  5184. };
  5185. SmartArray.prototype.contains = function (value) {
  5186. return this.data.indexOf(value) !== -1;
  5187. };
  5188. return SmartArray;
  5189. }());
  5190. // Statics
  5191. SmartArray._GlobalId = 0;
  5192. BABYLON.SmartArray = SmartArray;
  5193. })(BABYLON || (BABYLON = {}));
  5194. //# sourceMappingURL=babylon.smartArray.js.map
  5195. var BABYLON;
  5196. (function (BABYLON) {
  5197. // Screenshots
  5198. var screenshotCanvas;
  5199. var cloneValue = function (source, destinationObject) {
  5200. if (!source)
  5201. return null;
  5202. if (source instanceof BABYLON.Mesh) {
  5203. return null;
  5204. }
  5205. if (source instanceof BABYLON.SubMesh) {
  5206. return source.clone(destinationObject);
  5207. }
  5208. else if (source.clone) {
  5209. return source.clone();
  5210. }
  5211. return null;
  5212. };
  5213. var Tools = (function () {
  5214. function Tools() {
  5215. }
  5216. ;
  5217. /**
  5218. * Interpolates between a and b via alpha
  5219. * @param a The lower value (returned when alpha = 0)
  5220. * @param b The upper value (returned when alpha = 1)
  5221. * @param alpha The interpolation-factor
  5222. * @return The mixed value
  5223. */
  5224. Tools.Mix = function (a, b, alpha) {
  5225. return a * (1 - alpha) + b * alpha;
  5226. };
  5227. Tools.Instantiate = function (className) {
  5228. var arr = className.split(".");
  5229. var fn = (window || this);
  5230. for (var i = 0, len = arr.length; i < len; i++) {
  5231. fn = fn[arr[i]];
  5232. }
  5233. if (typeof fn !== "function") {
  5234. return null;
  5235. }
  5236. return fn;
  5237. };
  5238. Tools.SetImmediate = function (action) {
  5239. if (window.setImmediate) {
  5240. window.setImmediate(action);
  5241. }
  5242. else {
  5243. setTimeout(action, 1);
  5244. }
  5245. };
  5246. Tools.IsExponentOfTwo = function (value) {
  5247. var count = 1;
  5248. do {
  5249. count *= 2;
  5250. } while (count < value);
  5251. return count === value;
  5252. };
  5253. /**
  5254. * Find the next highest power of two.
  5255. * @param x Number to start search from.
  5256. * @return Next highest power of two.
  5257. */
  5258. Tools.CeilingPOT = function (x) {
  5259. x--;
  5260. x |= x >> 1;
  5261. x |= x >> 2;
  5262. x |= x >> 4;
  5263. x |= x >> 8;
  5264. x |= x >> 16;
  5265. x++;
  5266. return x;
  5267. };
  5268. /**
  5269. * Find the next lowest power of two.
  5270. * @param x Number to start search from.
  5271. * @return Next lowest power of two.
  5272. */
  5273. Tools.FloorPOT = function (x) {
  5274. x = x | (x >> 1);
  5275. x = x | (x >> 2);
  5276. x = x | (x >> 4);
  5277. x = x | (x >> 8);
  5278. x = x | (x >> 16);
  5279. return x - (x >> 1);
  5280. };
  5281. /**
  5282. * Find the nearest power of two.
  5283. * @param x Number to start search from.
  5284. * @return Next nearest power of two.
  5285. */
  5286. Tools.NearestPOT = function (x) {
  5287. var c = Tools.CeilingPOT(x);
  5288. var f = Tools.FloorPOT(x);
  5289. return (c - x) > (x - f) ? f : c;
  5290. };
  5291. Tools.GetExponentOfTwo = function (value, max, mode) {
  5292. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5293. var pot;
  5294. switch (mode) {
  5295. case BABYLON.Engine.SCALEMODE_FLOOR:
  5296. pot = Tools.FloorPOT(value);
  5297. break;
  5298. case BABYLON.Engine.SCALEMODE_NEAREST:
  5299. pot = Tools.NearestPOT(value);
  5300. break;
  5301. case BABYLON.Engine.SCALEMODE_CEILING:
  5302. pot = Tools.CeilingPOT(value);
  5303. break;
  5304. }
  5305. return Math.min(pot, max);
  5306. };
  5307. Tools.GetFilename = function (path) {
  5308. var index = path.lastIndexOf("/");
  5309. if (index < 0)
  5310. return path;
  5311. return path.substring(index + 1);
  5312. };
  5313. Tools.GetDOMTextContent = function (element) {
  5314. var result = "";
  5315. var child = element.firstChild;
  5316. while (child) {
  5317. if (child.nodeType === 3) {
  5318. result += child.textContent;
  5319. }
  5320. child = child.nextSibling;
  5321. }
  5322. return result;
  5323. };
  5324. Tools.ToDegrees = function (angle) {
  5325. return angle * 180 / Math.PI;
  5326. };
  5327. Tools.ToRadians = function (angle) {
  5328. return angle * Math.PI / 180;
  5329. };
  5330. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5331. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5332. var output = "";
  5333. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5334. var i = 0;
  5335. var bytes = new Uint8Array(buffer);
  5336. while (i < bytes.length) {
  5337. chr1 = bytes[i++];
  5338. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5339. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5340. enc1 = chr1 >> 2;
  5341. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5342. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5343. enc4 = chr3 & 63;
  5344. if (isNaN(chr2)) {
  5345. enc3 = enc4 = 64;
  5346. }
  5347. else if (isNaN(chr3)) {
  5348. enc4 = 64;
  5349. }
  5350. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5351. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5352. }
  5353. return "data:image/png;base64," + output;
  5354. };
  5355. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5356. if (bias === void 0) { bias = null; }
  5357. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5358. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5359. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5360. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5361. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5362. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5363. }
  5364. if (bias) {
  5365. minimum.x -= minimum.x * bias.x + bias.y;
  5366. minimum.y -= minimum.y * bias.x + bias.y;
  5367. minimum.z -= minimum.z * bias.x + bias.y;
  5368. maximum.x += maximum.x * bias.x + bias.y;
  5369. maximum.y += maximum.y * bias.x + bias.y;
  5370. maximum.z += maximum.z * bias.x + bias.y;
  5371. }
  5372. return {
  5373. minimum: minimum,
  5374. maximum: maximum
  5375. };
  5376. };
  5377. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5378. if (bias === void 0) { bias = null; }
  5379. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5380. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5381. if (!stride) {
  5382. stride = 3;
  5383. }
  5384. for (var index = start; index < start + count; index++) {
  5385. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5386. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5387. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5388. }
  5389. if (bias) {
  5390. minimum.x -= minimum.x * bias.x + bias.y;
  5391. minimum.y -= minimum.y * bias.x + bias.y;
  5392. minimum.z -= minimum.z * bias.x + bias.y;
  5393. maximum.x += maximum.x * bias.x + bias.y;
  5394. maximum.y += maximum.y * bias.x + bias.y;
  5395. maximum.z += maximum.z * bias.x + bias.y;
  5396. }
  5397. return {
  5398. minimum: minimum,
  5399. maximum: maximum
  5400. };
  5401. };
  5402. Tools.Vector2ArrayFeeder = function (array) {
  5403. return function (index) {
  5404. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5405. var length = isFloatArray ? array.length / 2 : array.length;
  5406. if (index >= length) {
  5407. return null;
  5408. }
  5409. if (isFloatArray) {
  5410. var fa = array;
  5411. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5412. }
  5413. var a = array;
  5414. return a[index];
  5415. };
  5416. };
  5417. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5418. if (bias === void 0) { bias = null; }
  5419. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5420. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5421. var i = 0;
  5422. var cur = feeder(i++);
  5423. while (cur) {
  5424. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5425. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5426. cur = feeder(i++);
  5427. }
  5428. if (bias) {
  5429. minimum.x -= minimum.x * bias.x + bias.y;
  5430. minimum.y -= minimum.y * bias.x + bias.y;
  5431. maximum.x += maximum.x * bias.x + bias.y;
  5432. maximum.y += maximum.y * bias.x + bias.y;
  5433. }
  5434. return {
  5435. minimum: minimum,
  5436. maximum: maximum
  5437. };
  5438. };
  5439. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5440. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5441. return undefined;
  5442. return Array.isArray(obj) ? obj : [obj];
  5443. };
  5444. // Misc.
  5445. Tools.GetPointerPrefix = function () {
  5446. var eventPrefix = "pointer";
  5447. // Check if pointer events are supported
  5448. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5449. eventPrefix = "mouse";
  5450. }
  5451. return eventPrefix;
  5452. };
  5453. /**
  5454. * @param func - the function to be called
  5455. * @param requester - the object that will request the next frame. Falls back to window.
  5456. */
  5457. Tools.QueueNewFrame = function (func, requester) {
  5458. if (requester === void 0) { requester = window; }
  5459. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5460. /*if(requester.isPresenting) {
  5461. return;
  5462. } else*/ if (requester.requestAnimationFrame)
  5463. requester.requestAnimationFrame(func);
  5464. else if (requester.msRequestAnimationFrame)
  5465. requester.msRequestAnimationFrame(func);
  5466. else if (requester.webkitRequestAnimationFrame)
  5467. requester.webkitRequestAnimationFrame(func);
  5468. else if (requester.mozRequestAnimationFrame)
  5469. requester.mozRequestAnimationFrame(func);
  5470. else if (requester.oRequestAnimationFrame)
  5471. requester.oRequestAnimationFrame(func);
  5472. else {
  5473. window.setTimeout(func, 16);
  5474. }
  5475. };
  5476. Tools.RequestFullscreen = function (element) {
  5477. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5478. if (!requestFunction)
  5479. return;
  5480. requestFunction.call(element);
  5481. };
  5482. Tools.ExitFullscreen = function () {
  5483. if (document.exitFullscreen) {
  5484. document.exitFullscreen();
  5485. }
  5486. else if (document.mozCancelFullScreen) {
  5487. document.mozCancelFullScreen();
  5488. }
  5489. else if (document.webkitCancelFullScreen) {
  5490. document.webkitCancelFullScreen();
  5491. }
  5492. else if (document.msCancelFullScreen) {
  5493. document.msCancelFullScreen();
  5494. }
  5495. };
  5496. Tools.SetCorsBehavior = function (url, img) {
  5497. if (Tools.CorsBehavior) {
  5498. switch (typeof (Tools.CorsBehavior)) {
  5499. case "function":
  5500. var result = Tools.CorsBehavior(url);
  5501. if (result) {
  5502. img.crossOrigin = result;
  5503. }
  5504. break;
  5505. case "string":
  5506. default:
  5507. img.crossOrigin = Tools.CorsBehavior;
  5508. break;
  5509. }
  5510. }
  5511. };
  5512. // External files
  5513. Tools.CleanUrl = function (url) {
  5514. url = url.replace(/#/mg, "%23");
  5515. return url;
  5516. };
  5517. Tools.LoadImage = function (url, onload, onerror, database) {
  5518. if (url instanceof ArrayBuffer) {
  5519. url = Tools.EncodeArrayBufferTobase64(url);
  5520. }
  5521. url = Tools.CleanUrl(url);
  5522. var img = new Image();
  5523. if (url.substr(0, 5) !== "data:") {
  5524. Tools.SetCorsBehavior(url, img);
  5525. }
  5526. img.onload = function () {
  5527. onload(img);
  5528. };
  5529. img.onerror = function (err) {
  5530. Tools.Error("Error while trying to load image: " + url);
  5531. if (Tools.UseFallbackTexture) {
  5532. img.src = Tools.fallbackTexture;
  5533. onload(img);
  5534. }
  5535. else {
  5536. onerror();
  5537. }
  5538. };
  5539. var noIndexedDB = function () {
  5540. img.src = url;
  5541. };
  5542. var loadFromIndexedDB = function () {
  5543. database.loadImageFromDB(url, img);
  5544. };
  5545. //ANY database to do!
  5546. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5547. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5548. }
  5549. else {
  5550. if (url.indexOf("file:") !== 0) {
  5551. noIndexedDB();
  5552. }
  5553. else {
  5554. var textureName = url.substring(5).toLowerCase();
  5555. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5556. try {
  5557. var blobURL;
  5558. try {
  5559. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5560. }
  5561. catch (ex) {
  5562. // Chrome doesn't support oneTimeOnly parameter
  5563. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5564. }
  5565. img.src = blobURL;
  5566. }
  5567. catch (e) {
  5568. img.src = null;
  5569. }
  5570. }
  5571. else {
  5572. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5573. img.src = Tools.fallbackTexture;
  5574. }
  5575. }
  5576. }
  5577. return img;
  5578. };
  5579. //ANY
  5580. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5581. url = Tools.CleanUrl(url);
  5582. var noIndexedDB = function () {
  5583. var request = new XMLHttpRequest();
  5584. var loadUrl = Tools.BaseUrl + url;
  5585. request.open('GET', loadUrl, true);
  5586. if (useArrayBuffer) {
  5587. request.responseType = "arraybuffer";
  5588. }
  5589. request.onprogress = progressCallBack;
  5590. request.onreadystatechange = function () {
  5591. // In case of undefined state in some browsers.
  5592. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5593. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5594. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5595. callback(!useArrayBuffer ? request.responseText : request.response);
  5596. }
  5597. else {
  5598. if (onError) {
  5599. onError(request);
  5600. }
  5601. else {
  5602. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5603. }
  5604. }
  5605. }
  5606. };
  5607. request.send(null);
  5608. };
  5609. var loadFromIndexedDB = function () {
  5610. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5611. };
  5612. if (url.indexOf("file:") !== -1) {
  5613. var fileName = url.substring(5).toLowerCase();
  5614. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5615. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5616. }
  5617. else {
  5618. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5619. }
  5620. }
  5621. else {
  5622. // Caching all files
  5623. if (database && database.enableSceneOffline) {
  5624. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5625. }
  5626. else {
  5627. noIndexedDB();
  5628. }
  5629. }
  5630. };
  5631. /**
  5632. * Load a script (identified by an url). When the url returns, the
  5633. * content of this file is added into a new script element, attached to the DOM (body element)
  5634. */
  5635. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5636. var head = document.getElementsByTagName('head')[0];
  5637. var script = document.createElement('script');
  5638. script.type = 'text/javascript';
  5639. script.src = scriptUrl;
  5640. var self = this;
  5641. script.onload = function () {
  5642. if (onSuccess) {
  5643. onSuccess();
  5644. }
  5645. };
  5646. script.onerror = function () {
  5647. if (onError) {
  5648. onError();
  5649. }
  5650. };
  5651. head.appendChild(script);
  5652. };
  5653. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5654. var reader = new FileReader();
  5655. reader.onload = function (e) {
  5656. //target doesn't have result from ts 1.3
  5657. callback(e.target['result']);
  5658. };
  5659. reader.onprogress = progressCallback;
  5660. reader.readAsDataURL(fileToLoad);
  5661. };
  5662. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5663. var reader = new FileReader();
  5664. reader.onerror = function (e) {
  5665. Tools.Log("Error while reading file: " + fileToLoad.name);
  5666. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5667. };
  5668. reader.onload = function (e) {
  5669. //target doesn't have result from ts 1.3
  5670. callback(e.target['result']);
  5671. };
  5672. reader.onprogress = progressCallBack;
  5673. if (!useArrayBuffer) {
  5674. // Asynchronous read
  5675. reader.readAsText(fileToLoad);
  5676. }
  5677. else {
  5678. reader.readAsArrayBuffer(fileToLoad);
  5679. }
  5680. };
  5681. //returns a downloadable url to a file content.
  5682. Tools.FileAsURL = function (content) {
  5683. var fileBlob = new Blob([content]);
  5684. var url = window.URL || window.webkitURL;
  5685. var link = url.createObjectURL(fileBlob);
  5686. return link;
  5687. };
  5688. // Misc.
  5689. Tools.Format = function (value, decimals) {
  5690. if (decimals === void 0) { decimals = 2; }
  5691. return value.toFixed(decimals);
  5692. };
  5693. Tools.CheckExtends = function (v, min, max) {
  5694. if (v.x < min.x)
  5695. min.x = v.x;
  5696. if (v.y < min.y)
  5697. min.y = v.y;
  5698. if (v.z < min.z)
  5699. min.z = v.z;
  5700. if (v.x > max.x)
  5701. max.x = v.x;
  5702. if (v.y > max.y)
  5703. max.y = v.y;
  5704. if (v.z > max.z)
  5705. max.z = v.z;
  5706. };
  5707. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5708. for (var prop in source) {
  5709. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5710. continue;
  5711. }
  5712. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5713. continue;
  5714. }
  5715. var sourceValue = source[prop];
  5716. var typeOfSourceValue = typeof sourceValue;
  5717. if (typeOfSourceValue === "function") {
  5718. continue;
  5719. }
  5720. if (typeOfSourceValue === "object") {
  5721. if (sourceValue instanceof Array) {
  5722. destination[prop] = [];
  5723. if (sourceValue.length > 0) {
  5724. if (typeof sourceValue[0] == "object") {
  5725. for (var index = 0; index < sourceValue.length; index++) {
  5726. var clonedValue = cloneValue(sourceValue[index], destination);
  5727. if (destination[prop].indexOf(clonedValue) === -1) {
  5728. destination[prop].push(clonedValue);
  5729. }
  5730. }
  5731. }
  5732. else {
  5733. destination[prop] = sourceValue.slice(0);
  5734. }
  5735. }
  5736. }
  5737. else {
  5738. destination[prop] = cloneValue(sourceValue, destination);
  5739. }
  5740. }
  5741. else {
  5742. destination[prop] = sourceValue;
  5743. }
  5744. }
  5745. };
  5746. Tools.IsEmpty = function (obj) {
  5747. for (var i in obj) {
  5748. return false;
  5749. }
  5750. return true;
  5751. };
  5752. Tools.RegisterTopRootEvents = function (events) {
  5753. for (var index = 0; index < events.length; index++) {
  5754. var event = events[index];
  5755. window.addEventListener(event.name, event.handler, false);
  5756. try {
  5757. if (window.parent) {
  5758. window.parent.addEventListener(event.name, event.handler, false);
  5759. }
  5760. }
  5761. catch (e) {
  5762. // Silently fails...
  5763. }
  5764. }
  5765. };
  5766. Tools.UnregisterTopRootEvents = function (events) {
  5767. for (var index = 0; index < events.length; index++) {
  5768. var event = events[index];
  5769. window.removeEventListener(event.name, event.handler);
  5770. try {
  5771. if (window.parent) {
  5772. window.parent.removeEventListener(event.name, event.handler);
  5773. }
  5774. }
  5775. catch (e) {
  5776. // Silently fails...
  5777. }
  5778. }
  5779. };
  5780. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5781. if (mimeType === void 0) { mimeType = "image/png"; }
  5782. // Read the contents of the framebuffer
  5783. var numberOfChannelsByLine = width * 4;
  5784. var halfHeight = height / 2;
  5785. //Reading datas from WebGL
  5786. var data = engine.readPixels(0, 0, width, height);
  5787. //To flip image on Y axis.
  5788. for (var i = 0; i < halfHeight; i++) {
  5789. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5790. var currentCell = j + i * numberOfChannelsByLine;
  5791. var targetLine = height - i - 1;
  5792. var targetCell = j + targetLine * numberOfChannelsByLine;
  5793. var temp = data[currentCell];
  5794. data[currentCell] = data[targetCell];
  5795. data[targetCell] = temp;
  5796. }
  5797. }
  5798. // Create a 2D canvas to store the result
  5799. if (!screenshotCanvas) {
  5800. screenshotCanvas = document.createElement('canvas');
  5801. }
  5802. screenshotCanvas.width = width;
  5803. screenshotCanvas.height = height;
  5804. var context = screenshotCanvas.getContext('2d');
  5805. // Copy the pixels to a 2D canvas
  5806. var imageData = context.createImageData(width, height);
  5807. var castData = (imageData.data);
  5808. castData.set(data);
  5809. context.putImageData(imageData, 0, 0);
  5810. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5811. };
  5812. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5813. if (mimeType === void 0) { mimeType = "image/png"; }
  5814. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5815. if (successCallback) {
  5816. successCallback(base64Image);
  5817. }
  5818. else {
  5819. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5820. if (("download" in document.createElement("a"))) {
  5821. var a = window.document.createElement("a");
  5822. a.href = base64Image;
  5823. var date = new Date();
  5824. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5825. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5826. window.document.body.appendChild(a);
  5827. a.addEventListener("click", function () {
  5828. a.parentElement.removeChild(a);
  5829. });
  5830. a.click();
  5831. //Or opening a new tab with the image if it is not possible to automatically start download.
  5832. }
  5833. else {
  5834. var newWindow = window.open("");
  5835. var img = newWindow.document.createElement("img");
  5836. img.src = base64Image;
  5837. newWindow.document.body.appendChild(img);
  5838. }
  5839. }
  5840. };
  5841. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5842. if (mimeType === void 0) { mimeType = "image/png"; }
  5843. var width;
  5844. var height;
  5845. // If a precision value is specified
  5846. if (size.precision) {
  5847. width = Math.round(engine.getRenderWidth() * size.precision);
  5848. height = Math.round(width / engine.getAspectRatio(camera));
  5849. }
  5850. else if (size.width && size.height) {
  5851. width = size.width;
  5852. height = size.height;
  5853. }
  5854. else if (size.width && !size.height) {
  5855. width = size.width;
  5856. height = Math.round(width / engine.getAspectRatio(camera));
  5857. }
  5858. else if (size.height && !size.width) {
  5859. height = size.height;
  5860. width = Math.round(height * engine.getAspectRatio(camera));
  5861. }
  5862. else if (!isNaN(size)) {
  5863. height = size;
  5864. width = size;
  5865. }
  5866. else {
  5867. Tools.Error("Invalid 'size' parameter !");
  5868. return;
  5869. }
  5870. if (!screenshotCanvas) {
  5871. screenshotCanvas = document.createElement('canvas');
  5872. }
  5873. screenshotCanvas.width = width;
  5874. screenshotCanvas.height = height;
  5875. var renderContext = screenshotCanvas.getContext("2d");
  5876. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5877. var newWidth = width;
  5878. var newHeight = newWidth / ratio;
  5879. if (newHeight > height) {
  5880. newHeight = height;
  5881. newWidth = newHeight * ratio;
  5882. }
  5883. var offsetX = Math.max(0, width - newWidth) / 2;
  5884. var offsetY = Math.max(0, height - newHeight) / 2;
  5885. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5886. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5887. };
  5888. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5889. if (mimeType === void 0) { mimeType = "image/png"; }
  5890. if (samples === void 0) { samples = 1; }
  5891. var width;
  5892. var height;
  5893. //If a precision value is specified
  5894. if (size.precision) {
  5895. width = Math.round(engine.getRenderWidth() * size.precision);
  5896. height = Math.round(width / engine.getAspectRatio(camera));
  5897. size = { width: width, height: height };
  5898. }
  5899. else if (size.width && size.height) {
  5900. width = size.width;
  5901. height = size.height;
  5902. }
  5903. else if (size.width && !size.height) {
  5904. width = size.width;
  5905. height = Math.round(width / engine.getAspectRatio(camera));
  5906. size = { width: width, height: height };
  5907. }
  5908. else if (size.height && !size.width) {
  5909. height = size.height;
  5910. width = Math.round(height * engine.getAspectRatio(camera));
  5911. size = { width: width, height: height };
  5912. }
  5913. else if (!isNaN(size)) {
  5914. height = size;
  5915. width = size;
  5916. }
  5917. else {
  5918. Tools.Error("Invalid 'size' parameter !");
  5919. return;
  5920. }
  5921. var scene = camera.getScene();
  5922. var previousCamera = null;
  5923. if (scene.activeCamera !== camera) {
  5924. previousCamera = scene.activeCamera;
  5925. scene.activeCamera = camera;
  5926. }
  5927. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5928. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5929. texture.renderList = scene.meshes;
  5930. texture.samples = samples;
  5931. texture.onAfterRenderObservable.add(function () {
  5932. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5933. });
  5934. scene.incrementRenderId();
  5935. scene.resetCachedMaterial();
  5936. texture.render(true);
  5937. texture.dispose();
  5938. if (previousCamera) {
  5939. scene.activeCamera = previousCamera;
  5940. }
  5941. camera.getProjectionMatrix(true); // Force cache refresh;
  5942. };
  5943. // XHR response validator for local file scenario
  5944. Tools.ValidateXHRData = function (xhr, dataType) {
  5945. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5946. if (dataType === void 0) { dataType = 7; }
  5947. try {
  5948. if (dataType & 1) {
  5949. if (xhr.responseText && xhr.responseText.length > 0) {
  5950. return true;
  5951. }
  5952. else if (dataType === 1) {
  5953. return false;
  5954. }
  5955. }
  5956. if (dataType & 2) {
  5957. // Check header width and height since there is no "TGA" magic number
  5958. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5959. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5960. return true;
  5961. }
  5962. else if (dataType === 2) {
  5963. return false;
  5964. }
  5965. }
  5966. if (dataType & 4) {
  5967. // Check for the "DDS" magic number
  5968. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5969. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5970. return true;
  5971. }
  5972. else {
  5973. return false;
  5974. }
  5975. }
  5976. }
  5977. catch (e) {
  5978. // Global protection
  5979. }
  5980. return false;
  5981. };
  5982. /**
  5983. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5984. * Be aware Math.random() could cause collisions, but:
  5985. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5986. */
  5987. Tools.RandomId = function () {
  5988. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5989. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5990. return v.toString(16);
  5991. });
  5992. };
  5993. Object.defineProperty(Tools, "NoneLogLevel", {
  5994. get: function () {
  5995. return Tools._NoneLogLevel;
  5996. },
  5997. enumerable: true,
  5998. configurable: true
  5999. });
  6000. Object.defineProperty(Tools, "MessageLogLevel", {
  6001. get: function () {
  6002. return Tools._MessageLogLevel;
  6003. },
  6004. enumerable: true,
  6005. configurable: true
  6006. });
  6007. Object.defineProperty(Tools, "WarningLogLevel", {
  6008. get: function () {
  6009. return Tools._WarningLogLevel;
  6010. },
  6011. enumerable: true,
  6012. configurable: true
  6013. });
  6014. Object.defineProperty(Tools, "ErrorLogLevel", {
  6015. get: function () {
  6016. return Tools._ErrorLogLevel;
  6017. },
  6018. enumerable: true,
  6019. configurable: true
  6020. });
  6021. Object.defineProperty(Tools, "AllLogLevel", {
  6022. get: function () {
  6023. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6024. },
  6025. enumerable: true,
  6026. configurable: true
  6027. });
  6028. Tools._AddLogEntry = function (entry) {
  6029. Tools._LogCache = entry + Tools._LogCache;
  6030. if (Tools.OnNewCacheEntry) {
  6031. Tools.OnNewCacheEntry(entry);
  6032. }
  6033. };
  6034. Tools._FormatMessage = function (message) {
  6035. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6036. var date = new Date();
  6037. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6038. };
  6039. Tools._LogDisabled = function (message) {
  6040. // nothing to do
  6041. };
  6042. Tools._LogEnabled = function (message) {
  6043. var formattedMessage = Tools._FormatMessage(message);
  6044. console.log("BJS - " + formattedMessage);
  6045. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6046. Tools._AddLogEntry(entry);
  6047. };
  6048. Tools._WarnDisabled = function (message) {
  6049. // nothing to do
  6050. };
  6051. Tools._WarnEnabled = function (message) {
  6052. var formattedMessage = Tools._FormatMessage(message);
  6053. console.warn("BJS - " + formattedMessage);
  6054. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6055. Tools._AddLogEntry(entry);
  6056. };
  6057. Tools._ErrorDisabled = function (message) {
  6058. // nothing to do
  6059. };
  6060. Tools._ErrorEnabled = function (message) {
  6061. Tools.errorsCount++;
  6062. var formattedMessage = Tools._FormatMessage(message);
  6063. console.error("BJS - " + formattedMessage);
  6064. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6065. Tools._AddLogEntry(entry);
  6066. };
  6067. Object.defineProperty(Tools, "LogCache", {
  6068. get: function () {
  6069. return Tools._LogCache;
  6070. },
  6071. enumerable: true,
  6072. configurable: true
  6073. });
  6074. Tools.ClearLogCache = function () {
  6075. Tools._LogCache = "";
  6076. Tools.errorsCount = 0;
  6077. };
  6078. Object.defineProperty(Tools, "LogLevels", {
  6079. set: function (level) {
  6080. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6081. Tools.Log = Tools._LogEnabled;
  6082. }
  6083. else {
  6084. Tools.Log = Tools._LogDisabled;
  6085. }
  6086. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6087. Tools.Warn = Tools._WarnEnabled;
  6088. }
  6089. else {
  6090. Tools.Warn = Tools._WarnDisabled;
  6091. }
  6092. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6093. Tools.Error = Tools._ErrorEnabled;
  6094. }
  6095. else {
  6096. Tools.Error = Tools._ErrorDisabled;
  6097. }
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6103. get: function () {
  6104. return Tools._PerformanceNoneLogLevel;
  6105. },
  6106. enumerable: true,
  6107. configurable: true
  6108. });
  6109. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6110. get: function () {
  6111. return Tools._PerformanceUserMarkLogLevel;
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6117. get: function () {
  6118. return Tools._PerformanceConsoleLogLevel;
  6119. },
  6120. enumerable: true,
  6121. configurable: true
  6122. });
  6123. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6124. set: function (level) {
  6125. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6126. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6127. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6128. return;
  6129. }
  6130. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6131. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6132. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6133. return;
  6134. }
  6135. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6136. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6137. },
  6138. enumerable: true,
  6139. configurable: true
  6140. });
  6141. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6142. };
  6143. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6144. };
  6145. Tools._StartUserMark = function (counterName, condition) {
  6146. if (condition === void 0) { condition = true; }
  6147. if (!condition || !Tools._performance.mark) {
  6148. return;
  6149. }
  6150. Tools._performance.mark(counterName + "-Begin");
  6151. };
  6152. Tools._EndUserMark = function (counterName, condition) {
  6153. if (condition === void 0) { condition = true; }
  6154. if (!condition || !Tools._performance.mark) {
  6155. return;
  6156. }
  6157. Tools._performance.mark(counterName + "-End");
  6158. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6159. };
  6160. Tools._StartPerformanceConsole = function (counterName, condition) {
  6161. if (condition === void 0) { condition = true; }
  6162. if (!condition) {
  6163. return;
  6164. }
  6165. Tools._StartUserMark(counterName, condition);
  6166. if (console.time) {
  6167. console.time(counterName);
  6168. }
  6169. };
  6170. Tools._EndPerformanceConsole = function (counterName, condition) {
  6171. if (condition === void 0) { condition = true; }
  6172. if (!condition) {
  6173. return;
  6174. }
  6175. Tools._EndUserMark(counterName, condition);
  6176. if (console.time) {
  6177. console.timeEnd(counterName);
  6178. }
  6179. };
  6180. Object.defineProperty(Tools, "Now", {
  6181. get: function () {
  6182. if (window.performance && window.performance.now) {
  6183. return window.performance.now();
  6184. }
  6185. return new Date().getTime();
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. /**
  6191. * This method will return the name of the class used to create the instance of the given object.
  6192. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6193. * @param object the object to get the class name from
  6194. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6195. */
  6196. Tools.getClassName = function (object, isType) {
  6197. if (isType === void 0) { isType = false; }
  6198. var name = null;
  6199. if (!isType && object.getClassName) {
  6200. name = object.getClassName();
  6201. }
  6202. else {
  6203. if (object instanceof Object) {
  6204. var classObj = isType ? object : Object.getPrototypeOf(object);
  6205. name = classObj.constructor["__bjsclassName__"];
  6206. }
  6207. if (!name) {
  6208. name = typeof object;
  6209. }
  6210. }
  6211. return name;
  6212. };
  6213. Tools.first = function (array, predicate) {
  6214. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6215. var el = array_1[_i];
  6216. if (predicate(el)) {
  6217. return el;
  6218. }
  6219. }
  6220. };
  6221. /**
  6222. * This method will return the name of the full name of the class, including its owning module (if any).
  6223. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6224. * @param object the object to get the class name from
  6225. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6226. */
  6227. Tools.getFullClassName = function (object, isType) {
  6228. if (isType === void 0) { isType = false; }
  6229. var className = null;
  6230. var moduleName = null;
  6231. if (!isType && object.getClassName) {
  6232. className = object.getClassName();
  6233. }
  6234. else {
  6235. if (object instanceof Object) {
  6236. var classObj = isType ? object : Object.getPrototypeOf(object);
  6237. className = classObj.constructor["__bjsclassName__"];
  6238. moduleName = classObj.constructor["__bjsmoduleName__"];
  6239. }
  6240. if (!className) {
  6241. className = typeof object;
  6242. }
  6243. }
  6244. if (!className) {
  6245. return null;
  6246. }
  6247. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6248. };
  6249. /**
  6250. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6251. * @param array
  6252. */
  6253. Tools.arrayOrStringFeeder = function (array) {
  6254. return function (index) {
  6255. if (index >= array.length) {
  6256. return null;
  6257. }
  6258. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6259. if (val && val.getHashCode) {
  6260. val = val.getHashCode();
  6261. }
  6262. if (typeof val === "string") {
  6263. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6264. }
  6265. return val;
  6266. };
  6267. };
  6268. /**
  6269. * Compute the hashCode of a stream of number
  6270. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6271. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6272. * @return the hash code computed
  6273. */
  6274. Tools.hashCodeFromStream = function (feeder) {
  6275. // Based from here: http://stackoverflow.com/a/7616484/802124
  6276. var hash = 0;
  6277. var index = 0;
  6278. var chr = feeder(index++);
  6279. while (chr != null) {
  6280. hash = ((hash << 5) - hash) + chr;
  6281. hash |= 0; // Convert to 32bit integer
  6282. chr = feeder(index++);
  6283. }
  6284. return hash;
  6285. };
  6286. return Tools;
  6287. }());
  6288. Tools.BaseUrl = "";
  6289. Tools.CorsBehavior = "anonymous";
  6290. Tools.UseFallbackTexture = true;
  6291. // Used in case of a texture loading problem
  6292. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6293. // Logs
  6294. Tools._NoneLogLevel = 0;
  6295. Tools._MessageLogLevel = 1;
  6296. Tools._WarningLogLevel = 2;
  6297. Tools._ErrorLogLevel = 4;
  6298. Tools._LogCache = "";
  6299. Tools.errorsCount = 0;
  6300. Tools.Log = Tools._LogEnabled;
  6301. Tools.Warn = Tools._WarnEnabled;
  6302. Tools.Error = Tools._ErrorEnabled;
  6303. // Performances
  6304. Tools._PerformanceNoneLogLevel = 0;
  6305. Tools._PerformanceUserMarkLogLevel = 1;
  6306. Tools._PerformanceConsoleLogLevel = 2;
  6307. Tools._performance = window.performance;
  6308. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6309. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6310. BABYLON.Tools = Tools;
  6311. /**
  6312. * This class is used to track a performance counter which is number based.
  6313. * The user has access to many properties which give statistics of different nature
  6314. *
  6315. * The implementer can track two kinds of Performance Counter: time and count
  6316. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6317. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6318. */
  6319. var PerfCounter = (function () {
  6320. function PerfCounter() {
  6321. this._startMonitoringTime = 0;
  6322. this._min = 0;
  6323. this._max = 0;
  6324. this._average = 0;
  6325. this._lastSecAverage = 0;
  6326. this._current = 0;
  6327. this._totalValueCount = 0;
  6328. this._totalAccumulated = 0;
  6329. this._lastSecAccumulated = 0;
  6330. this._lastSecTime = 0;
  6331. this._lastSecValueCount = 0;
  6332. }
  6333. Object.defineProperty(PerfCounter.prototype, "min", {
  6334. /**
  6335. * Returns the smallest value ever
  6336. */
  6337. get: function () {
  6338. return this._min;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "max", {
  6344. /**
  6345. * Returns the biggest value ever
  6346. */
  6347. get: function () {
  6348. return this._max;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "average", {
  6354. /**
  6355. * Returns the average value since the performance counter is running
  6356. */
  6357. get: function () {
  6358. return this._average;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6364. /**
  6365. * Returns the average value of the last second the counter was monitored
  6366. */
  6367. get: function () {
  6368. return this._lastSecAverage;
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. Object.defineProperty(PerfCounter.prototype, "current", {
  6374. /**
  6375. * Returns the current value
  6376. */
  6377. get: function () {
  6378. return this._current;
  6379. },
  6380. enumerable: true,
  6381. configurable: true
  6382. });
  6383. Object.defineProperty(PerfCounter.prototype, "total", {
  6384. get: function () {
  6385. return this._totalAccumulated;
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. /**
  6391. * Call this method to start monitoring a new frame.
  6392. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6393. */
  6394. PerfCounter.prototype.fetchNewFrame = function () {
  6395. this._totalValueCount++;
  6396. this._current = 0;
  6397. this._lastSecValueCount++;
  6398. };
  6399. /**
  6400. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6401. * @param newCount the count value to add to the monitored count
  6402. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6403. */
  6404. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6405. if (!PerfCounter.Enabled) {
  6406. return;
  6407. }
  6408. this._current += newCount;
  6409. if (fetchResult) {
  6410. this._fetchResult();
  6411. }
  6412. };
  6413. /**
  6414. * Start monitoring this performance counter
  6415. */
  6416. PerfCounter.prototype.beginMonitoring = function () {
  6417. if (!PerfCounter.Enabled) {
  6418. return;
  6419. }
  6420. this._startMonitoringTime = Tools.Now;
  6421. };
  6422. /**
  6423. * Compute the time lapsed since the previous beginMonitoring() call.
  6424. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6425. */
  6426. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6427. if (newFrame === void 0) { newFrame = true; }
  6428. if (!PerfCounter.Enabled) {
  6429. return;
  6430. }
  6431. if (newFrame) {
  6432. this.fetchNewFrame();
  6433. }
  6434. var currentTime = Tools.Now;
  6435. this._current = currentTime - this._startMonitoringTime;
  6436. if (newFrame) {
  6437. this._fetchResult();
  6438. }
  6439. };
  6440. PerfCounter.prototype._fetchResult = function () {
  6441. this._totalAccumulated += this._current;
  6442. this._lastSecAccumulated += this._current;
  6443. // Min/Max update
  6444. this._min = Math.min(this._min, this._current);
  6445. this._max = Math.max(this._max, this._current);
  6446. this._average = this._totalAccumulated / this._totalValueCount;
  6447. // Reset last sec?
  6448. var now = Tools.Now;
  6449. if ((now - this._lastSecTime) > 1000) {
  6450. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6451. this._lastSecTime = now;
  6452. this._lastSecAccumulated = 0;
  6453. this._lastSecValueCount = 0;
  6454. }
  6455. };
  6456. return PerfCounter;
  6457. }());
  6458. PerfCounter.Enabled = true;
  6459. BABYLON.PerfCounter = PerfCounter;
  6460. /**
  6461. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6462. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6463. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6464. * @param name The name of the class, case should be preserved
  6465. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6466. */
  6467. function className(name, module) {
  6468. return function (target) {
  6469. target["__bjsclassName__"] = name;
  6470. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6471. };
  6472. }
  6473. BABYLON.className = className;
  6474. /**
  6475. * An implementation of a loop for asynchronous functions.
  6476. */
  6477. var AsyncLoop = (function () {
  6478. /**
  6479. * Constroctor.
  6480. * @param iterations the number of iterations.
  6481. * @param _fn the function to run each iteration
  6482. * @param _successCallback the callback that will be called upon succesful execution
  6483. * @param offset starting offset.
  6484. */
  6485. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6486. if (offset === void 0) { offset = 0; }
  6487. this.iterations = iterations;
  6488. this._fn = _fn;
  6489. this._successCallback = _successCallback;
  6490. this.index = offset - 1;
  6491. this._done = false;
  6492. }
  6493. /**
  6494. * Execute the next iteration. Must be called after the last iteration was finished.
  6495. */
  6496. AsyncLoop.prototype.executeNext = function () {
  6497. if (!this._done) {
  6498. if (this.index + 1 < this.iterations) {
  6499. ++this.index;
  6500. this._fn(this);
  6501. }
  6502. else {
  6503. this.breakLoop();
  6504. }
  6505. }
  6506. };
  6507. /**
  6508. * Break the loop and run the success callback.
  6509. */
  6510. AsyncLoop.prototype.breakLoop = function () {
  6511. this._done = true;
  6512. this._successCallback();
  6513. };
  6514. /**
  6515. * Helper function
  6516. */
  6517. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6518. if (offset === void 0) { offset = 0; }
  6519. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6520. loop.executeNext();
  6521. return loop;
  6522. };
  6523. /**
  6524. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6525. * @param iterations total number of iterations
  6526. * @param syncedIterations number of synchronous iterations in each async iteration.
  6527. * @param fn the function to call each iteration.
  6528. * @param callback a success call back that will be called when iterating stops.
  6529. * @param breakFunction a break condition (optional)
  6530. * @param timeout timeout settings for the setTimeout function. default - 0.
  6531. * @constructor
  6532. */
  6533. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6534. if (timeout === void 0) { timeout = 0; }
  6535. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6536. if (breakFunction && breakFunction())
  6537. loop.breakLoop();
  6538. else {
  6539. setTimeout(function () {
  6540. for (var i = 0; i < syncedIterations; ++i) {
  6541. var iteration = (loop.index * syncedIterations) + i;
  6542. if (iteration >= iterations)
  6543. break;
  6544. fn(iteration);
  6545. if (breakFunction && breakFunction()) {
  6546. loop.breakLoop();
  6547. break;
  6548. }
  6549. }
  6550. loop.executeNext();
  6551. }, timeout);
  6552. }
  6553. }, callback);
  6554. };
  6555. return AsyncLoop;
  6556. }());
  6557. BABYLON.AsyncLoop = AsyncLoop;
  6558. })(BABYLON || (BABYLON = {}));
  6559. //# sourceMappingURL=babylon.tools.js.map
  6560. var BABYLON;
  6561. (function (BABYLON) {
  6562. var Internals;
  6563. (function (Internals) {
  6564. var _AlphaState = (function () {
  6565. /**
  6566. * Initializes the state.
  6567. */
  6568. function _AlphaState() {
  6569. this._isAlphaBlendDirty = false;
  6570. this._isBlendFunctionParametersDirty = false;
  6571. this._isBlendEquationParametersDirty = false;
  6572. this._isBlendConstantsDirty = false;
  6573. this._alphaBlend = false;
  6574. this._blendFunctionParameters = new Array(4);
  6575. this._blendEquationParameters = new Array(2);
  6576. this._blendConstants = new Array(4);
  6577. this.reset();
  6578. }
  6579. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6580. get: function () {
  6581. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6587. get: function () {
  6588. return this._alphaBlend;
  6589. },
  6590. set: function (value) {
  6591. if (this._alphaBlend === value) {
  6592. return;
  6593. }
  6594. this._alphaBlend = value;
  6595. this._isAlphaBlendDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6601. if (this._blendConstants[0] === r &&
  6602. this._blendConstants[1] === g &&
  6603. this._blendConstants[2] === b &&
  6604. this._blendConstants[3] === a) {
  6605. return;
  6606. }
  6607. this._blendConstants[0] = r;
  6608. this._blendConstants[1] = g;
  6609. this._blendConstants[2] = b;
  6610. this._blendConstants[3] = a;
  6611. this._isBlendConstantsDirty = true;
  6612. };
  6613. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6614. if (this._blendFunctionParameters[0] === value0 &&
  6615. this._blendFunctionParameters[1] === value1 &&
  6616. this._blendFunctionParameters[2] === value2 &&
  6617. this._blendFunctionParameters[3] === value3) {
  6618. return;
  6619. }
  6620. this._blendFunctionParameters[0] = value0;
  6621. this._blendFunctionParameters[1] = value1;
  6622. this._blendFunctionParameters[2] = value2;
  6623. this._blendFunctionParameters[3] = value3;
  6624. this._isBlendFunctionParametersDirty = true;
  6625. };
  6626. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6627. if (this._blendEquationParameters[0] === rgb &&
  6628. this._blendEquationParameters[1] === alpha) {
  6629. return;
  6630. }
  6631. this._blendEquationParameters[0] = rgb;
  6632. this._blendEquationParameters[1] = alpha;
  6633. this._isBlendEquationParametersDirty = true;
  6634. };
  6635. _AlphaState.prototype.reset = function () {
  6636. this._alphaBlend = false;
  6637. this._blendFunctionParameters[0] = null;
  6638. this._blendFunctionParameters[1] = null;
  6639. this._blendFunctionParameters[2] = null;
  6640. this._blendFunctionParameters[3] = null;
  6641. this._blendEquationParameters[0] = null;
  6642. this._blendEquationParameters[1] = null;
  6643. this._blendConstants[0] = null;
  6644. this._blendConstants[1] = null;
  6645. this._blendConstants[2] = null;
  6646. this._blendConstants[3] = null;
  6647. this._isAlphaBlendDirty = true;
  6648. this._isBlendFunctionParametersDirty = false;
  6649. this._isBlendEquationParametersDirty = false;
  6650. this._isBlendConstantsDirty = false;
  6651. };
  6652. _AlphaState.prototype.apply = function (gl) {
  6653. if (!this.isDirty) {
  6654. return;
  6655. }
  6656. // Alpha blend
  6657. if (this._isAlphaBlendDirty) {
  6658. if (this._alphaBlend) {
  6659. gl.enable(gl.BLEND);
  6660. }
  6661. else {
  6662. gl.disable(gl.BLEND);
  6663. }
  6664. this._isAlphaBlendDirty = false;
  6665. }
  6666. // Alpha function
  6667. if (this._isBlendFunctionParametersDirty) {
  6668. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6669. this._isBlendFunctionParametersDirty = false;
  6670. }
  6671. // Alpha equation
  6672. if (this._isBlendEquationParametersDirty) {
  6673. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6674. this._isBlendEquationParametersDirty = false;
  6675. }
  6676. // Constants
  6677. if (this._isBlendConstantsDirty) {
  6678. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6679. this._isBlendConstantsDirty = false;
  6680. }
  6681. };
  6682. return _AlphaState;
  6683. }());
  6684. Internals._AlphaState = _AlphaState;
  6685. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6686. })(BABYLON || (BABYLON = {}));
  6687. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6688. var BABYLON;
  6689. (function (BABYLON) {
  6690. var Internals;
  6691. (function (Internals) {
  6692. var _DepthCullingState = (function () {
  6693. /**
  6694. * Initializes the state.
  6695. */
  6696. function _DepthCullingState() {
  6697. this._isDepthTestDirty = false;
  6698. this._isDepthMaskDirty = false;
  6699. this._isDepthFuncDirty = false;
  6700. this._isCullFaceDirty = false;
  6701. this._isCullDirty = false;
  6702. this._isZOffsetDirty = false;
  6703. this.reset();
  6704. }
  6705. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6706. get: function () {
  6707. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6713. get: function () {
  6714. return this._zOffset;
  6715. },
  6716. set: function (value) {
  6717. if (this._zOffset === value) {
  6718. return;
  6719. }
  6720. this._zOffset = value;
  6721. this._isZOffsetDirty = true;
  6722. },
  6723. enumerable: true,
  6724. configurable: true
  6725. });
  6726. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6727. get: function () {
  6728. return this._cullFace;
  6729. },
  6730. set: function (value) {
  6731. if (this._cullFace === value) {
  6732. return;
  6733. }
  6734. this._cullFace = value;
  6735. this._isCullFaceDirty = true;
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6741. get: function () {
  6742. return this._cull;
  6743. },
  6744. set: function (value) {
  6745. if (this._cull === value) {
  6746. return;
  6747. }
  6748. this._cull = value;
  6749. this._isCullDirty = true;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6755. get: function () {
  6756. return this._depthFunc;
  6757. },
  6758. set: function (value) {
  6759. if (this._depthFunc === value) {
  6760. return;
  6761. }
  6762. this._depthFunc = value;
  6763. this._isDepthFuncDirty = true;
  6764. },
  6765. enumerable: true,
  6766. configurable: true
  6767. });
  6768. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6769. get: function () {
  6770. return this._depthMask;
  6771. },
  6772. set: function (value) {
  6773. if (this._depthMask === value) {
  6774. return;
  6775. }
  6776. this._depthMask = value;
  6777. this._isDepthMaskDirty = true;
  6778. },
  6779. enumerable: true,
  6780. configurable: true
  6781. });
  6782. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6783. get: function () {
  6784. return this._depthTest;
  6785. },
  6786. set: function (value) {
  6787. if (this._depthTest === value) {
  6788. return;
  6789. }
  6790. this._depthTest = value;
  6791. this._isDepthTestDirty = true;
  6792. },
  6793. enumerable: true,
  6794. configurable: true
  6795. });
  6796. _DepthCullingState.prototype.reset = function () {
  6797. this._depthMask = true;
  6798. this._depthTest = true;
  6799. this._depthFunc = null;
  6800. this._cullFace = null;
  6801. this._cull = null;
  6802. this._zOffset = 0;
  6803. this._isDepthTestDirty = true;
  6804. this._isDepthMaskDirty = true;
  6805. this._isDepthFuncDirty = false;
  6806. this._isCullFaceDirty = false;
  6807. this._isCullDirty = false;
  6808. this._isZOffsetDirty = false;
  6809. };
  6810. _DepthCullingState.prototype.apply = function (gl) {
  6811. if (!this.isDirty) {
  6812. return;
  6813. }
  6814. // Cull
  6815. if (this._isCullDirty) {
  6816. if (this.cull) {
  6817. gl.enable(gl.CULL_FACE);
  6818. }
  6819. else {
  6820. gl.disable(gl.CULL_FACE);
  6821. }
  6822. this._isCullDirty = false;
  6823. }
  6824. // Cull face
  6825. if (this._isCullFaceDirty) {
  6826. gl.cullFace(this.cullFace);
  6827. this._isCullFaceDirty = false;
  6828. }
  6829. // Depth mask
  6830. if (this._isDepthMaskDirty) {
  6831. gl.depthMask(this.depthMask);
  6832. this._isDepthMaskDirty = false;
  6833. }
  6834. // Depth test
  6835. if (this._isDepthTestDirty) {
  6836. if (this.depthTest) {
  6837. gl.enable(gl.DEPTH_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.DEPTH_TEST);
  6841. }
  6842. this._isDepthTestDirty = false;
  6843. }
  6844. // Depth func
  6845. if (this._isDepthFuncDirty) {
  6846. gl.depthFunc(this.depthFunc);
  6847. this._isDepthFuncDirty = false;
  6848. }
  6849. // zOffset
  6850. if (this._isZOffsetDirty) {
  6851. if (this.zOffset) {
  6852. gl.enable(gl.POLYGON_OFFSET_FILL);
  6853. gl.polygonOffset(this.zOffset, 0);
  6854. }
  6855. else {
  6856. gl.disable(gl.POLYGON_OFFSET_FILL);
  6857. }
  6858. this._isZOffsetDirty = false;
  6859. }
  6860. };
  6861. return _DepthCullingState;
  6862. }());
  6863. Internals._DepthCullingState = _DepthCullingState;
  6864. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6865. })(BABYLON || (BABYLON = {}));
  6866. //# sourceMappingURL=babylon.depthCullingState.js.map
  6867. var BABYLON;
  6868. (function (BABYLON) {
  6869. var Internals;
  6870. (function (Internals) {
  6871. var _StencilState = (function () {
  6872. function _StencilState() {
  6873. this._isStencilTestDirty = false;
  6874. this._isStencilMaskDirty = false;
  6875. this._isStencilFuncDirty = false;
  6876. this._isStencilOpDirty = false;
  6877. this.reset();
  6878. }
  6879. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6880. get: function () {
  6881. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6887. get: function () {
  6888. return this._stencilFunc;
  6889. },
  6890. set: function (value) {
  6891. if (this._stencilFunc === value) {
  6892. return;
  6893. }
  6894. this._stencilFunc = value;
  6895. this._isStencilFuncDirty = true;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6901. get: function () {
  6902. return this._stencilFuncRef;
  6903. },
  6904. set: function (value) {
  6905. if (this._stencilFuncRef === value) {
  6906. return;
  6907. }
  6908. this._stencilFuncRef = value;
  6909. this._isStencilFuncDirty = true;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6915. get: function () {
  6916. return this._stencilFuncMask;
  6917. },
  6918. set: function (value) {
  6919. if (this._stencilFuncMask === value) {
  6920. return;
  6921. }
  6922. this._stencilFuncMask = value;
  6923. this._isStencilFuncDirty = true;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6929. get: function () {
  6930. return this._stencilOpStencilFail;
  6931. },
  6932. set: function (value) {
  6933. if (this._stencilOpStencilFail === value) {
  6934. return;
  6935. }
  6936. this._stencilOpStencilFail = value;
  6937. this._isStencilOpDirty = true;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6943. get: function () {
  6944. return this._stencilOpDepthFail;
  6945. },
  6946. set: function (value) {
  6947. if (this._stencilOpDepthFail === value) {
  6948. return;
  6949. }
  6950. this._stencilOpDepthFail = value;
  6951. this._isStencilOpDirty = true;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6957. get: function () {
  6958. return this._stencilOpStencilDepthPass;
  6959. },
  6960. set: function (value) {
  6961. if (this._stencilOpStencilDepthPass === value) {
  6962. return;
  6963. }
  6964. this._stencilOpStencilDepthPass = value;
  6965. this._isStencilOpDirty = true;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6971. get: function () {
  6972. return this._stencilMask;
  6973. },
  6974. set: function (value) {
  6975. if (this._stencilMask === value) {
  6976. return;
  6977. }
  6978. this._stencilMask = value;
  6979. this._isStencilMaskDirty = true;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6985. get: function () {
  6986. return this._stencilTest;
  6987. },
  6988. set: function (value) {
  6989. if (this._stencilTest === value) {
  6990. return;
  6991. }
  6992. this._stencilTest = value;
  6993. this._isStencilTestDirty = true;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. _StencilState.prototype.reset = function () {
  6999. this._stencilTest = false;
  7000. this._stencilMask = 0xFF;
  7001. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7002. this._stencilFuncRef = 1;
  7003. this._stencilFuncMask = 0xFF;
  7004. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7005. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7006. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7007. this._isStencilTestDirty = true;
  7008. this._isStencilMaskDirty = true;
  7009. this._isStencilFuncDirty = true;
  7010. this._isStencilOpDirty = true;
  7011. };
  7012. _StencilState.prototype.apply = function (gl) {
  7013. if (!this.isDirty) {
  7014. return;
  7015. }
  7016. // Stencil test
  7017. if (this._isStencilTestDirty) {
  7018. if (this.stencilTest) {
  7019. gl.enable(gl.STENCIL_TEST);
  7020. }
  7021. else {
  7022. gl.disable(gl.STENCIL_TEST);
  7023. }
  7024. this._isStencilTestDirty = false;
  7025. }
  7026. // Stencil mask
  7027. if (this._isStencilMaskDirty) {
  7028. gl.stencilMask(this.stencilMask);
  7029. this._isStencilMaskDirty = false;
  7030. }
  7031. // Stencil func
  7032. if (this._isStencilFuncDirty) {
  7033. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7034. this._isStencilFuncDirty = false;
  7035. }
  7036. // Stencil op
  7037. if (this._isStencilOpDirty) {
  7038. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7039. this._isStencilOpDirty = false;
  7040. }
  7041. };
  7042. return _StencilState;
  7043. }());
  7044. Internals._StencilState = _StencilState;
  7045. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7046. })(BABYLON || (BABYLON = {}));
  7047. //# sourceMappingURL=babylon.stencilState.js.map
  7048. var BABYLON;
  7049. (function (BABYLON) {
  7050. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7051. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7052. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7053. gl.compileShader(shader);
  7054. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7055. throw new Error(gl.getShaderInfoLog(shader));
  7056. }
  7057. return shader;
  7058. };
  7059. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7060. var magFilter = gl.NEAREST;
  7061. var minFilter = gl.NEAREST;
  7062. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7063. magFilter = gl.LINEAR;
  7064. if (generateMipMaps) {
  7065. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7066. }
  7067. else {
  7068. minFilter = gl.LINEAR;
  7069. }
  7070. }
  7071. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7072. magFilter = gl.LINEAR;
  7073. if (generateMipMaps) {
  7074. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7075. }
  7076. else {
  7077. minFilter = gl.LINEAR;
  7078. }
  7079. }
  7080. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7081. magFilter = gl.NEAREST;
  7082. if (generateMipMaps) {
  7083. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7084. }
  7085. else {
  7086. minFilter = gl.NEAREST;
  7087. }
  7088. }
  7089. return {
  7090. min: minFilter,
  7091. mag: magFilter
  7092. };
  7093. };
  7094. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7095. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7096. var engine = scene.getEngine();
  7097. if (!engine) {
  7098. return;
  7099. }
  7100. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7101. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7102. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7103. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7104. texture._baseWidth = width;
  7105. texture._baseHeight = height;
  7106. texture._width = potWidth;
  7107. texture._height = potHeight;
  7108. texture.isReady = true;
  7109. processFunction(potWidth, potHeight);
  7110. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7113. if (!noMipmap && !isCompressed) {
  7114. gl.generateMipmap(gl.TEXTURE_2D);
  7115. }
  7116. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7117. engine.resetTextureCache();
  7118. scene._removePendingData(texture);
  7119. texture.onLoadedCallbacks.forEach(function (callback) {
  7120. callback();
  7121. });
  7122. texture.onLoadedCallbacks = [];
  7123. };
  7124. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7125. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7126. var img;
  7127. var onload = function () {
  7128. loadedImages[index] = img;
  7129. loadedImages._internalCount++;
  7130. scene._removePendingData(img);
  7131. if (loadedImages._internalCount === 6) {
  7132. onfinish(loadedImages);
  7133. }
  7134. };
  7135. var onerror = function () {
  7136. scene._removePendingData(img);
  7137. if (onErrorCallBack) {
  7138. onErrorCallBack();
  7139. }
  7140. };
  7141. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7142. scene._addPendingData(img);
  7143. };
  7144. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7145. if (onError === void 0) { onError = null; }
  7146. var loadedImages = [];
  7147. loadedImages._internalCount = 0;
  7148. for (var index = 0; index < 6; index++) {
  7149. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7150. }
  7151. };
  7152. var InstancingAttributeInfo = (function () {
  7153. function InstancingAttributeInfo() {
  7154. }
  7155. return InstancingAttributeInfo;
  7156. }());
  7157. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7158. var EngineCapabilities = (function () {
  7159. function EngineCapabilities() {
  7160. }
  7161. return EngineCapabilities;
  7162. }());
  7163. BABYLON.EngineCapabilities = EngineCapabilities;
  7164. /**
  7165. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7166. */
  7167. var Engine = (function () {
  7168. /**
  7169. * @constructor
  7170. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7171. * @param {boolean} [antialias] - enable antialias
  7172. * @param options - further options to be sent to the getContext function
  7173. */
  7174. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7175. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7176. var _this = this;
  7177. // Public members
  7178. this.isFullscreen = false;
  7179. this.isPointerLock = false;
  7180. this.cullBackFaces = true;
  7181. this.renderEvenInBackground = true;
  7182. this.preventCacheWipeBetweenFrames = false;
  7183. // To enable/disable IDB support and avoid XHR on .manifest
  7184. this.enableOfflineSupport = BABYLON.Database;
  7185. this.scenes = new Array();
  7186. // Observables
  7187. /**
  7188. * Observable event triggered each time the rendering canvas is resized
  7189. */
  7190. this.onResizeObservable = new BABYLON.Observable();
  7191. /**
  7192. * Observable event triggered each time the canvas lost focus
  7193. */
  7194. this.onCanvasBlurObservable = new BABYLON.Observable();
  7195. this._windowIsBackground = false;
  7196. this._webGLVersion = 1.0;
  7197. this._badOS = false;
  7198. this._drawCalls = new BABYLON.PerfCounter();
  7199. this._renderingQueueLaunched = false;
  7200. this._activeRenderLoops = [];
  7201. // FPS
  7202. this.fpsRange = 60;
  7203. this.previousFramesDuration = [];
  7204. this.fps = 60;
  7205. this.deltaTime = 0;
  7206. // States
  7207. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7208. this._stencilState = new BABYLON.Internals._StencilState();
  7209. this._alphaState = new BABYLON.Internals._AlphaState();
  7210. this._alphaMode = Engine.ALPHA_DISABLE;
  7211. // Cache
  7212. this._loadedTexturesCache = new Array();
  7213. this._maxTextureChannels = 16;
  7214. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7215. this._compiledEffects = {};
  7216. this._vertexAttribArraysEnabled = [];
  7217. this._uintIndicesCurrentlySet = false;
  7218. this._currentBoundBuffer = new Array();
  7219. this._currentBufferPointers = [];
  7220. this._currentInstanceLocations = new Array();
  7221. this._currentInstanceBuffers = new Array();
  7222. this._vaoRecordInProgress = false;
  7223. this._mustWipeVertexAttributes = false;
  7224. // Hardware supported Compressed Textures
  7225. this._texturesSupported = new Array();
  7226. this._onVRFullScreenTriggered = function () {
  7227. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7228. //get the old size before we change
  7229. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7230. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7231. //get the width and height, change the render size
  7232. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7233. var width, height;
  7234. _this.setHardwareScalingLevel(1);
  7235. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7236. }
  7237. else {
  7238. //When the specs are implemented, need to uncomment this.
  7239. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7240. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7241. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7242. _this._vrDisplayEnabled = undefined;
  7243. }
  7244. };
  7245. this._renderingCanvas = canvas;
  7246. Engine.Instances.push(this);
  7247. options = options || {};
  7248. if (antialias != null) {
  7249. options.antialias = antialias;
  7250. }
  7251. if (options.preserveDrawingBuffer === undefined) {
  7252. options.preserveDrawingBuffer = false;
  7253. }
  7254. if (options.audioEngine === undefined) {
  7255. options.audioEngine = true;
  7256. }
  7257. if (options.stencil === undefined) {
  7258. options.stencil = true;
  7259. }
  7260. // GL
  7261. if (!options.disableWebGL2Support) {
  7262. try {
  7263. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7264. if (this._gl) {
  7265. this._webGLVersion = 2.0;
  7266. }
  7267. }
  7268. catch (e) {
  7269. // Do nothing
  7270. }
  7271. }
  7272. if (!this._gl) {
  7273. if (!canvas) {
  7274. throw new Error("The provided canvas is null or undefined.");
  7275. }
  7276. try {
  7277. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7278. }
  7279. catch (e) {
  7280. throw new Error("WebGL not supported");
  7281. }
  7282. }
  7283. if (!this._gl) {
  7284. throw new Error("WebGL not supported");
  7285. }
  7286. this._onBlur = function () {
  7287. _this._windowIsBackground = true;
  7288. };
  7289. this._onFocus = function () {
  7290. _this._windowIsBackground = false;
  7291. };
  7292. this._onCanvasBlur = function () {
  7293. _this.onCanvasBlurObservable.notifyObservers(_this);
  7294. };
  7295. window.addEventListener("blur", this._onBlur);
  7296. window.addEventListener("focus", this._onFocus);
  7297. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7298. // Viewport
  7299. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7300. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7301. this.resize();
  7302. // Caps
  7303. this._isStencilEnable = options.stencil;
  7304. this._caps = new EngineCapabilities();
  7305. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7306. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7307. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7308. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7309. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7310. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7311. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7312. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7313. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7314. // Infos
  7315. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7316. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7317. if (rendererInfo != null) {
  7318. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7319. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7320. }
  7321. if (!this._glVendor) {
  7322. this._glVendor = "Unknown vendor";
  7323. }
  7324. if (!this._glRenderer) {
  7325. this._glRenderer = "Unknown renderer";
  7326. }
  7327. // Extensions
  7328. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7329. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7331. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7332. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7333. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7334. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7335. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  7336. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7337. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7338. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7339. this._caps.highPrecisionShaderSupported = true;
  7340. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7341. // Checks if some of the format renders first to allow the use of webgl inspector.
  7342. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7343. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7344. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7345. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7346. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7347. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7348. if (this._webGLVersion > 1) {
  7349. Engine.HALF_FLOAT_OES = 0x140B;
  7350. }
  7351. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7352. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7353. // Vertex array object
  7354. if (this._webGLVersion > 1) {
  7355. this._caps.vertexArrayObject = true;
  7356. }
  7357. else {
  7358. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7359. if (vertexArrayObjectExtension != null) {
  7360. this._caps.vertexArrayObject = true;
  7361. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7362. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7363. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7364. }
  7365. else {
  7366. this._caps.vertexArrayObject = false;
  7367. }
  7368. }
  7369. // Instances count
  7370. if (this._webGLVersion > 1) {
  7371. this._caps.instancedArrays = true;
  7372. }
  7373. else {
  7374. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7375. if (instanceExtension != null) {
  7376. this._caps.instancedArrays = true;
  7377. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7378. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7379. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7380. }
  7381. else {
  7382. this._caps.instancedArrays = false;
  7383. }
  7384. }
  7385. // Intelligently add supported compressed formats in order to check for.
  7386. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7387. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7388. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7389. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7390. if (this._caps.astc)
  7391. this.texturesSupported.push('-astc.ktx');
  7392. if (this._caps.s3tc)
  7393. this.texturesSupported.push('-dxt.ktx');
  7394. if (this._caps.pvrtc)
  7395. this.texturesSupported.push('-pvrtc.ktx');
  7396. if (this._caps.etc2)
  7397. this.texturesSupported.push('-etc2.ktx');
  7398. if (this._caps.etc1)
  7399. this.texturesSupported.push('-etc1.ktx');
  7400. if (this._gl.getShaderPrecisionFormat) {
  7401. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7402. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7403. }
  7404. // Depth buffer
  7405. this.setDepthBuffer(true);
  7406. this.setDepthFunctionToLessOrEqual();
  7407. this.setDepthWrite(true);
  7408. // Fullscreen
  7409. this._onFullscreenChange = function () {
  7410. if (document.fullscreen !== undefined) {
  7411. _this.isFullscreen = document.fullscreen;
  7412. }
  7413. else if (document.mozFullScreen !== undefined) {
  7414. _this.isFullscreen = document.mozFullScreen;
  7415. }
  7416. else if (document.webkitIsFullScreen !== undefined) {
  7417. _this.isFullscreen = document.webkitIsFullScreen;
  7418. }
  7419. else if (document.msIsFullScreen !== undefined) {
  7420. _this.isFullscreen = document.msIsFullScreen;
  7421. }
  7422. // Pointer lock
  7423. if (_this.isFullscreen && _this._pointerLockRequested) {
  7424. canvas.requestPointerLock = canvas.requestPointerLock ||
  7425. canvas.msRequestPointerLock ||
  7426. canvas.mozRequestPointerLock ||
  7427. canvas.webkitRequestPointerLock;
  7428. if (canvas.requestPointerLock) {
  7429. canvas.requestPointerLock();
  7430. }
  7431. }
  7432. };
  7433. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7434. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7435. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7436. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7437. // Pointer lock
  7438. this._onPointerLockChange = function () {
  7439. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7440. document.webkitPointerLockElement === canvas ||
  7441. document.msPointerLockElement === canvas ||
  7442. document.pointerLockElement === canvas);
  7443. };
  7444. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7445. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7446. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7447. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7448. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7449. Engine.audioEngine = new BABYLON.AudioEngine();
  7450. }
  7451. //Load WebVR Devices
  7452. if (options.autoEnableWebVR) {
  7453. this.initWebVR();
  7454. }
  7455. //Detect if we are running on a faulty buggy OS.
  7456. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7457. //ua sniffing is the tool of the devil.
  7458. this._badOS = regexp.test(navigator.userAgent);
  7459. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7460. }
  7461. Object.defineProperty(Engine, "LastCreatedEngine", {
  7462. get: function () {
  7463. if (Engine.Instances.length === 0) {
  7464. return null;
  7465. }
  7466. return Engine.Instances[Engine.Instances.length - 1];
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(Engine, "LastCreatedScene", {
  7472. get: function () {
  7473. var lastCreatedEngine = Engine.LastCreatedEngine;
  7474. if (!lastCreatedEngine) {
  7475. return null;
  7476. }
  7477. if (lastCreatedEngine.scenes.length === 0) {
  7478. return null;
  7479. }
  7480. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. /**
  7486. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7487. */
  7488. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7489. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7490. var engine = Engine.Instances[engineIndex];
  7491. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7492. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7493. }
  7494. }
  7495. };
  7496. Object.defineProperty(Engine, "NEVER", {
  7497. get: function () {
  7498. return Engine._NEVER;
  7499. },
  7500. enumerable: true,
  7501. configurable: true
  7502. });
  7503. Object.defineProperty(Engine, "ALWAYS", {
  7504. get: function () {
  7505. return Engine._ALWAYS;
  7506. },
  7507. enumerable: true,
  7508. configurable: true
  7509. });
  7510. Object.defineProperty(Engine, "LESS", {
  7511. get: function () {
  7512. return Engine._LESS;
  7513. },
  7514. enumerable: true,
  7515. configurable: true
  7516. });
  7517. Object.defineProperty(Engine, "EQUAL", {
  7518. get: function () {
  7519. return Engine._EQUAL;
  7520. },
  7521. enumerable: true,
  7522. configurable: true
  7523. });
  7524. Object.defineProperty(Engine, "LEQUAL", {
  7525. get: function () {
  7526. return Engine._LEQUAL;
  7527. },
  7528. enumerable: true,
  7529. configurable: true
  7530. });
  7531. Object.defineProperty(Engine, "GREATER", {
  7532. get: function () {
  7533. return Engine._GREATER;
  7534. },
  7535. enumerable: true,
  7536. configurable: true
  7537. });
  7538. Object.defineProperty(Engine, "GEQUAL", {
  7539. get: function () {
  7540. return Engine._GEQUAL;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Engine, "NOTEQUAL", {
  7546. get: function () {
  7547. return Engine._NOTEQUAL;
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. Object.defineProperty(Engine, "KEEP", {
  7553. get: function () {
  7554. return Engine._KEEP;
  7555. },
  7556. enumerable: true,
  7557. configurable: true
  7558. });
  7559. Object.defineProperty(Engine, "REPLACE", {
  7560. get: function () {
  7561. return Engine._REPLACE;
  7562. },
  7563. enumerable: true,
  7564. configurable: true
  7565. });
  7566. Object.defineProperty(Engine, "INCR", {
  7567. get: function () {
  7568. return Engine._INCR;
  7569. },
  7570. enumerable: true,
  7571. configurable: true
  7572. });
  7573. Object.defineProperty(Engine, "DECR", {
  7574. get: function () {
  7575. return Engine._DECR;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Engine, "INVERT", {
  7581. get: function () {
  7582. return Engine._INVERT;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Engine, "INCR_WRAP", {
  7588. get: function () {
  7589. return Engine._INCR_WRAP;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Engine, "DECR_WRAP", {
  7595. get: function () {
  7596. return Engine._DECR_WRAP;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7602. get: function () {
  7603. return Engine._ALPHA_DISABLE;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7609. get: function () {
  7610. return Engine._ALPHA_ONEONE;
  7611. },
  7612. enumerable: true,
  7613. configurable: true
  7614. });
  7615. Object.defineProperty(Engine, "ALPHA_ADD", {
  7616. get: function () {
  7617. return Engine._ALPHA_ADD;
  7618. },
  7619. enumerable: true,
  7620. configurable: true
  7621. });
  7622. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7623. get: function () {
  7624. return Engine._ALPHA_COMBINE;
  7625. },
  7626. enumerable: true,
  7627. configurable: true
  7628. });
  7629. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7630. get: function () {
  7631. return Engine._ALPHA_SUBTRACT;
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7637. get: function () {
  7638. return Engine._ALPHA_MULTIPLY;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7644. get: function () {
  7645. return Engine._ALPHA_MAXIMIZED;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7651. get: function () {
  7652. return Engine._ALPHA_PREMULTIPLIED;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7658. get: function () {
  7659. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7665. get: function () {
  7666. return Engine._ALPHA_INTERPOLATE;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7672. get: function () {
  7673. return Engine._ALPHA_SCREENMODE;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7679. get: function () {
  7680. return Engine._DELAYLOADSTATE_NONE;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7686. get: function () {
  7687. return Engine._DELAYLOADSTATE_LOADED;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7693. get: function () {
  7694. return Engine._DELAYLOADSTATE_LOADING;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7700. get: function () {
  7701. return Engine._DELAYLOADSTATE_NOTLOADED;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7707. get: function () {
  7708. return Engine._TEXTUREFORMAT_ALPHA;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7714. get: function () {
  7715. return Engine._TEXTUREFORMAT_LUMINANCE;
  7716. },
  7717. enumerable: true,
  7718. configurable: true
  7719. });
  7720. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7721. get: function () {
  7722. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7723. },
  7724. enumerable: true,
  7725. configurable: true
  7726. });
  7727. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7728. get: function () {
  7729. return Engine._TEXTUREFORMAT_RGB;
  7730. },
  7731. enumerable: true,
  7732. configurable: true
  7733. });
  7734. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7735. get: function () {
  7736. return Engine._TEXTUREFORMAT_RGBA;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7742. get: function () {
  7743. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7744. },
  7745. enumerable: true,
  7746. configurable: true
  7747. });
  7748. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7749. get: function () {
  7750. return Engine._TEXTURETYPE_FLOAT;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7756. get: function () {
  7757. return Engine._TEXTURETYPE_HALF_FLOAT;
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7763. get: function () {
  7764. return Engine._SCALEMODE_FLOOR;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7770. get: function () {
  7771. return Engine._SCALEMODE_NEAREST;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7777. get: function () {
  7778. return Engine._SCALEMODE_CEILING;
  7779. },
  7780. enumerable: true,
  7781. configurable: true
  7782. });
  7783. Object.defineProperty(Engine, "Version", {
  7784. get: function () {
  7785. return "3.0-rc";
  7786. },
  7787. enumerable: true,
  7788. configurable: true
  7789. });
  7790. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7791. get: function () {
  7792. return this._texturesSupported;
  7793. },
  7794. enumerable: true,
  7795. configurable: true
  7796. });
  7797. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7798. get: function () {
  7799. return this._textureFormatInUse;
  7800. },
  7801. enumerable: true,
  7802. configurable: true
  7803. });
  7804. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7805. // Empty texture
  7806. get: function () {
  7807. if (!this._emptyTexture) {
  7808. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7809. }
  7810. return this._emptyTexture;
  7811. },
  7812. enumerable: true,
  7813. configurable: true
  7814. });
  7815. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7816. get: function () {
  7817. if (!this._emptyCubeTexture) {
  7818. var faceData = new Uint8Array(4);
  7819. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7820. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7821. }
  7822. return this._emptyCubeTexture;
  7823. },
  7824. enumerable: true,
  7825. configurable: true
  7826. });
  7827. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7828. get: function () {
  7829. return this._webGLVersion;
  7830. },
  7831. enumerable: true,
  7832. configurable: true
  7833. });
  7834. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7835. /**
  7836. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7837. */
  7838. get: function () {
  7839. return this._isStencilEnable;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Engine.prototype._prepareWorkingCanvas = function () {
  7845. if (this._workingCanvas) {
  7846. return;
  7847. }
  7848. this._workingCanvas = document.createElement("canvas");
  7849. this._workingContext = this._workingCanvas.getContext("2d");
  7850. };
  7851. Engine.prototype.resetTextureCache = function () {
  7852. for (var index = 0; index < this._maxTextureChannels; index++) {
  7853. this._activeTexturesCache[index] = null;
  7854. }
  7855. };
  7856. Engine.prototype.getGlInfo = function () {
  7857. return {
  7858. vendor: this._glVendor,
  7859. renderer: this._glRenderer,
  7860. version: this._glVersion
  7861. };
  7862. };
  7863. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7864. if (useScreen === void 0) { useScreen = false; }
  7865. var viewport = camera.viewport;
  7866. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7867. };
  7868. Engine.prototype.getRenderWidth = function (useScreen) {
  7869. if (useScreen === void 0) { useScreen = false; }
  7870. if (!useScreen && this._currentRenderTarget) {
  7871. return this._currentRenderTarget._width;
  7872. }
  7873. return this._renderingCanvas.width;
  7874. };
  7875. Engine.prototype.getRenderHeight = function (useScreen) {
  7876. if (useScreen === void 0) { useScreen = false; }
  7877. if (!useScreen && this._currentRenderTarget) {
  7878. return this._currentRenderTarget._height;
  7879. }
  7880. return this._renderingCanvas.height;
  7881. };
  7882. Engine.prototype.getRenderingCanvas = function () {
  7883. return this._renderingCanvas;
  7884. };
  7885. Engine.prototype.getRenderingCanvasClientRect = function () {
  7886. return this._renderingCanvas.getBoundingClientRect();
  7887. };
  7888. Engine.prototype.setHardwareScalingLevel = function (level) {
  7889. this._hardwareScalingLevel = level;
  7890. this.resize();
  7891. };
  7892. Engine.prototype.getHardwareScalingLevel = function () {
  7893. return this._hardwareScalingLevel;
  7894. };
  7895. Engine.prototype.getLoadedTexturesCache = function () {
  7896. return this._loadedTexturesCache;
  7897. };
  7898. Engine.prototype.getCaps = function () {
  7899. return this._caps;
  7900. };
  7901. Object.defineProperty(Engine.prototype, "drawCalls", {
  7902. get: function () {
  7903. return this._drawCalls.current;
  7904. },
  7905. enumerable: true,
  7906. configurable: true
  7907. });
  7908. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7909. get: function () {
  7910. return this._drawCalls;
  7911. },
  7912. enumerable: true,
  7913. configurable: true
  7914. });
  7915. Engine.prototype.getDepthFunction = function () {
  7916. return this._depthCullingState.depthFunc;
  7917. };
  7918. Engine.prototype.setDepthFunction = function (depthFunc) {
  7919. this._depthCullingState.depthFunc = depthFunc;
  7920. };
  7921. Engine.prototype.setDepthFunctionToGreater = function () {
  7922. this._depthCullingState.depthFunc = this._gl.GREATER;
  7923. };
  7924. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7925. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7926. };
  7927. Engine.prototype.setDepthFunctionToLess = function () {
  7928. this._depthCullingState.depthFunc = this._gl.LESS;
  7929. };
  7930. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7931. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7932. };
  7933. Engine.prototype.getStencilBuffer = function () {
  7934. return this._stencilState.stencilTest;
  7935. };
  7936. Engine.prototype.setStencilBuffer = function (enable) {
  7937. this._stencilState.stencilTest = enable;
  7938. };
  7939. Engine.prototype.getStencilMask = function () {
  7940. return this._stencilState.stencilMask;
  7941. };
  7942. Engine.prototype.setStencilMask = function (mask) {
  7943. this._stencilState.stencilMask = mask;
  7944. };
  7945. Engine.prototype.getStencilFunction = function () {
  7946. return this._stencilState.stencilFunc;
  7947. };
  7948. Engine.prototype.getStencilFunctionReference = function () {
  7949. return this._stencilState.stencilFuncRef;
  7950. };
  7951. Engine.prototype.getStencilFunctionMask = function () {
  7952. return this._stencilState.stencilFuncMask;
  7953. };
  7954. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7955. this._stencilState.stencilFunc = stencilFunc;
  7956. };
  7957. Engine.prototype.setStencilFunctionReference = function (reference) {
  7958. this._stencilState.stencilFuncRef = reference;
  7959. };
  7960. Engine.prototype.setStencilFunctionMask = function (mask) {
  7961. this._stencilState.stencilFuncMask = mask;
  7962. };
  7963. Engine.prototype.getStencilOperationFail = function () {
  7964. return this._stencilState.stencilOpStencilFail;
  7965. };
  7966. Engine.prototype.getStencilOperationDepthFail = function () {
  7967. return this._stencilState.stencilOpDepthFail;
  7968. };
  7969. Engine.prototype.getStencilOperationPass = function () {
  7970. return this._stencilState.stencilOpStencilDepthPass;
  7971. };
  7972. Engine.prototype.setStencilOperationFail = function (operation) {
  7973. this._stencilState.stencilOpStencilFail = operation;
  7974. };
  7975. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7976. this._stencilState.stencilOpDepthFail = operation;
  7977. };
  7978. Engine.prototype.setStencilOperationPass = function (operation) {
  7979. this._stencilState.stencilOpStencilDepthPass = operation;
  7980. };
  7981. Engine.prototype.setDitheringState = function (value) {
  7982. if (value) {
  7983. this._gl.enable(this._gl.DITHER);
  7984. }
  7985. else {
  7986. this._gl.disable(this._gl.DITHER);
  7987. }
  7988. };
  7989. /**
  7990. * stop executing a render loop function and remove it from the execution array
  7991. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7992. */
  7993. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7994. if (!renderFunction) {
  7995. this._activeRenderLoops = [];
  7996. return;
  7997. }
  7998. var index = this._activeRenderLoops.indexOf(renderFunction);
  7999. if (index >= 0) {
  8000. this._activeRenderLoops.splice(index, 1);
  8001. }
  8002. };
  8003. Engine.prototype._renderLoop = function () {
  8004. var shouldRender = true;
  8005. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8006. shouldRender = false;
  8007. }
  8008. if (shouldRender) {
  8009. // Start new frame
  8010. this.beginFrame();
  8011. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8012. var renderFunction = this._activeRenderLoops[index];
  8013. renderFunction();
  8014. }
  8015. // Present
  8016. this.endFrame();
  8017. }
  8018. if (this._activeRenderLoops.length > 0) {
  8019. // Register new frame
  8020. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8021. }
  8022. else {
  8023. this._renderingQueueLaunched = false;
  8024. }
  8025. };
  8026. /**
  8027. * Register and execute a render loop. The engine can have more than one render function.
  8028. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8029. * @example
  8030. * engine.runRenderLoop(function () {
  8031. * scene.render()
  8032. * })
  8033. */
  8034. Engine.prototype.runRenderLoop = function (renderFunction) {
  8035. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8036. return;
  8037. }
  8038. this._activeRenderLoops.push(renderFunction);
  8039. if (!this._renderingQueueLaunched) {
  8040. this._renderingQueueLaunched = true;
  8041. this._bindedRenderFunction = this._renderLoop.bind(this);
  8042. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8043. }
  8044. };
  8045. /**
  8046. * Toggle full screen mode.
  8047. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8048. * @param {any} options - an options object to be sent to the requestFullscreen function
  8049. */
  8050. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8051. if (this.isFullscreen) {
  8052. BABYLON.Tools.ExitFullscreen();
  8053. }
  8054. else {
  8055. this._pointerLockRequested = requestPointerLock;
  8056. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8057. }
  8058. };
  8059. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8060. if (stencil === void 0) { stencil = false; }
  8061. this.applyStates();
  8062. var mode = 0;
  8063. if (backBuffer && color) {
  8064. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8065. mode |= this._gl.COLOR_BUFFER_BIT;
  8066. }
  8067. if (depth) {
  8068. this._gl.clearDepth(1.0);
  8069. mode |= this._gl.DEPTH_BUFFER_BIT;
  8070. }
  8071. if (stencil) {
  8072. this._gl.clearStencil(0);
  8073. mode |= this._gl.STENCIL_BUFFER_BIT;
  8074. }
  8075. this._gl.clear(mode);
  8076. };
  8077. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8078. var gl = this._gl;
  8079. // Save state
  8080. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8081. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8082. // Change state
  8083. gl.enable(gl.SCISSOR_TEST);
  8084. gl.scissor(x, y, width, height);
  8085. // Clear
  8086. this.clear(clearColor, true, true, true);
  8087. // Restore state
  8088. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8089. if (curScissor === true) {
  8090. gl.enable(gl.SCISSOR_TEST);
  8091. }
  8092. else {
  8093. gl.disable(gl.SCISSOR_TEST);
  8094. }
  8095. };
  8096. /**
  8097. * Set the WebGL's viewport
  8098. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8099. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8100. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8101. */
  8102. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8103. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8104. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8105. var x = viewport.x || 0;
  8106. var y = viewport.y || 0;
  8107. this._cachedViewport = viewport;
  8108. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8109. };
  8110. /**
  8111. * Directly set the WebGL Viewport
  8112. * The x, y, width & height are directly passed to the WebGL call
  8113. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  8114. */
  8115. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8116. var currentViewport = this._cachedViewport;
  8117. this._cachedViewport = null;
  8118. this._gl.viewport(x, y, width, height);
  8119. return currentViewport;
  8120. };
  8121. Engine.prototype.beginFrame = function () {
  8122. this._measureFps();
  8123. };
  8124. Engine.prototype.endFrame = function () {
  8125. //force a flush in case we are using a bad OS.
  8126. if (this._badOS) {
  8127. this.flushFramebuffer();
  8128. }
  8129. //submit frame to the vr device, if enabled
  8130. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8131. this._vrDisplayEnabled.submitFrame();
  8132. }
  8133. };
  8134. /**
  8135. * resize the view according to the canvas' size.
  8136. * @example
  8137. * window.addEventListener("resize", function () {
  8138. * engine.resize();
  8139. * });
  8140. */
  8141. Engine.prototype.resize = function () {
  8142. // We're not resizing the size of the canvas while in VR mode & presenting
  8143. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8144. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8145. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8146. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8147. }
  8148. };
  8149. /**
  8150. * force a specific size of the canvas
  8151. * @param {number} width - the new canvas' width
  8152. * @param {number} height - the new canvas' height
  8153. */
  8154. Engine.prototype.setSize = function (width, height) {
  8155. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8156. return;
  8157. }
  8158. this._renderingCanvas.width = width;
  8159. this._renderingCanvas.height = height;
  8160. for (var index = 0; index < this.scenes.length; index++) {
  8161. var scene = this.scenes[index];
  8162. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8163. var cam = scene.cameras[camIndex];
  8164. cam._currentRenderId = 0;
  8165. }
  8166. }
  8167. if (this.onResizeObservable.hasObservers) {
  8168. this.onResizeObservable.notifyObservers(this);
  8169. }
  8170. };
  8171. //WebVR functions
  8172. Engine.prototype.isVRDevicePresent = function (callback) {
  8173. this.getVRDevice(null, function (device) {
  8174. callback(device !== null);
  8175. });
  8176. };
  8177. Engine.prototype.getVRDevice = function (name, callback) {
  8178. if (!this.vrDisplaysPromise) {
  8179. callback(null);
  8180. return;
  8181. }
  8182. this.vrDisplaysPromise.then(function (devices) {
  8183. if (devices.length > 0) {
  8184. if (name) {
  8185. var found = devices.some(function (device) {
  8186. if (device.displayName === name) {
  8187. callback(device);
  8188. return true;
  8189. }
  8190. else {
  8191. return false;
  8192. }
  8193. });
  8194. if (!found) {
  8195. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8196. callback(devices[0]);
  8197. }
  8198. }
  8199. else {
  8200. //choose the first one
  8201. callback(devices[0]);
  8202. }
  8203. }
  8204. else {
  8205. BABYLON.Tools.Error("No WebVR devices found!");
  8206. callback(null);
  8207. }
  8208. });
  8209. };
  8210. Engine.prototype.initWebVR = function () {
  8211. if (!this.vrDisplaysPromise) {
  8212. this._getVRDisplays();
  8213. }
  8214. };
  8215. Engine.prototype.enableVR = function (vrDevice) {
  8216. this._vrDisplayEnabled = vrDevice;
  8217. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8218. };
  8219. Engine.prototype.disableVR = function () {
  8220. if (this._vrDisplayEnabled) {
  8221. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8222. }
  8223. };
  8224. Engine.prototype._getVRDisplays = function () {
  8225. var _this = this;
  8226. var getWebVRDevices = function (devices) {
  8227. var size = devices.length;
  8228. var i = 0;
  8229. _this._vrDisplays = devices.filter(function (device) {
  8230. return devices[i] instanceof VRDisplay;
  8231. });
  8232. return _this._vrDisplays;
  8233. };
  8234. //using a key due to typescript
  8235. if (navigator.getVRDisplays) {
  8236. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8237. }
  8238. };
  8239. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8240. this._currentRenderTarget = texture;
  8241. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8242. var gl = this._gl;
  8243. if (texture.isCube) {
  8244. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8245. }
  8246. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8247. this.wipeCaches();
  8248. };
  8249. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8250. if (this._currentFramebuffer !== framebuffer) {
  8251. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8252. this._currentFramebuffer = framebuffer;
  8253. }
  8254. };
  8255. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8256. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8257. this._currentRenderTarget = null;
  8258. // If MSAA, we need to bitblt back to main texture
  8259. var gl = this._gl;
  8260. if (texture._MSAAFramebuffer) {
  8261. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8262. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8263. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8264. }
  8265. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8266. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8267. gl.generateMipmap(gl.TEXTURE_2D);
  8268. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8269. }
  8270. if (onBeforeUnbind) {
  8271. if (texture._MSAAFramebuffer) {
  8272. // Bind the correct framebuffer
  8273. this.bindUnboundFramebuffer(texture._framebuffer);
  8274. }
  8275. onBeforeUnbind();
  8276. }
  8277. this.bindUnboundFramebuffer(null);
  8278. };
  8279. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8280. if (texture.generateMipMaps) {
  8281. var gl = this._gl;
  8282. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8283. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8284. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8285. }
  8286. };
  8287. Engine.prototype.flushFramebuffer = function () {
  8288. this._gl.flush();
  8289. };
  8290. Engine.prototype.restoreDefaultFramebuffer = function () {
  8291. this._currentRenderTarget = null;
  8292. this.bindUnboundFramebuffer(null);
  8293. if (this._cachedViewport) {
  8294. this.setViewport(this._cachedViewport);
  8295. }
  8296. this.wipeCaches();
  8297. };
  8298. // UBOs
  8299. Engine.prototype.createUniformBuffer = function (elements) {
  8300. var ubo = this._gl.createBuffer();
  8301. this.bindUniformBuffer(ubo);
  8302. if (elements instanceof Float32Array) {
  8303. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8304. }
  8305. else {
  8306. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8307. }
  8308. this.bindUniformBuffer(null);
  8309. ubo.references = 1;
  8310. return ubo;
  8311. };
  8312. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8313. var ubo = this._gl.createBuffer();
  8314. this.bindUniformBuffer(ubo);
  8315. if (elements instanceof Float32Array) {
  8316. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8317. }
  8318. else {
  8319. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8320. }
  8321. this.bindUniformBuffer(null);
  8322. ubo.references = 1;
  8323. return ubo;
  8324. };
  8325. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8326. this.bindUniformBuffer(uniformBuffer);
  8327. if (offset === undefined) {
  8328. offset = 0;
  8329. }
  8330. if (count === undefined) {
  8331. if (elements instanceof Float32Array) {
  8332. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8333. }
  8334. else {
  8335. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8336. }
  8337. }
  8338. else {
  8339. if (elements instanceof Float32Array) {
  8340. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8341. }
  8342. else {
  8343. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8344. }
  8345. }
  8346. this.bindUniformBuffer(null);
  8347. };
  8348. // VBOs
  8349. Engine.prototype._resetVertexBufferBinding = function () {
  8350. this.bindArrayBuffer(null);
  8351. this._cachedVertexBuffers = null;
  8352. };
  8353. Engine.prototype.createVertexBuffer = function (vertices) {
  8354. var vbo = this._gl.createBuffer();
  8355. this.bindArrayBuffer(vbo);
  8356. if (vertices instanceof Float32Array) {
  8357. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8358. }
  8359. else {
  8360. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8361. }
  8362. this._resetVertexBufferBinding();
  8363. vbo.references = 1;
  8364. return vbo;
  8365. };
  8366. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8367. var vbo = this._gl.createBuffer();
  8368. this.bindArrayBuffer(vbo);
  8369. if (vertices instanceof Float32Array) {
  8370. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8371. }
  8372. else {
  8373. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8374. }
  8375. this._resetVertexBufferBinding();
  8376. vbo.references = 1;
  8377. return vbo;
  8378. };
  8379. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8380. this.bindArrayBuffer(vertexBuffer);
  8381. if (offset === undefined) {
  8382. offset = 0;
  8383. }
  8384. if (count === undefined) {
  8385. if (vertices instanceof Float32Array) {
  8386. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8387. }
  8388. else {
  8389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8390. }
  8391. }
  8392. else {
  8393. if (vertices instanceof Float32Array) {
  8394. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8395. }
  8396. else {
  8397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8398. }
  8399. }
  8400. this._resetVertexBufferBinding();
  8401. };
  8402. Engine.prototype._resetIndexBufferBinding = function () {
  8403. this.bindIndexBuffer(null);
  8404. this._cachedIndexBuffer = null;
  8405. };
  8406. Engine.prototype.createIndexBuffer = function (indices) {
  8407. var vbo = this._gl.createBuffer();
  8408. this.bindIndexBuffer(vbo);
  8409. // Check for 32 bits indices
  8410. var arrayBuffer;
  8411. var need32Bits = false;
  8412. if (indices instanceof Uint16Array) {
  8413. arrayBuffer = indices;
  8414. }
  8415. else {
  8416. //check 32 bit support
  8417. if (this._caps.uintIndices) {
  8418. if (indices instanceof Uint32Array) {
  8419. arrayBuffer = indices;
  8420. need32Bits = true;
  8421. }
  8422. else {
  8423. //number[] or Int32Array, check if 32 bit is necessary
  8424. for (var index = 0; index < indices.length; index++) {
  8425. if (indices[index] > 65535) {
  8426. need32Bits = true;
  8427. break;
  8428. }
  8429. }
  8430. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8431. }
  8432. }
  8433. else {
  8434. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8435. arrayBuffer = new Uint16Array(indices);
  8436. }
  8437. }
  8438. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8439. this._resetIndexBufferBinding();
  8440. vbo.references = 1;
  8441. vbo.is32Bits = need32Bits;
  8442. return vbo;
  8443. };
  8444. Engine.prototype.bindArrayBuffer = function (buffer) {
  8445. if (!this._vaoRecordInProgress) {
  8446. this._unBindVertexArrayObject();
  8447. }
  8448. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8449. };
  8450. Engine.prototype.bindUniformBuffer = function (buffer) {
  8451. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8452. };
  8453. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8454. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8455. };
  8456. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8457. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8458. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8459. };
  8460. ;
  8461. Engine.prototype.bindIndexBuffer = function (buffer) {
  8462. if (!this._vaoRecordInProgress) {
  8463. this._unBindVertexArrayObject();
  8464. }
  8465. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8466. };
  8467. Engine.prototype.bindBuffer = function (buffer, target) {
  8468. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8469. this._gl.bindBuffer(target, buffer);
  8470. this._currentBoundBuffer[target] = buffer;
  8471. }
  8472. };
  8473. Engine.prototype.updateArrayBuffer = function (data) {
  8474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8475. };
  8476. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8477. var pointer = this._currentBufferPointers[indx];
  8478. var changed = false;
  8479. if (!pointer) {
  8480. changed = true;
  8481. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8482. }
  8483. else {
  8484. if (pointer.buffer !== buffer) {
  8485. pointer.buffer = buffer;
  8486. changed = true;
  8487. }
  8488. if (pointer.size !== size) {
  8489. pointer.size = size;
  8490. changed = true;
  8491. }
  8492. if (pointer.type !== type) {
  8493. pointer.type = type;
  8494. changed = true;
  8495. }
  8496. if (pointer.normalized !== normalized) {
  8497. pointer.normalized = normalized;
  8498. changed = true;
  8499. }
  8500. if (pointer.stride !== stride) {
  8501. pointer.stride = stride;
  8502. changed = true;
  8503. }
  8504. if (pointer.offset !== offset) {
  8505. pointer.offset = offset;
  8506. changed = true;
  8507. }
  8508. }
  8509. if (changed || this._vaoRecordInProgress) {
  8510. this.bindArrayBuffer(buffer);
  8511. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8512. }
  8513. };
  8514. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8515. if (indexBuffer == null) {
  8516. return;
  8517. }
  8518. if (this._cachedIndexBuffer !== indexBuffer) {
  8519. this._cachedIndexBuffer = indexBuffer;
  8520. this.bindIndexBuffer(indexBuffer);
  8521. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8522. }
  8523. };
  8524. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8525. var attributes = effect.getAttributesNames();
  8526. if (!this._vaoRecordInProgress) {
  8527. this._unBindVertexArrayObject();
  8528. }
  8529. this.unbindAllAttributes();
  8530. for (var index = 0; index < attributes.length; index++) {
  8531. var order = effect.getAttributeLocation(index);
  8532. if (order >= 0) {
  8533. var vertexBuffer = vertexBuffers[attributes[index]];
  8534. if (!vertexBuffer) {
  8535. continue;
  8536. }
  8537. this._gl.enableVertexAttribArray(order);
  8538. if (!this._vaoRecordInProgress) {
  8539. this._vertexAttribArraysEnabled[order] = true;
  8540. }
  8541. var buffer = vertexBuffer.getBuffer();
  8542. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8543. if (vertexBuffer.getIsInstanced()) {
  8544. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8545. if (!this._vaoRecordInProgress) {
  8546. this._currentInstanceLocations.push(order);
  8547. this._currentInstanceBuffers.push(buffer);
  8548. }
  8549. }
  8550. }
  8551. }
  8552. };
  8553. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8554. var vao = this._gl.createVertexArray();
  8555. this._vaoRecordInProgress = true;
  8556. this._gl.bindVertexArray(vao);
  8557. this._mustWipeVertexAttributes = true;
  8558. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8559. this.bindIndexBuffer(indexBuffer);
  8560. this._vaoRecordInProgress = false;
  8561. this._gl.bindVertexArray(null);
  8562. return vao;
  8563. };
  8564. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8565. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8566. this._cachedVertexArrayObject = vertexArrayObject;
  8567. this._gl.bindVertexArray(vertexArrayObject);
  8568. this._cachedVertexBuffers = null;
  8569. this._cachedIndexBuffer = null;
  8570. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8571. this._mustWipeVertexAttributes = true;
  8572. }
  8573. };
  8574. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8575. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8576. this._cachedVertexBuffers = vertexBuffer;
  8577. this._cachedEffectForVertexBuffers = effect;
  8578. var attributesCount = effect.getAttributesCount();
  8579. this._unBindVertexArrayObject();
  8580. this.unbindAllAttributes();
  8581. var offset = 0;
  8582. for (var index = 0; index < attributesCount; index++) {
  8583. if (index < vertexDeclaration.length) {
  8584. var order = effect.getAttributeLocation(index);
  8585. if (order >= 0) {
  8586. this._gl.enableVertexAttribArray(order);
  8587. this._vertexAttribArraysEnabled[order] = true;
  8588. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8589. }
  8590. offset += vertexDeclaration[index] * 4;
  8591. }
  8592. }
  8593. }
  8594. this._bindIndexBufferWithCache(indexBuffer);
  8595. };
  8596. Engine.prototype._unBindVertexArrayObject = function () {
  8597. if (!this._cachedVertexArrayObject) {
  8598. return;
  8599. }
  8600. this._cachedVertexArrayObject = null;
  8601. this._gl.bindVertexArray(null);
  8602. };
  8603. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8604. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8605. this._cachedVertexBuffers = vertexBuffers;
  8606. this._cachedEffectForVertexBuffers = effect;
  8607. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8608. }
  8609. this._bindIndexBufferWithCache(indexBuffer);
  8610. };
  8611. Engine.prototype.unbindInstanceAttributes = function () {
  8612. var boundBuffer;
  8613. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8614. var instancesBuffer = this._currentInstanceBuffers[i];
  8615. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8616. boundBuffer = instancesBuffer;
  8617. this.bindArrayBuffer(instancesBuffer);
  8618. }
  8619. var offsetLocation = this._currentInstanceLocations[i];
  8620. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8621. }
  8622. this._currentInstanceBuffers.length = 0;
  8623. this._currentInstanceLocations.length = 0;
  8624. };
  8625. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8626. this._gl.deleteVertexArray(vao);
  8627. };
  8628. Engine.prototype._releaseBuffer = function (buffer) {
  8629. buffer.references--;
  8630. if (buffer.references === 0) {
  8631. this._gl.deleteBuffer(buffer);
  8632. return true;
  8633. }
  8634. return false;
  8635. };
  8636. Engine.prototype.createInstancesBuffer = function (capacity) {
  8637. var buffer = this._gl.createBuffer();
  8638. buffer.capacity = capacity;
  8639. this.bindArrayBuffer(buffer);
  8640. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8641. return buffer;
  8642. };
  8643. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8644. this._gl.deleteBuffer(buffer);
  8645. };
  8646. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8647. this.bindArrayBuffer(instancesBuffer);
  8648. if (data) {
  8649. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8650. }
  8651. if (offsetLocations[0].index !== undefined) {
  8652. var stride = 0;
  8653. for (var i = 0; i < offsetLocations.length; i++) {
  8654. var ai = offsetLocations[i];
  8655. stride += ai.attributeSize * 4;
  8656. }
  8657. for (var i = 0; i < offsetLocations.length; i++) {
  8658. var ai = offsetLocations[i];
  8659. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8660. this._gl.enableVertexAttribArray(ai.index);
  8661. this._vertexAttribArraysEnabled[ai.index] = true;
  8662. }
  8663. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8664. this._gl.vertexAttribDivisor(ai.index, 1);
  8665. this._currentInstanceLocations.push(ai.index);
  8666. this._currentInstanceBuffers.push(instancesBuffer);
  8667. }
  8668. }
  8669. else {
  8670. for (var index = 0; index < 4; index++) {
  8671. var offsetLocation = offsetLocations[index];
  8672. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8673. this._gl.enableVertexAttribArray(offsetLocation);
  8674. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8675. }
  8676. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8677. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8678. this._currentInstanceLocations.push(offsetLocation);
  8679. this._currentInstanceBuffers.push(instancesBuffer);
  8680. }
  8681. }
  8682. };
  8683. Engine.prototype.applyStates = function () {
  8684. this._depthCullingState.apply(this._gl);
  8685. this._stencilState.apply(this._gl);
  8686. this._alphaState.apply(this._gl);
  8687. };
  8688. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8689. // Apply states
  8690. this.applyStates();
  8691. this._drawCalls.addCount(1, false);
  8692. // Render
  8693. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8694. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8695. if (instancesCount) {
  8696. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8697. return;
  8698. }
  8699. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8700. };
  8701. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8702. // Apply states
  8703. this.applyStates();
  8704. this._drawCalls.addCount(1, false);
  8705. if (instancesCount) {
  8706. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8707. return;
  8708. }
  8709. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8710. };
  8711. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8712. // Apply states
  8713. this.applyStates();
  8714. this._drawCalls.addCount(1, false);
  8715. if (instancesCount) {
  8716. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8717. return;
  8718. }
  8719. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8720. };
  8721. // Shaders
  8722. Engine.prototype._releaseEffect = function (effect) {
  8723. if (this._compiledEffects[effect._key]) {
  8724. delete this._compiledEffects[effect._key];
  8725. if (effect.getProgram()) {
  8726. this._gl.deleteProgram(effect.getProgram());
  8727. }
  8728. }
  8729. };
  8730. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8731. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8732. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8733. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8734. if (this._compiledEffects[name]) {
  8735. var compiledEffect = this._compiledEffects[name];
  8736. if (onCompiled && compiledEffect.isReady()) {
  8737. onCompiled(compiledEffect);
  8738. }
  8739. return compiledEffect;
  8740. }
  8741. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8742. effect._key = name;
  8743. this._compiledEffects[name] = effect;
  8744. return effect;
  8745. };
  8746. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8747. if (uniformsNames === void 0) { uniformsNames = []; }
  8748. if (samplers === void 0) { samplers = []; }
  8749. if (defines === void 0) { defines = ""; }
  8750. return this.createEffect({
  8751. vertex: "particles",
  8752. fragmentElement: fragmentName
  8753. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8754. };
  8755. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8756. context = context || this._gl;
  8757. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8758. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8759. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8760. var shaderProgram = context.createProgram();
  8761. context.attachShader(shaderProgram, vertexShader);
  8762. context.attachShader(shaderProgram, fragmentShader);
  8763. context.linkProgram(shaderProgram);
  8764. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8765. if (!linked) {
  8766. var error = context.getProgramInfoLog(shaderProgram);
  8767. if (error) {
  8768. throw new Error(error);
  8769. }
  8770. }
  8771. context.deleteShader(vertexShader);
  8772. context.deleteShader(fragmentShader);
  8773. return shaderProgram;
  8774. };
  8775. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8776. var results = [];
  8777. for (var index = 0; index < uniformsNames.length; index++) {
  8778. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8779. }
  8780. return results;
  8781. };
  8782. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8783. var results = [];
  8784. for (var index = 0; index < attributesNames.length; index++) {
  8785. try {
  8786. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8787. }
  8788. catch (e) {
  8789. results.push(-1);
  8790. }
  8791. }
  8792. return results;
  8793. };
  8794. Engine.prototype.enableEffect = function (effect) {
  8795. // Use program
  8796. this.setProgram(effect.getProgram());
  8797. this._currentEffect = effect;
  8798. if (effect.onBind) {
  8799. effect.onBind(effect);
  8800. }
  8801. effect.onBindObservable.notifyObservers(effect);
  8802. };
  8803. Engine.prototype.setIntArray = function (uniform, array) {
  8804. if (!uniform)
  8805. return;
  8806. this._gl.uniform1iv(uniform, array);
  8807. };
  8808. Engine.prototype.setIntArray2 = function (uniform, array) {
  8809. if (!uniform || array.length % 2 !== 0)
  8810. return;
  8811. this._gl.uniform2iv(uniform, array);
  8812. };
  8813. Engine.prototype.setIntArray3 = function (uniform, array) {
  8814. if (!uniform || array.length % 3 !== 0)
  8815. return;
  8816. this._gl.uniform3iv(uniform, array);
  8817. };
  8818. Engine.prototype.setIntArray4 = function (uniform, array) {
  8819. if (!uniform || array.length % 4 !== 0)
  8820. return;
  8821. this._gl.uniform4iv(uniform, array);
  8822. };
  8823. Engine.prototype.setFloatArray = function (uniform, array) {
  8824. if (!uniform)
  8825. return;
  8826. this._gl.uniform1fv(uniform, array);
  8827. };
  8828. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8829. if (!uniform || array.length % 2 !== 0)
  8830. return;
  8831. this._gl.uniform2fv(uniform, array);
  8832. };
  8833. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8834. if (!uniform || array.length % 3 !== 0)
  8835. return;
  8836. this._gl.uniform3fv(uniform, array);
  8837. };
  8838. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8839. if (!uniform || array.length % 4 !== 0)
  8840. return;
  8841. this._gl.uniform4fv(uniform, array);
  8842. };
  8843. Engine.prototype.setArray = function (uniform, array) {
  8844. if (!uniform)
  8845. return;
  8846. this._gl.uniform1fv(uniform, array);
  8847. };
  8848. Engine.prototype.setArray2 = function (uniform, array) {
  8849. if (!uniform || array.length % 2 !== 0)
  8850. return;
  8851. this._gl.uniform2fv(uniform, array);
  8852. };
  8853. Engine.prototype.setArray3 = function (uniform, array) {
  8854. if (!uniform || array.length % 3 !== 0)
  8855. return;
  8856. this._gl.uniform3fv(uniform, array);
  8857. };
  8858. Engine.prototype.setArray4 = function (uniform, array) {
  8859. if (!uniform || array.length % 4 !== 0)
  8860. return;
  8861. this._gl.uniform4fv(uniform, array);
  8862. };
  8863. Engine.prototype.setMatrices = function (uniform, matrices) {
  8864. if (!uniform)
  8865. return;
  8866. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8867. };
  8868. Engine.prototype.setMatrix = function (uniform, matrix) {
  8869. if (!uniform)
  8870. return;
  8871. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8872. };
  8873. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8874. if (!uniform)
  8875. return;
  8876. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8877. };
  8878. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8879. if (!uniform)
  8880. return;
  8881. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8882. };
  8883. Engine.prototype.setFloat = function (uniform, value) {
  8884. if (!uniform)
  8885. return;
  8886. this._gl.uniform1f(uniform, value);
  8887. };
  8888. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8889. if (!uniform)
  8890. return;
  8891. this._gl.uniform2f(uniform, x, y);
  8892. };
  8893. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8894. if (!uniform)
  8895. return;
  8896. this._gl.uniform3f(uniform, x, y, z);
  8897. };
  8898. Engine.prototype.setBool = function (uniform, bool) {
  8899. if (!uniform)
  8900. return;
  8901. this._gl.uniform1i(uniform, bool);
  8902. };
  8903. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8904. if (!uniform)
  8905. return;
  8906. this._gl.uniform4f(uniform, x, y, z, w);
  8907. };
  8908. Engine.prototype.setColor3 = function (uniform, color3) {
  8909. if (!uniform)
  8910. return;
  8911. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8912. };
  8913. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8914. if (!uniform)
  8915. return;
  8916. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8917. };
  8918. // States
  8919. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8920. if (zOffset === void 0) { zOffset = 0; }
  8921. if (reverseSide === void 0) { reverseSide = false; }
  8922. // Culling
  8923. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8924. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8925. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8926. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8927. if (culling) {
  8928. this._depthCullingState.cullFace = cullFace;
  8929. this._depthCullingState.cull = true;
  8930. }
  8931. else {
  8932. this._depthCullingState.cull = false;
  8933. }
  8934. }
  8935. // Z offset
  8936. this.setZOffset(zOffset);
  8937. };
  8938. Engine.prototype.setZOffset = function (value) {
  8939. this._depthCullingState.zOffset = value;
  8940. };
  8941. Engine.prototype.getZOffset = function () {
  8942. return this._depthCullingState.zOffset;
  8943. };
  8944. Engine.prototype.setDepthBuffer = function (enable) {
  8945. this._depthCullingState.depthTest = enable;
  8946. };
  8947. Engine.prototype.getDepthWrite = function () {
  8948. return this._depthCullingState.depthMask;
  8949. };
  8950. Engine.prototype.setDepthWrite = function (enable) {
  8951. this._depthCullingState.depthMask = enable;
  8952. };
  8953. Engine.prototype.setColorWrite = function (enable) {
  8954. this._gl.colorMask(enable, enable, enable, enable);
  8955. };
  8956. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8957. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8958. };
  8959. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8960. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8961. if (this._alphaMode === mode) {
  8962. return;
  8963. }
  8964. switch (mode) {
  8965. case Engine.ALPHA_DISABLE:
  8966. this._alphaState.alphaBlend = false;
  8967. break;
  8968. case Engine.ALPHA_PREMULTIPLIED:
  8969. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8970. this._alphaState.alphaBlend = true;
  8971. break;
  8972. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8973. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8974. this._alphaState.alphaBlend = true;
  8975. break;
  8976. case Engine.ALPHA_COMBINE:
  8977. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8978. this._alphaState.alphaBlend = true;
  8979. break;
  8980. case Engine.ALPHA_ONEONE:
  8981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8982. this._alphaState.alphaBlend = true;
  8983. break;
  8984. case Engine.ALPHA_ADD:
  8985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8986. this._alphaState.alphaBlend = true;
  8987. break;
  8988. case Engine.ALPHA_SUBTRACT:
  8989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8990. this._alphaState.alphaBlend = true;
  8991. break;
  8992. case Engine.ALPHA_MULTIPLY:
  8993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8994. this._alphaState.alphaBlend = true;
  8995. break;
  8996. case Engine.ALPHA_MAXIMIZED:
  8997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8998. this._alphaState.alphaBlend = true;
  8999. break;
  9000. case Engine.ALPHA_INTERPOLATE:
  9001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9002. this._alphaState.alphaBlend = true;
  9003. break;
  9004. case Engine.ALPHA_SCREENMODE:
  9005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9006. this._alphaState.alphaBlend = true;
  9007. break;
  9008. }
  9009. if (!noDepthWriteChange) {
  9010. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9011. }
  9012. this._alphaMode = mode;
  9013. };
  9014. Engine.prototype.getAlphaMode = function () {
  9015. return this._alphaMode;
  9016. };
  9017. Engine.prototype.setAlphaTesting = function (enable) {
  9018. this._alphaTest = enable;
  9019. };
  9020. Engine.prototype.getAlphaTesting = function () {
  9021. return !!this._alphaTest;
  9022. };
  9023. // Textures
  9024. Engine.prototype.wipeCaches = function (bruteForce) {
  9025. if (this.preventCacheWipeBetweenFrames) {
  9026. return;
  9027. }
  9028. this.resetTextureCache();
  9029. this._currentEffect = null;
  9030. // 6/8/2017: deltakosh: Should not be required anymore.
  9031. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9032. if (bruteForce) {
  9033. this._stencilState.reset();
  9034. this._depthCullingState.reset();
  9035. this.setDepthFunctionToLessOrEqual();
  9036. this._alphaState.reset();
  9037. }
  9038. this._cachedVertexBuffers = null;
  9039. this._cachedIndexBuffer = null;
  9040. this._cachedEffectForVertexBuffers = null;
  9041. this._unBindVertexArrayObject();
  9042. this.bindIndexBuffer(null);
  9043. this.bindArrayBuffer(null);
  9044. };
  9045. /**
  9046. * Set the compressed texture format to use, based on the formats you have, and the formats
  9047. * supported by the hardware / browser.
  9048. *
  9049. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9050. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9051. * to API arguments needed to compressed textures. This puts the burden on the container
  9052. * generator to house the arcane code for determining these for current & future formats.
  9053. *
  9054. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9055. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9056. *
  9057. * Note: The result of this call is not taken into account when a texture is base64.
  9058. *
  9059. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9060. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9061. *
  9062. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9063. * @returns The extension selected.
  9064. */
  9065. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9066. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9067. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9068. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9069. return this._textureFormatInUse = this._texturesSupported[i];
  9070. }
  9071. }
  9072. }
  9073. // actively set format to nothing, to allow this to be called more than once
  9074. // and possibly fail the 2nd time
  9075. return this._textureFormatInUse = null;
  9076. };
  9077. /**
  9078. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9079. * @param {string} urlArg- This contains one of the following:
  9080. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9081. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9082. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9083. *
  9084. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9085. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9086. * @param {Scene} scene- Needed for loading to the correct scene.
  9087. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9088. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9089. * @param {callback} onError- Optional callback to be called upon failure.
  9090. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9091. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9092. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9093. *
  9094. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9095. */
  9096. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9097. var _this = this;
  9098. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9099. if (onLoad === void 0) { onLoad = null; }
  9100. if (onError === void 0) { onError = null; }
  9101. if (buffer === void 0) { buffer = null; }
  9102. var texture = fallBack ? fallBack : this._gl.createTexture();
  9103. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9104. var fromData = url.substr(0, 5) === "data:";
  9105. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9106. // establish the file extension, if possible
  9107. var lastDot = url.lastIndexOf('.');
  9108. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9109. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9110. if (isDDS) {
  9111. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9112. }
  9113. var isTGA = (extension === ".tga");
  9114. // determine if a ktx file should be substituted
  9115. var isKTX = false;
  9116. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9117. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9118. isKTX = true;
  9119. }
  9120. scene._addPendingData(texture);
  9121. texture.url = url;
  9122. texture.noMipmap = noMipmap;
  9123. texture.references = 1;
  9124. texture.samplingMode = samplingMode;
  9125. texture.onLoadedCallbacks = [];
  9126. if (onLoad) {
  9127. texture.onLoadedCallbacks.push(onLoad);
  9128. }
  9129. if (!fallBack)
  9130. this._loadedTexturesCache.push(texture);
  9131. var onerror = function () {
  9132. scene._removePendingData(texture);
  9133. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9134. if (isKTX) {
  9135. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9136. }
  9137. else if (onError) {
  9138. onError();
  9139. }
  9140. };
  9141. var callback;
  9142. // processing for non-image formats
  9143. if (isKTX || isTGA || isDDS) {
  9144. if (isKTX) {
  9145. callback = function (data) {
  9146. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9147. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9148. ktx.uploadLevels(_this._gl, !noMipmap);
  9149. }, samplingMode);
  9150. };
  9151. }
  9152. else if (isTGA) {
  9153. callback = function (arrayBuffer) {
  9154. var data = new Uint8Array(arrayBuffer);
  9155. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9156. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9157. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9158. }, samplingMode);
  9159. };
  9160. }
  9161. else if (isDDS) {
  9162. callback = function (data) {
  9163. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9164. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9165. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9166. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9167. }, samplingMode);
  9168. };
  9169. }
  9170. if (!buffer) {
  9171. BABYLON.Tools.LoadFile(url, function (data) {
  9172. callback(data);
  9173. }, null, scene.database, true, onerror);
  9174. }
  9175. else {
  9176. callback(buffer);
  9177. }
  9178. // image format processing
  9179. }
  9180. else {
  9181. var onload = function (img) {
  9182. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9183. var isPot = (img.width === potWidth && img.height === potHeight);
  9184. if (!isPot) {
  9185. _this._prepareWorkingCanvas();
  9186. _this._workingCanvas.width = potWidth;
  9187. _this._workingCanvas.height = potHeight;
  9188. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9189. _this._workingContext.imageSmoothingEnabled = false;
  9190. _this._workingContext.mozImageSmoothingEnabled = false;
  9191. _this._workingContext.oImageSmoothingEnabled = false;
  9192. _this._workingContext.webkitImageSmoothingEnabled = false;
  9193. _this._workingContext.msImageSmoothingEnabled = false;
  9194. }
  9195. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9196. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9197. _this._workingContext.imageSmoothingEnabled = true;
  9198. _this._workingContext.mozImageSmoothingEnabled = true;
  9199. _this._workingContext.oImageSmoothingEnabled = true;
  9200. _this._workingContext.webkitImageSmoothingEnabled = true;
  9201. _this._workingContext.msImageSmoothingEnabled = true;
  9202. }
  9203. }
  9204. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9205. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9206. }, samplingMode);
  9207. };
  9208. if (!fromData || isBase64)
  9209. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9210. else if (buffer instanceof Array || typeof buffer === "string")
  9211. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9212. else
  9213. onload(buffer);
  9214. }
  9215. return texture;
  9216. };
  9217. Engine.prototype._getInternalFormat = function (format) {
  9218. var internalFormat = this._gl.RGBA;
  9219. switch (format) {
  9220. case Engine.TEXTUREFORMAT_ALPHA:
  9221. internalFormat = this._gl.ALPHA;
  9222. break;
  9223. case Engine.TEXTUREFORMAT_LUMINANCE:
  9224. internalFormat = this._gl.LUMINANCE;
  9225. break;
  9226. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9227. internalFormat = this._gl.LUMINANCE_ALPHA;
  9228. break;
  9229. case Engine.TEXTUREFORMAT_RGB:
  9230. internalFormat = this._gl.RGB;
  9231. break;
  9232. case Engine.TEXTUREFORMAT_RGBA:
  9233. internalFormat = this._gl.RGBA;
  9234. break;
  9235. }
  9236. return internalFormat;
  9237. };
  9238. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9239. if (compression === void 0) { compression = null; }
  9240. var internalFormat = this._getInternalFormat(format);
  9241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9243. if (texture._width % 4 !== 0) {
  9244. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9245. }
  9246. if (compression) {
  9247. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9248. }
  9249. else {
  9250. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9251. }
  9252. if (texture.generateMipMaps) {
  9253. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9254. }
  9255. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9256. this.resetTextureCache();
  9257. texture.isReady = true;
  9258. };
  9259. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9260. if (compression === void 0) { compression = null; }
  9261. var texture = this._gl.createTexture();
  9262. texture._baseWidth = width;
  9263. texture._baseHeight = height;
  9264. texture._width = width;
  9265. texture._height = height;
  9266. texture.references = 1;
  9267. this.updateRawTexture(texture, data, format, invertY, compression);
  9268. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9269. // Filters
  9270. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9271. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9272. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9273. if (generateMipMaps) {
  9274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9275. }
  9276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9277. texture.samplingMode = samplingMode;
  9278. this._loadedTexturesCache.push(texture);
  9279. return texture;
  9280. };
  9281. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9282. var texture = this._gl.createTexture();
  9283. texture._baseWidth = width;
  9284. texture._baseHeight = height;
  9285. if (generateMipMaps) {
  9286. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9287. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9288. }
  9289. this.resetTextureCache();
  9290. texture._width = width;
  9291. texture._height = height;
  9292. texture.isReady = false;
  9293. texture.generateMipMaps = generateMipMaps;
  9294. texture.references = 1;
  9295. texture.samplingMode = samplingMode;
  9296. this.updateTextureSamplingMode(samplingMode, texture);
  9297. this._loadedTexturesCache.push(texture);
  9298. return texture;
  9299. };
  9300. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9301. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9302. if (texture.isCube) {
  9303. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9305. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9307. }
  9308. else {
  9309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9310. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9312. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9313. }
  9314. texture.samplingMode = samplingMode;
  9315. };
  9316. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9317. if (premulAlpha === void 0) { premulAlpha = false; }
  9318. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9319. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9320. if (premulAlpha) {
  9321. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9322. }
  9323. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9325. if (texture.generateMipMaps) {
  9326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9327. }
  9328. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9329. if (premulAlpha) {
  9330. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9331. }
  9332. this.resetTextureCache();
  9333. texture.isReady = true;
  9334. };
  9335. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9336. if (texture._isDisabled) {
  9337. return;
  9338. }
  9339. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9340. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9341. try {
  9342. // Testing video texture support
  9343. if (this._videoTextureSupported === undefined) {
  9344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9345. if (this._gl.getError() !== 0) {
  9346. this._videoTextureSupported = false;
  9347. }
  9348. else {
  9349. this._videoTextureSupported = true;
  9350. }
  9351. }
  9352. // Copy video through the current working canvas if video texture is not supported
  9353. if (!this._videoTextureSupported) {
  9354. if (!texture._workingCanvas) {
  9355. texture._workingCanvas = document.createElement("canvas");
  9356. texture._workingContext = texture._workingCanvas.getContext("2d");
  9357. texture._workingCanvas.width = texture._width;
  9358. texture._workingCanvas.height = texture._height;
  9359. }
  9360. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9361. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9362. }
  9363. else {
  9364. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9365. }
  9366. if (texture.generateMipMaps) {
  9367. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9368. }
  9369. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9370. this.resetTextureCache();
  9371. texture.isReady = true;
  9372. }
  9373. catch (ex) {
  9374. // Something unexpected
  9375. // Let's disable the texture
  9376. texture._isDisabled = true;
  9377. }
  9378. };
  9379. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9380. // old version had a "generateMipMaps" arg instead of options.
  9381. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9382. // in the same way, generateDepthBuffer is defaulted to true
  9383. var generateMipMaps = false;
  9384. var generateDepthBuffer = true;
  9385. var generateStencilBuffer = false;
  9386. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9387. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9388. if (options !== undefined) {
  9389. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9390. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9391. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9392. type = options.type === undefined ? type : options.type;
  9393. if (options.samplingMode !== undefined) {
  9394. samplingMode = options.samplingMode;
  9395. }
  9396. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9397. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9398. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9399. }
  9400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9401. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9402. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9403. }
  9404. }
  9405. var gl = this._gl;
  9406. var texture = gl.createTexture();
  9407. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9408. var width = size.width || size;
  9409. var height = size.height || size;
  9410. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9411. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9412. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9413. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9414. }
  9415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9419. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9420. // Create the framebuffer
  9421. var framebuffer = gl.createFramebuffer();
  9422. this.bindUnboundFramebuffer(framebuffer);
  9423. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9424. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9425. if (generateMipMaps) {
  9426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9427. }
  9428. // Unbind
  9429. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9430. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9431. this.bindUnboundFramebuffer(null);
  9432. texture._framebuffer = framebuffer;
  9433. texture._baseWidth = width;
  9434. texture._baseHeight = height;
  9435. texture._width = width;
  9436. texture._height = height;
  9437. texture.isReady = true;
  9438. texture.samples = 1;
  9439. texture.generateMipMaps = generateMipMaps;
  9440. texture.references = 1;
  9441. texture.samplingMode = samplingMode;
  9442. texture.type = type;
  9443. texture._generateDepthBuffer = generateDepthBuffer;
  9444. texture._generateStencilBuffer = generateStencilBuffer;
  9445. this.resetTextureCache();
  9446. this._loadedTexturesCache.push(texture);
  9447. return texture;
  9448. };
  9449. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9450. var generateMipMaps = false;
  9451. var generateDepthBuffer = true;
  9452. var generateStencilBuffer = false;
  9453. var generateDepthTexture = false;
  9454. var textureCount = 1;
  9455. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9456. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9457. var types = [], samplingModes = [];
  9458. if (options !== undefined) {
  9459. generateMipMaps = options.generateMipMaps;
  9460. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9461. generateStencilBuffer = options.generateStencilBuffer;
  9462. generateDepthTexture = options.generateDepthTexture;
  9463. textureCount = options.textureCount || 1;
  9464. if (options.types) {
  9465. types = options.types;
  9466. }
  9467. if (options.samplingModes) {
  9468. samplingModes = options.samplingModes;
  9469. }
  9470. }
  9471. var gl = this._gl;
  9472. // Create the framebuffer
  9473. var framebuffer = gl.createFramebuffer();
  9474. this.bindUnboundFramebuffer(framebuffer);
  9475. var width = size.width || size;
  9476. var height = size.height || size;
  9477. var textures = [];
  9478. var attachments = [];
  9479. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9480. for (var i = 0; i < textureCount; i++) {
  9481. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9482. var type = types[i] || defaultType;
  9483. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9484. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9485. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9486. }
  9487. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9488. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9489. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9490. }
  9491. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9492. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9493. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9494. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9495. }
  9496. var texture = gl.createTexture();
  9497. var attachment = gl["COLOR_ATTACHMENT" + i];
  9498. textures.push(texture);
  9499. attachments.push(attachment);
  9500. gl.activeTexture(gl["TEXTURE" + i]);
  9501. gl.bindTexture(gl.TEXTURE_2D, texture);
  9502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9503. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9504. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9506. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9507. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9508. if (generateMipMaps) {
  9509. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9510. }
  9511. // Unbind
  9512. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9513. texture._framebuffer = framebuffer;
  9514. texture._depthStencilBuffer = depthStencilBuffer;
  9515. texture._baseWidth = width;
  9516. texture._baseHeight = height;
  9517. texture._width = width;
  9518. texture._height = height;
  9519. texture.isReady = true;
  9520. texture.samples = 1;
  9521. texture.generateMipMaps = generateMipMaps;
  9522. texture.references = 1;
  9523. texture.samplingMode = samplingMode;
  9524. texture.type = type;
  9525. texture._generateDepthBuffer = generateDepthBuffer;
  9526. texture._generateStencilBuffer = generateStencilBuffer;
  9527. this._loadedTexturesCache.push(texture);
  9528. }
  9529. if (generateDepthTexture) {
  9530. // Depth texture
  9531. var depthTexture = gl.createTexture();
  9532. gl.activeTexture(gl.TEXTURE0);
  9533. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9535. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9536. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9537. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9538. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9539. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9540. depthTexture._framebuffer = framebuffer;
  9541. depthTexture._baseWidth = width;
  9542. depthTexture._baseHeight = height;
  9543. depthTexture._width = width;
  9544. depthTexture._height = height;
  9545. depthTexture.isReady = true;
  9546. depthTexture.samples = 1;
  9547. depthTexture.generateMipMaps = generateMipMaps;
  9548. depthTexture.references = 1;
  9549. depthTexture.samplingMode = gl.NEAREST;
  9550. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9551. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9552. textures.push(depthTexture);
  9553. this._loadedTexturesCache.push(depthTexture);
  9554. }
  9555. gl.drawBuffers(attachments);
  9556. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9557. this.bindUnboundFramebuffer(null);
  9558. this.resetTextureCache();
  9559. return textures;
  9560. };
  9561. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9562. if (samples === void 0) { samples = 1; }
  9563. var depthStencilBuffer = null;
  9564. var gl = this._gl;
  9565. // Create the depth/stencil buffer
  9566. if (generateStencilBuffer) {
  9567. depthStencilBuffer = gl.createRenderbuffer();
  9568. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9569. if (samples > 1) {
  9570. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9571. }
  9572. else {
  9573. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9574. }
  9575. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9576. }
  9577. else if (generateDepthBuffer) {
  9578. depthStencilBuffer = gl.createRenderbuffer();
  9579. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9580. if (samples > 1) {
  9581. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9582. }
  9583. else {
  9584. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9585. }
  9586. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9587. }
  9588. return depthStencilBuffer;
  9589. };
  9590. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9591. if (this.webGLVersion < 2) {
  9592. return 1;
  9593. }
  9594. if (texture.samples === samples) {
  9595. return samples;
  9596. }
  9597. var gl = this._gl;
  9598. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9599. // Dispose previous render buffers
  9600. if (texture._depthStencilBuffer) {
  9601. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9602. }
  9603. if (texture._MSAAFramebuffer) {
  9604. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9605. }
  9606. if (texture._MSAARenderBuffer) {
  9607. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9608. }
  9609. if (samples > 1) {
  9610. texture._MSAAFramebuffer = gl.createFramebuffer();
  9611. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9612. var colorRenderbuffer = gl.createRenderbuffer();
  9613. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9614. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9615. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9616. texture._MSAARenderBuffer = colorRenderbuffer;
  9617. }
  9618. else {
  9619. this.bindUnboundFramebuffer(texture._framebuffer);
  9620. }
  9621. texture.samples = samples;
  9622. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9623. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9624. this.bindUnboundFramebuffer(null);
  9625. return samples;
  9626. };
  9627. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9628. var gl = this._gl;
  9629. var texture = gl.createTexture();
  9630. var generateMipMaps = true;
  9631. var generateDepthBuffer = true;
  9632. var generateStencilBuffer = false;
  9633. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9634. if (options !== undefined) {
  9635. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9636. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9637. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9638. if (options.samplingMode !== undefined) {
  9639. samplingMode = options.samplingMode;
  9640. }
  9641. }
  9642. texture.isCube = true;
  9643. texture.references = 1;
  9644. texture.generateMipMaps = generateMipMaps;
  9645. texture.references = 1;
  9646. texture.samples = 1;
  9647. texture.samplingMode = samplingMode;
  9648. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9649. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9650. for (var face = 0; face < 6; face++) {
  9651. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9652. }
  9653. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9654. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9655. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9656. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9657. // Create the framebuffer
  9658. var framebuffer = gl.createFramebuffer();
  9659. this.bindUnboundFramebuffer(framebuffer);
  9660. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9661. // Mipmaps
  9662. if (texture.generateMipMaps) {
  9663. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9664. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9665. }
  9666. // Unbind
  9667. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9668. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9669. this.bindUnboundFramebuffer(null);
  9670. texture._framebuffer = framebuffer;
  9671. texture._width = size;
  9672. texture._height = size;
  9673. texture.isReady = true;
  9674. this.resetTextureCache();
  9675. this._loadedTexturesCache.push(texture);
  9676. return texture;
  9677. };
  9678. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9679. var _this = this;
  9680. if (onLoad === void 0) { onLoad = null; }
  9681. if (onError === void 0) { onError = null; }
  9682. var gl = this._gl;
  9683. var texture = gl.createTexture();
  9684. texture.isCube = true;
  9685. texture.url = rootUrl;
  9686. texture.references = 1;
  9687. texture.onLoadedCallbacks = [];
  9688. var isKTX = false;
  9689. var lastDot = rootUrl.lastIndexOf('.');
  9690. var extension = rootUrl.substring(lastDot).toLowerCase();
  9691. if (this._textureFormatInUse) {
  9692. extension = this._textureFormatInUse;
  9693. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9694. isKTX = true;
  9695. }
  9696. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9697. if (isDDS) {
  9698. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9699. }
  9700. if (isKTX) {
  9701. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9702. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9703. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9704. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9705. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9706. ktx.uploadLevels(_this._gl, !noMipmap);
  9707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9709. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9711. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9712. _this.resetTextureCache();
  9713. texture._width = ktx.pixelWidth;
  9714. texture._height = ktx.pixelHeight;
  9715. texture.isReady = true;
  9716. }, null, null, true, onError);
  9717. }
  9718. else if (isDDS) {
  9719. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9720. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9721. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9723. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9724. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9725. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9726. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9727. }
  9728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9732. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9733. _this.resetTextureCache();
  9734. texture._width = info.width;
  9735. texture._height = info.height;
  9736. texture.isReady = true;
  9737. }, null, null, true, onError);
  9738. }
  9739. else {
  9740. cascadeLoad(rootUrl, scene, function (imgs) {
  9741. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9742. var height = width;
  9743. _this._prepareWorkingCanvas();
  9744. _this._workingCanvas.width = width;
  9745. _this._workingCanvas.height = height;
  9746. var faces = [
  9747. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9748. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9749. ];
  9750. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9751. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9752. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9753. for (var index = 0; index < faces.length; index++) {
  9754. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9755. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9756. }
  9757. if (!noMipmap) {
  9758. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9759. }
  9760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9763. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9764. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9765. _this.resetTextureCache();
  9766. texture._width = width;
  9767. texture._height = height;
  9768. texture.isReady = true;
  9769. texture.onLoadedCallbacks.forEach(function (callback) {
  9770. callback();
  9771. });
  9772. if (onLoad) {
  9773. onLoad();
  9774. }
  9775. }, files, onError);
  9776. }
  9777. this._loadedTexturesCache.push(texture);
  9778. return texture;
  9779. };
  9780. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9781. texture._width = width;
  9782. texture._height = height;
  9783. texture._size = width * height;
  9784. texture._baseWidth = width;
  9785. texture._baseHeight = height;
  9786. };
  9787. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9788. if (compression === void 0) { compression = null; }
  9789. if (level === void 0) { level = 0; }
  9790. var gl = this._gl;
  9791. var textureType = this._getWebGLTextureType(type);
  9792. var internalFormat = this._getInternalFormat(format);
  9793. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9794. var needConversion = false;
  9795. if (internalFormat === gl.RGB) {
  9796. internalFormat = gl.RGBA;
  9797. needConversion = true;
  9798. }
  9799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9800. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9801. if (texture._width % 4 !== 0) {
  9802. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9803. }
  9804. var facesIndex = [
  9805. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9806. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9807. ];
  9808. // Data are known to be in +X +Y +Z -X -Y -Z
  9809. for (var index = 0; index < facesIndex.length; index++) {
  9810. var faceData = data[index];
  9811. if (compression) {
  9812. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9813. }
  9814. else {
  9815. if (needConversion) {
  9816. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9817. }
  9818. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9819. }
  9820. }
  9821. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9822. if (isPot && texture.generateMipMaps && level === 0) {
  9823. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9824. }
  9825. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9826. this.resetTextureCache();
  9827. texture.isReady = true;
  9828. };
  9829. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9830. if (compression === void 0) { compression = null; }
  9831. var gl = this._gl;
  9832. var texture = gl.createTexture();
  9833. texture.isCube = true;
  9834. texture.references = 1;
  9835. var textureType = this._getWebGLTextureType(type);
  9836. var internalFormat = this._getInternalFormat(format);
  9837. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9838. var needConversion = false;
  9839. if (internalFormat === gl.RGB) {
  9840. internalFormat = gl.RGBA;
  9841. needConversion = true;
  9842. }
  9843. var width = size;
  9844. var height = width;
  9845. texture._width = width;
  9846. texture._height = height;
  9847. // Double check on POT to generate Mips.
  9848. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9849. if (!isPot) {
  9850. generateMipMaps = false;
  9851. }
  9852. texture.generateMipMaps = generateMipMaps;
  9853. // Upload data if needed. The texture won t be ready until then.
  9854. if (data) {
  9855. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9856. }
  9857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9858. // Filters
  9859. if (data && generateMipMaps) {
  9860. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9861. }
  9862. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9864. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9865. }
  9866. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9867. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9868. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9869. }
  9870. else {
  9871. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9872. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9874. }
  9875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9877. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9878. this._loadedTexturesCache.push(texture);
  9879. return texture;
  9880. };
  9881. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9882. var _this = this;
  9883. if (onLoad === void 0) { onLoad = null; }
  9884. if (onError === void 0) { onError = null; }
  9885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9886. if (invertY === void 0) { invertY = false; }
  9887. var gl = this._gl;
  9888. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9889. scene._addPendingData(texture);
  9890. texture.url = url;
  9891. var onerror = function () {
  9892. scene._removePendingData(texture);
  9893. if (onError) {
  9894. onError();
  9895. }
  9896. };
  9897. var internalCallback = function (data) {
  9898. var rgbeDataArrays = callback(data);
  9899. var facesIndex = [
  9900. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9901. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9902. ];
  9903. var width = texture._width;
  9904. var height = texture._height;
  9905. if (mipmmapGenerator) {
  9906. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9907. // I ll remove ASAP.
  9908. var textureType = _this._getWebGLTextureType(type);
  9909. var internalFormat = _this._getInternalFormat(format);
  9910. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9911. var needConversion = false;
  9912. if (internalFormat === gl.RGB) {
  9913. internalFormat = gl.RGBA;
  9914. needConversion = true;
  9915. }
  9916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9917. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9918. var arrayTemp = [];
  9919. // Data are known to be in +X +Y +Z -X -Y -Z
  9920. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9921. arrayTemp.push(rgbeDataArrays[0]); // +X
  9922. arrayTemp.push(rgbeDataArrays[3]); // -X
  9923. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9924. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9925. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9926. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9927. var mipData = mipmmapGenerator(arrayTemp);
  9928. // mipData is order in +X -X +Y -Y +Z -Z
  9929. var mipFaces = [0, 2, 4, 1, 3, 5];
  9930. for (var level = 0; level < mipData.length; level++) {
  9931. var mipSize = width >> level;
  9932. for (var mipIndex in mipFaces) {
  9933. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9934. if (needConversion) {
  9935. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9936. }
  9937. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9938. }
  9939. }
  9940. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9941. }
  9942. else {
  9943. texture.generateMipMaps = !noMipmap;
  9944. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9945. }
  9946. texture.isReady = true;
  9947. _this.resetTextureCache();
  9948. scene._removePendingData(texture);
  9949. if (onLoad) {
  9950. onLoad();
  9951. }
  9952. };
  9953. BABYLON.Tools.LoadFile(url, function (data) {
  9954. internalCallback(data);
  9955. }, onerror, scene.database, true);
  9956. return texture;
  9957. };
  9958. ;
  9959. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9960. // Create new RGBA data container.
  9961. var rgbaData;
  9962. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9963. rgbaData = new Float32Array(width * height * 4);
  9964. }
  9965. else {
  9966. rgbaData = new Uint32Array(width * height * 4);
  9967. }
  9968. // Convert each pixel.
  9969. for (var x = 0; x < width; x++) {
  9970. for (var y = 0; y < height; y++) {
  9971. var index = (y * width + x) * 3;
  9972. var newIndex = (y * width + x) * 4;
  9973. // Map Old Value to new value.
  9974. rgbaData[newIndex + 0] = rgbData[index + 0];
  9975. rgbaData[newIndex + 1] = rgbData[index + 1];
  9976. rgbaData[newIndex + 2] = rgbData[index + 2];
  9977. // Add fully opaque alpha channel.
  9978. rgbaData[newIndex + 3] = 1;
  9979. }
  9980. }
  9981. return rgbaData;
  9982. };
  9983. Engine.prototype._releaseFramebufferObjects = function (texture) {
  9984. var gl = this._gl;
  9985. if (texture._framebuffer) {
  9986. gl.deleteFramebuffer(texture._framebuffer);
  9987. texture._framebuffer = null;
  9988. }
  9989. if (texture._depthStencilBuffer) {
  9990. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9991. texture._depthStencilBuffer = null;
  9992. }
  9993. if (texture._MSAAFramebuffer) {
  9994. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9995. texture._MSAAFramebuffer = null;
  9996. }
  9997. if (texture._MSAARenderBuffer) {
  9998. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9999. texture._MSAARenderBuffer = null;
  10000. }
  10001. };
  10002. Engine.prototype._releaseTexture = function (texture) {
  10003. var gl = this._gl;
  10004. this._releaseFramebufferObjects(texture);
  10005. gl.deleteTexture(texture);
  10006. // Unbind channels
  10007. this.unbindAllTextures();
  10008. var index = this._loadedTexturesCache.indexOf(texture);
  10009. if (index !== -1) {
  10010. this._loadedTexturesCache.splice(index, 1);
  10011. }
  10012. };
  10013. Engine.prototype.setProgram = function (program) {
  10014. if (this._currentProgram !== program) {
  10015. this._gl.useProgram(program);
  10016. this._currentProgram = program;
  10017. }
  10018. };
  10019. Engine.prototype.bindSamplers = function (effect) {
  10020. this.setProgram(effect.getProgram());
  10021. var samplers = effect.getSamplers();
  10022. for (var index = 0; index < samplers.length; index++) {
  10023. var uniform = effect.getUniform(samplers[index]);
  10024. this._gl.uniform1i(uniform, index);
  10025. }
  10026. this._currentEffect = null;
  10027. };
  10028. Engine.prototype.activateTexture = function (texture) {
  10029. if (this._activeTexture !== texture) {
  10030. this._gl.activeTexture(texture);
  10031. this._activeTexture = texture;
  10032. }
  10033. };
  10034. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10035. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10036. this._gl.bindTexture(target, texture);
  10037. this._activeTexturesCache[this._activeTexture] = texture;
  10038. }
  10039. };
  10040. Engine.prototype._bindTexture = function (channel, texture) {
  10041. if (channel < 0) {
  10042. return;
  10043. }
  10044. this.activateTexture(this._gl.TEXTURE0 + channel);
  10045. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10046. };
  10047. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10048. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10049. };
  10050. Engine.prototype.unbindAllTextures = function () {
  10051. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10052. this.activateTexture(this._gl["TEXTURE" + channel]);
  10053. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10054. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10055. }
  10056. };
  10057. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10058. if (channel < 0) {
  10059. return;
  10060. }
  10061. this._gl.uniform1i(uniform, channel);
  10062. this._setTexture(channel, texture);
  10063. };
  10064. Engine.prototype._setTexture = function (channel, texture) {
  10065. // Not ready?
  10066. if (!texture) {
  10067. if (this._activeTexturesCache[channel] != null) {
  10068. this.activateTexture(this._gl["TEXTURE" + channel]);
  10069. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10070. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10071. }
  10072. return;
  10073. }
  10074. // Video
  10075. var alreadyActivated = false;
  10076. if (texture.video) {
  10077. this.activateTexture(this._gl["TEXTURE" + channel]);
  10078. alreadyActivated = true;
  10079. texture.update();
  10080. }
  10081. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10082. texture.delayLoad();
  10083. return;
  10084. }
  10085. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10086. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10087. if (this._activeTexturesCache[channel] === internalTexture) {
  10088. return;
  10089. }
  10090. if (!alreadyActivated) {
  10091. this.activateTexture(this._gl["TEXTURE" + channel]);
  10092. }
  10093. if (internalTexture.isCube) {
  10094. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10095. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10096. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10097. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10098. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10099. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10100. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10101. }
  10102. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10103. }
  10104. else {
  10105. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10106. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10107. internalTexture._cachedWrapU = texture.wrapU;
  10108. switch (texture.wrapU) {
  10109. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10110. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10111. break;
  10112. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10113. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10114. break;
  10115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10116. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10117. break;
  10118. }
  10119. }
  10120. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10121. internalTexture._cachedWrapV = texture.wrapV;
  10122. switch (texture.wrapV) {
  10123. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10124. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10125. break;
  10126. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10127. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10128. break;
  10129. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10130. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10131. break;
  10132. }
  10133. }
  10134. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10135. }
  10136. };
  10137. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10138. if (channel < 0) {
  10139. return;
  10140. }
  10141. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10142. this._textureUnits = new Int32Array(textures.length);
  10143. }
  10144. for (var i = 0; i < textures.length; i++) {
  10145. this._textureUnits[i] = channel + i;
  10146. }
  10147. this._gl.uniform1iv(uniform, this._textureUnits);
  10148. for (var index = 0; index < textures.length; index++) {
  10149. this._setTexture(channel + index, textures[index]);
  10150. }
  10151. };
  10152. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10153. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10154. var value = texture.anisotropicFilteringLevel;
  10155. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10156. value = 1;
  10157. }
  10158. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10159. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10160. texture._cachedAnisotropicFilteringLevel = value;
  10161. }
  10162. };
  10163. Engine.prototype.readPixels = function (x, y, width, height) {
  10164. var data = new Uint8Array(height * width * 4);
  10165. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10166. return data;
  10167. };
  10168. /**
  10169. * Add an externaly attached data from its key.
  10170. * This method call will fail and return false, if such key already exists.
  10171. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10172. * @param key the unique key that identifies the data
  10173. * @param data the data object to associate to the key for this Engine instance
  10174. * @return true if no such key were already present and the data was added successfully, false otherwise
  10175. */
  10176. Engine.prototype.addExternalData = function (key, data) {
  10177. if (!this._externalData) {
  10178. this._externalData = new BABYLON.StringDictionary();
  10179. }
  10180. return this._externalData.add(key, data);
  10181. };
  10182. /**
  10183. * Get an externaly attached data from its key
  10184. * @param key the unique key that identifies the data
  10185. * @return the associated data, if present (can be null), or undefined if not present
  10186. */
  10187. Engine.prototype.getExternalData = function (key) {
  10188. if (!this._externalData) {
  10189. this._externalData = new BABYLON.StringDictionary();
  10190. }
  10191. return this._externalData.get(key);
  10192. };
  10193. /**
  10194. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10195. * @param key the unique key that identifies the data
  10196. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10197. * @return the associated data, can be null if the factory returned null.
  10198. */
  10199. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10200. if (!this._externalData) {
  10201. this._externalData = new BABYLON.StringDictionary();
  10202. }
  10203. return this._externalData.getOrAddWithFactory(key, factory);
  10204. };
  10205. /**
  10206. * Remove an externaly attached data from the Engine instance
  10207. * @param key the unique key that identifies the data
  10208. * @return true if the data was successfully removed, false if it doesn't exist
  10209. */
  10210. Engine.prototype.removeExternalData = function (key) {
  10211. if (!this._externalData) {
  10212. this._externalData = new BABYLON.StringDictionary();
  10213. }
  10214. return this._externalData.remove(key);
  10215. };
  10216. Engine.prototype.releaseInternalTexture = function (texture) {
  10217. if (!texture) {
  10218. return;
  10219. }
  10220. texture.references--;
  10221. // Final reference ?
  10222. if (texture.references === 0) {
  10223. var texturesCache = this.getLoadedTexturesCache();
  10224. var index = texturesCache.indexOf(texture);
  10225. if (index > -1) {
  10226. texturesCache.splice(index, 1);
  10227. }
  10228. this._releaseTexture(texture);
  10229. }
  10230. };
  10231. Engine.prototype.unbindAllAttributes = function () {
  10232. if (this._mustWipeVertexAttributes) {
  10233. this._mustWipeVertexAttributes = false;
  10234. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10235. this._gl.disableVertexAttribArray(i);
  10236. this._vertexAttribArraysEnabled[i] = false;
  10237. this._currentBufferPointers[i] = null;
  10238. }
  10239. return;
  10240. }
  10241. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10242. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10243. continue;
  10244. }
  10245. this._gl.disableVertexAttribArray(i);
  10246. this._vertexAttribArraysEnabled[i] = false;
  10247. this._currentBufferPointers[i] = null;
  10248. }
  10249. };
  10250. Engine.prototype.releaseEffects = function () {
  10251. for (var name in this._compiledEffects) {
  10252. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10253. }
  10254. this._compiledEffects = {};
  10255. };
  10256. // Dispose
  10257. Engine.prototype.dispose = function () {
  10258. this.hideLoadingUI();
  10259. this.stopRenderLoop();
  10260. // Empty texture
  10261. if (this._emptyTexture) {
  10262. this._releaseTexture(this._emptyTexture);
  10263. this._emptyTexture = null;
  10264. }
  10265. if (this._emptyCubeTexture) {
  10266. this._releaseTexture(this._emptyCubeTexture);
  10267. this._emptyCubeTexture = null;
  10268. }
  10269. // Release scenes
  10270. while (this.scenes.length) {
  10271. this.scenes[0].dispose();
  10272. }
  10273. // Release audio engine
  10274. if (Engine.audioEngine) {
  10275. Engine.audioEngine.dispose();
  10276. }
  10277. // Release effects
  10278. this.releaseEffects();
  10279. // Unbind
  10280. this.unbindAllAttributes();
  10281. if (this._dummyFramebuffer) {
  10282. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10283. }
  10284. this._gl = null;
  10285. //WebVR
  10286. this.disableVR();
  10287. // Events
  10288. window.removeEventListener("blur", this._onBlur);
  10289. window.removeEventListener("focus", this._onFocus);
  10290. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10291. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10292. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10293. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10294. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10295. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10296. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10297. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10298. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10299. // Remove from Instances
  10300. var index = Engine.Instances.indexOf(this);
  10301. if (index >= 0) {
  10302. Engine.Instances.splice(index, 1);
  10303. }
  10304. };
  10305. // Loading screen
  10306. Engine.prototype.displayLoadingUI = function () {
  10307. var loadingScreen = this.loadingScreen;
  10308. if (loadingScreen) {
  10309. loadingScreen.displayLoadingUI();
  10310. }
  10311. };
  10312. Engine.prototype.hideLoadingUI = function () {
  10313. var loadingScreen = this.loadingScreen;
  10314. if (loadingScreen) {
  10315. loadingScreen.hideLoadingUI();
  10316. }
  10317. };
  10318. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10319. get: function () {
  10320. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10321. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10322. return this._loadingScreen;
  10323. },
  10324. set: function (loadingScreen) {
  10325. this._loadingScreen = loadingScreen;
  10326. },
  10327. enumerable: true,
  10328. configurable: true
  10329. });
  10330. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10331. set: function (text) {
  10332. this.loadingScreen.loadingUIText = text;
  10333. },
  10334. enumerable: true,
  10335. configurable: true
  10336. });
  10337. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10338. set: function (color) {
  10339. this.loadingScreen.loadingUIBackgroundColor = color;
  10340. },
  10341. enumerable: true,
  10342. configurable: true
  10343. });
  10344. Engine.prototype.attachContextLostEvent = function (callback) {
  10345. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10346. };
  10347. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10348. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10349. };
  10350. Engine.prototype.getVertexShaderSource = function (program) {
  10351. var shaders = this._gl.getAttachedShaders(program);
  10352. return this._gl.getShaderSource(shaders[0]);
  10353. };
  10354. Engine.prototype.getFragmentShaderSource = function (program) {
  10355. var shaders = this._gl.getAttachedShaders(program);
  10356. return this._gl.getShaderSource(shaders[1]);
  10357. };
  10358. Engine.prototype.getError = function () {
  10359. return this._gl.getError();
  10360. };
  10361. // FPS
  10362. Engine.prototype.getFps = function () {
  10363. return this.fps;
  10364. };
  10365. Engine.prototype.getDeltaTime = function () {
  10366. return this.deltaTime;
  10367. };
  10368. Engine.prototype._measureFps = function () {
  10369. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10370. var length = this.previousFramesDuration.length;
  10371. if (length >= 2) {
  10372. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10373. }
  10374. if (length >= this.fpsRange) {
  10375. if (length > this.fpsRange) {
  10376. this.previousFramesDuration.splice(0, 1);
  10377. length = this.previousFramesDuration.length;
  10378. }
  10379. var sum = 0;
  10380. for (var id = 0; id < length - 1; id++) {
  10381. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10382. }
  10383. this.fps = 1000.0 / (sum / (length - 1));
  10384. }
  10385. };
  10386. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10387. if (faceIndex === void 0) { faceIndex = -1; }
  10388. var gl = this._gl;
  10389. if (!this._dummyFramebuffer) {
  10390. this._dummyFramebuffer = gl.createFramebuffer();
  10391. }
  10392. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10393. if (faceIndex > -1) {
  10394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  10395. }
  10396. else {
  10397. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10398. }
  10399. var readFormat = gl.RGBA;
  10400. var readType = gl.UNSIGNED_BYTE;
  10401. var buffer = new Uint8Array(4 * width * height);
  10402. gl.readPixels(0, 0, width, height, readFormat, readType, buffer);
  10403. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10404. return buffer;
  10405. };
  10406. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10407. if (this._webGLVersion > 1) {
  10408. return this._caps.colorBufferFloat;
  10409. }
  10410. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10411. };
  10412. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10413. if (this._webGLVersion > 1) {
  10414. return this._caps.colorBufferFloat;
  10415. }
  10416. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10417. };
  10418. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10419. Engine.prototype._canRenderToFramebuffer = function (type) {
  10420. var gl = this._gl;
  10421. //clear existing errors
  10422. while (gl.getError() !== gl.NO_ERROR) { }
  10423. var successful = true;
  10424. var texture = gl.createTexture();
  10425. gl.bindTexture(gl.TEXTURE_2D, texture);
  10426. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10427. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10429. var fb = gl.createFramebuffer();
  10430. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10431. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10432. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10433. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10434. successful = successful && (gl.getError() === gl.NO_ERROR);
  10435. //try render by clearing frame buffer's color buffer
  10436. if (successful) {
  10437. gl.clear(gl.COLOR_BUFFER_BIT);
  10438. successful = successful && (gl.getError() === gl.NO_ERROR);
  10439. }
  10440. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10441. if (successful) {
  10442. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10443. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10444. var readFormat = gl.RGBA;
  10445. var readType = gl.UNSIGNED_BYTE;
  10446. var buffer = new Uint8Array(4);
  10447. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10448. successful = successful && (gl.getError() === gl.NO_ERROR);
  10449. }
  10450. //clean up
  10451. gl.deleteTexture(texture);
  10452. gl.deleteFramebuffer(fb);
  10453. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10454. //clear accumulated errors
  10455. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10456. return successful;
  10457. };
  10458. Engine.prototype._getWebGLTextureType = function (type) {
  10459. if (type === Engine.TEXTURETYPE_FLOAT) {
  10460. return this._gl.FLOAT;
  10461. }
  10462. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10463. // Add Half Float Constant.
  10464. return Engine.HALF_FLOAT_OES;
  10465. }
  10466. return this._gl.UNSIGNED_BYTE;
  10467. };
  10468. ;
  10469. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10470. if (this._webGLVersion === 1) {
  10471. return this._gl.RGBA;
  10472. }
  10473. if (type === Engine.TEXTURETYPE_FLOAT) {
  10474. return Engine.RGBA32F;
  10475. }
  10476. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10477. return Engine.RGBA16F;
  10478. }
  10479. return this._gl.RGBA;
  10480. };
  10481. ;
  10482. // Statics
  10483. Engine.isSupported = function () {
  10484. try {
  10485. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10486. if (navigator.isCocoonJS) {
  10487. return true;
  10488. }
  10489. var tempcanvas = document.createElement("canvas");
  10490. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10491. return gl != null && !!window.WebGLRenderingContext;
  10492. }
  10493. catch (e) {
  10494. return false;
  10495. }
  10496. };
  10497. return Engine;
  10498. }());
  10499. Engine.Instances = new Array();
  10500. // Const statics
  10501. Engine._ALPHA_DISABLE = 0;
  10502. Engine._ALPHA_ADD = 1;
  10503. Engine._ALPHA_COMBINE = 2;
  10504. Engine._ALPHA_SUBTRACT = 3;
  10505. Engine._ALPHA_MULTIPLY = 4;
  10506. Engine._ALPHA_MAXIMIZED = 5;
  10507. Engine._ALPHA_ONEONE = 6;
  10508. Engine._ALPHA_PREMULTIPLIED = 7;
  10509. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10510. Engine._ALPHA_INTERPOLATE = 9;
  10511. Engine._ALPHA_SCREENMODE = 10;
  10512. Engine._DELAYLOADSTATE_NONE = 0;
  10513. Engine._DELAYLOADSTATE_LOADED = 1;
  10514. Engine._DELAYLOADSTATE_LOADING = 2;
  10515. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10516. Engine._TEXTUREFORMAT_ALPHA = 0;
  10517. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10518. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10519. Engine._TEXTUREFORMAT_RGB = 4;
  10520. Engine._TEXTUREFORMAT_RGBA = 5;
  10521. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10522. Engine._TEXTURETYPE_FLOAT = 1;
  10523. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10524. // Depht or Stencil test Constants.
  10525. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10526. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  10527. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  10528. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  10529. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  10530. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  10531. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  10532. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  10533. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10534. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10535. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10536. // Stencil Actions Constants.
  10537. Engine._KEEP = 0x1E00;
  10538. Engine._REPLACE = 0x1E01;
  10539. Engine._INCR = 0x1E02;
  10540. Engine._DECR = 0x1E03;
  10541. Engine._INVERT = 0x150A;
  10542. Engine._INCR_WRAP = 0x8507;
  10543. Engine._DECR_WRAP = 0x8508;
  10544. // Texture rescaling mode
  10545. Engine._SCALEMODE_FLOOR = 1;
  10546. Engine._SCALEMODE_NEAREST = 2;
  10547. Engine._SCALEMODE_CEILING = 3;
  10548. // Updatable statics so stick with vars here
  10549. Engine.CollisionsEpsilon = 0.001;
  10550. Engine.CodeRepository = "src/";
  10551. Engine.ShadersRepository = "src/Shaders/";
  10552. BABYLON.Engine = Engine;
  10553. })(BABYLON || (BABYLON = {}));
  10554. //# sourceMappingURL=babylon.engine.js.map
  10555. /// <reference path="Tools\babylon.decorators.ts" />
  10556. var BABYLON;
  10557. (function (BABYLON) {
  10558. /**
  10559. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10560. */
  10561. var Node = (function () {
  10562. /**
  10563. * @constructor
  10564. * @param {string} name - the name and id to be given to this node
  10565. * @param {BABYLON.Scene} the scene this node will be added to
  10566. */
  10567. function Node(name, scene) {
  10568. this.state = "";
  10569. this.metadata = null;
  10570. this.doNotSerialize = false;
  10571. this.animations = new Array();
  10572. this._ranges = {};
  10573. this._childrenFlag = -1;
  10574. this._isEnabled = true;
  10575. this._isReady = true;
  10576. this._currentRenderId = -1;
  10577. this._parentRenderId = -1;
  10578. /**
  10579. * An event triggered when the mesh is disposed.
  10580. * @type {BABYLON.Observable}
  10581. */
  10582. this.onDisposeObservable = new BABYLON.Observable();
  10583. this.name = name;
  10584. this.id = name;
  10585. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10586. this._initCache();
  10587. }
  10588. Object.defineProperty(Node.prototype, "parent", {
  10589. get: function () {
  10590. return this._parentNode;
  10591. },
  10592. set: function (parent) {
  10593. if (this._parentNode === parent) {
  10594. return;
  10595. }
  10596. if (this._parentNode) {
  10597. var index = this._parentNode._children.indexOf(this);
  10598. if (index !== -1) {
  10599. this._parentNode._children.splice(index, 1);
  10600. }
  10601. }
  10602. this._parentNode = parent;
  10603. if (this._parentNode) {
  10604. if (!this._parentNode._children) {
  10605. this._parentNode._children = new Array();
  10606. }
  10607. this._parentNode._children.push(this);
  10608. }
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Node.prototype.getClassName = function () {
  10614. return "Node";
  10615. };
  10616. Object.defineProperty(Node.prototype, "onDispose", {
  10617. set: function (callback) {
  10618. if (this._onDisposeObserver) {
  10619. this.onDisposeObservable.remove(this._onDisposeObserver);
  10620. }
  10621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. Node.prototype.getScene = function () {
  10627. return this._scene;
  10628. };
  10629. Node.prototype.getEngine = function () {
  10630. return this._scene.getEngine();
  10631. };
  10632. // override it in derived class
  10633. Node.prototype.getWorldMatrix = function () {
  10634. return BABYLON.Matrix.Identity();
  10635. };
  10636. // override it in derived class if you add new variables to the cache
  10637. // and call the parent class method
  10638. Node.prototype._initCache = function () {
  10639. this._cache = {};
  10640. this._cache.parent = undefined;
  10641. };
  10642. Node.prototype.updateCache = function (force) {
  10643. if (!force && this.isSynchronized())
  10644. return;
  10645. this._cache.parent = this.parent;
  10646. this._updateCache();
  10647. };
  10648. // override it in derived class if you add new variables to the cache
  10649. // and call the parent class method if !ignoreParentClass
  10650. Node.prototype._updateCache = function (ignoreParentClass) {
  10651. };
  10652. // override it in derived class if you add new variables to the cache
  10653. Node.prototype._isSynchronized = function () {
  10654. return true;
  10655. };
  10656. Node.prototype._markSyncedWithParent = function () {
  10657. this._parentRenderId = this.parent._currentRenderId;
  10658. };
  10659. Node.prototype.isSynchronizedWithParent = function () {
  10660. if (!this.parent) {
  10661. return true;
  10662. }
  10663. if (this._parentRenderId !== this.parent._currentRenderId) {
  10664. return false;
  10665. }
  10666. return this.parent.isSynchronized();
  10667. };
  10668. Node.prototype.isSynchronized = function (updateCache) {
  10669. var check = this.hasNewParent();
  10670. check = check || !this.isSynchronizedWithParent();
  10671. check = check || !this._isSynchronized();
  10672. if (updateCache)
  10673. this.updateCache(true);
  10674. return !check;
  10675. };
  10676. Node.prototype.hasNewParent = function (update) {
  10677. if (this._cache.parent === this.parent)
  10678. return false;
  10679. if (update)
  10680. this._cache.parent = this.parent;
  10681. return true;
  10682. };
  10683. /**
  10684. * Is this node ready to be used/rendered
  10685. * @return {boolean} is it ready
  10686. */
  10687. Node.prototype.isReady = function () {
  10688. return this._isReady;
  10689. };
  10690. /**
  10691. * Is this node enabled.
  10692. * If the node has a parent and is enabled, the parent will be inspected as well.
  10693. * @return {boolean} whether this node (and its parent) is enabled.
  10694. * @see setEnabled
  10695. */
  10696. Node.prototype.isEnabled = function () {
  10697. if (!this._isEnabled) {
  10698. return false;
  10699. }
  10700. if (this.parent) {
  10701. return this.parent.isEnabled();
  10702. }
  10703. return true;
  10704. };
  10705. /**
  10706. * Set the enabled state of this node.
  10707. * @param {boolean} value - the new enabled state
  10708. * @see isEnabled
  10709. */
  10710. Node.prototype.setEnabled = function (value) {
  10711. this._isEnabled = value;
  10712. };
  10713. /**
  10714. * Is this node a descendant of the given node.
  10715. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10716. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10717. * @see parent
  10718. */
  10719. Node.prototype.isDescendantOf = function (ancestor) {
  10720. if (this.parent) {
  10721. if (this.parent === ancestor) {
  10722. return true;
  10723. }
  10724. return this.parent.isDescendantOf(ancestor);
  10725. }
  10726. return false;
  10727. };
  10728. /**
  10729. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10730. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10731. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  10732. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  10733. */
  10734. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10735. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10736. if (!this._children) {
  10737. return;
  10738. }
  10739. for (var index = 0; index < this._children.length; index++) {
  10740. var item = this._children[index];
  10741. if (!predicate || predicate(item)) {
  10742. results.push(item);
  10743. }
  10744. if (!directDescendantsOnly) {
  10745. item._getDescendants(results, false, predicate);
  10746. }
  10747. }
  10748. };
  10749. /**
  10750. * Will return all nodes that have this node as ascendant.
  10751. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  10752. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  10753. * @return {BABYLON.Node[]} all children nodes of all types.
  10754. */
  10755. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10756. var results = [];
  10757. this._getDescendants(results, directDescendantsOnly, predicate);
  10758. return results;
  10759. };
  10760. /**
  10761. * Get all child-meshes of this node.
  10762. */
  10763. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10764. var results = [];
  10765. this._getDescendants(results, directDecendantsOnly, function (node) {
  10766. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10767. });
  10768. return results;
  10769. };
  10770. /**
  10771. * Get all direct children of this node.
  10772. */
  10773. Node.prototype.getChildren = function (predicate) {
  10774. return this.getDescendants(true, predicate);
  10775. };
  10776. Node.prototype._setReady = function (state) {
  10777. if (state === this._isReady) {
  10778. return;
  10779. }
  10780. if (!state) {
  10781. this._isReady = false;
  10782. return;
  10783. }
  10784. this._isReady = true;
  10785. if (this.onReady) {
  10786. this.onReady(this);
  10787. }
  10788. };
  10789. Node.prototype.getAnimationByName = function (name) {
  10790. for (var i = 0; i < this.animations.length; i++) {
  10791. var animation = this.animations[i];
  10792. if (animation.name === name) {
  10793. return animation;
  10794. }
  10795. }
  10796. return null;
  10797. };
  10798. Node.prototype.createAnimationRange = function (name, from, to) {
  10799. // check name not already in use
  10800. if (!this._ranges[name]) {
  10801. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10802. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10803. if (this.animations[i]) {
  10804. this.animations[i].createRange(name, from, to);
  10805. }
  10806. }
  10807. }
  10808. };
  10809. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10810. if (deleteFrames === void 0) { deleteFrames = true; }
  10811. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10812. if (this.animations[i]) {
  10813. this.animations[i].deleteRange(name, deleteFrames);
  10814. }
  10815. }
  10816. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10817. };
  10818. Node.prototype.getAnimationRange = function (name) {
  10819. return this._ranges[name];
  10820. };
  10821. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10822. var range = this.getAnimationRange(name);
  10823. if (!range) {
  10824. return null;
  10825. }
  10826. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10827. };
  10828. Node.prototype.serializeAnimationRanges = function () {
  10829. var serializationRanges = [];
  10830. for (var name in this._ranges) {
  10831. var range = {};
  10832. range.name = name;
  10833. range.from = this._ranges[name].from;
  10834. range.to = this._ranges[name].to;
  10835. serializationRanges.push(range);
  10836. }
  10837. return serializationRanges;
  10838. };
  10839. Node.prototype.dispose = function () {
  10840. this.parent = null;
  10841. // Callback
  10842. this.onDisposeObservable.notifyObservers(this);
  10843. this.onDisposeObservable.clear();
  10844. };
  10845. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10846. if (parsedNode.ranges) {
  10847. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10848. var data = parsedNode.ranges[index];
  10849. node.createAnimationRange(data.name, data.from, data.to);
  10850. }
  10851. }
  10852. };
  10853. return Node;
  10854. }());
  10855. __decorate([
  10856. BABYLON.serialize()
  10857. ], Node.prototype, "name", void 0);
  10858. __decorate([
  10859. BABYLON.serialize()
  10860. ], Node.prototype, "id", void 0);
  10861. __decorate([
  10862. BABYLON.serialize()
  10863. ], Node.prototype, "uniqueId", void 0);
  10864. __decorate([
  10865. BABYLON.serialize()
  10866. ], Node.prototype, "state", void 0);
  10867. __decorate([
  10868. BABYLON.serialize()
  10869. ], Node.prototype, "metadata", void 0);
  10870. BABYLON.Node = Node;
  10871. })(BABYLON || (BABYLON = {}));
  10872. //# sourceMappingURL=babylon.node.js.map
  10873. var BABYLON;
  10874. (function (BABYLON) {
  10875. var BoundingSphere = (function () {
  10876. function BoundingSphere(minimum, maximum) {
  10877. this.minimum = minimum;
  10878. this.maximum = maximum;
  10879. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10880. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10881. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10882. this.radius = distance * 0.5;
  10883. this.centerWorld = BABYLON.Vector3.Zero();
  10884. this._update(BABYLON.Matrix.Identity());
  10885. }
  10886. // Methods
  10887. BoundingSphere.prototype._update = function (world) {
  10888. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10889. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10890. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10891. };
  10892. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10893. for (var i = 0; i < 6; i++) {
  10894. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10895. return false;
  10896. }
  10897. return true;
  10898. };
  10899. BoundingSphere.prototype.intersectsPoint = function (point) {
  10900. var x = this.centerWorld.x - point.x;
  10901. var y = this.centerWorld.y - point.y;
  10902. var z = this.centerWorld.z - point.z;
  10903. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10904. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10905. return false;
  10906. return true;
  10907. };
  10908. // Statics
  10909. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10910. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10911. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10912. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10913. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10914. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10915. return false;
  10916. return true;
  10917. };
  10918. return BoundingSphere;
  10919. }());
  10920. BABYLON.BoundingSphere = BoundingSphere;
  10921. })(BABYLON || (BABYLON = {}));
  10922. //# sourceMappingURL=babylon.boundingSphere.js.map
  10923. var BABYLON;
  10924. (function (BABYLON) {
  10925. var BoundingBox = (function () {
  10926. function BoundingBox(minimum, maximum) {
  10927. this.minimum = minimum;
  10928. this.maximum = maximum;
  10929. this.vectors = new Array();
  10930. this.vectorsWorld = new Array();
  10931. // Bounding vectors
  10932. this.vectors.push(this.minimum.clone());
  10933. this.vectors.push(this.maximum.clone());
  10934. this.vectors.push(this.minimum.clone());
  10935. this.vectors[2].x = this.maximum.x;
  10936. this.vectors.push(this.minimum.clone());
  10937. this.vectors[3].y = this.maximum.y;
  10938. this.vectors.push(this.minimum.clone());
  10939. this.vectors[4].z = this.maximum.z;
  10940. this.vectors.push(this.maximum.clone());
  10941. this.vectors[5].z = this.minimum.z;
  10942. this.vectors.push(this.maximum.clone());
  10943. this.vectors[6].x = this.minimum.x;
  10944. this.vectors.push(this.maximum.clone());
  10945. this.vectors[7].y = this.minimum.y;
  10946. // OBB
  10947. this.center = this.maximum.add(this.minimum).scale(0.5);
  10948. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10949. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10950. // World
  10951. for (var index = 0; index < this.vectors.length; index++) {
  10952. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10953. }
  10954. this.minimumWorld = BABYLON.Vector3.Zero();
  10955. this.maximumWorld = BABYLON.Vector3.Zero();
  10956. this.centerWorld = BABYLON.Vector3.Zero();
  10957. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10958. this._update(BABYLON.Matrix.Identity());
  10959. }
  10960. // Methods
  10961. BoundingBox.prototype.getWorldMatrix = function () {
  10962. return this._worldMatrix;
  10963. };
  10964. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10965. this._worldMatrix.copyFrom(matrix);
  10966. return this;
  10967. };
  10968. BoundingBox.prototype._update = function (world) {
  10969. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10970. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10971. for (var index = 0; index < this.vectors.length; index++) {
  10972. var v = this.vectorsWorld[index];
  10973. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10974. if (v.x < this.minimumWorld.x)
  10975. this.minimumWorld.x = v.x;
  10976. if (v.y < this.minimumWorld.y)
  10977. this.minimumWorld.y = v.y;
  10978. if (v.z < this.minimumWorld.z)
  10979. this.minimumWorld.z = v.z;
  10980. if (v.x > this.maximumWorld.x)
  10981. this.maximumWorld.x = v.x;
  10982. if (v.y > this.maximumWorld.y)
  10983. this.maximumWorld.y = v.y;
  10984. if (v.z > this.maximumWorld.z)
  10985. this.maximumWorld.z = v.z;
  10986. }
  10987. // Extend
  10988. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10989. this.extendSizeWorld.scaleInPlace(0.5);
  10990. // OBB
  10991. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10992. this.centerWorld.scaleInPlace(0.5);
  10993. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10994. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10995. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10996. this._worldMatrix = world;
  10997. };
  10998. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10999. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11000. };
  11001. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11002. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11003. };
  11004. BoundingBox.prototype.intersectsPoint = function (point) {
  11005. var delta = -BABYLON.Epsilon;
  11006. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11007. return false;
  11008. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11009. return false;
  11010. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11011. return false;
  11012. return true;
  11013. };
  11014. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11015. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11016. };
  11017. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11018. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11019. return false;
  11020. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11021. return false;
  11022. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11023. return false;
  11024. return true;
  11025. };
  11026. // Statics
  11027. BoundingBox.Intersects = function (box0, box1) {
  11028. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11029. return false;
  11030. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11031. return false;
  11032. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11033. return false;
  11034. return true;
  11035. };
  11036. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11037. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11038. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11039. return (num <= (sphereRadius * sphereRadius));
  11040. };
  11041. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11042. for (var p = 0; p < 6; p++) {
  11043. for (var i = 0; i < 8; i++) {
  11044. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11045. return false;
  11046. }
  11047. }
  11048. }
  11049. return true;
  11050. };
  11051. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11052. for (var p = 0; p < 6; p++) {
  11053. var inCount = 8;
  11054. for (var i = 0; i < 8; i++) {
  11055. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11056. --inCount;
  11057. }
  11058. else {
  11059. break;
  11060. }
  11061. }
  11062. if (inCount === 0)
  11063. return false;
  11064. }
  11065. return true;
  11066. };
  11067. return BoundingBox;
  11068. }());
  11069. BABYLON.BoundingBox = BoundingBox;
  11070. })(BABYLON || (BABYLON = {}));
  11071. //# sourceMappingURL=babylon.boundingBox.js.map
  11072. var BABYLON;
  11073. (function (BABYLON) {
  11074. var computeBoxExtents = function (axis, box) {
  11075. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11076. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11077. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11078. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11079. var r = r0 + r1 + r2;
  11080. return {
  11081. min: p - r,
  11082. max: p + r
  11083. };
  11084. };
  11085. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11086. var axisOverlap = function (axis, box0, box1) {
  11087. var result0 = computeBoxExtents(axis, box0);
  11088. var result1 = computeBoxExtents(axis, box1);
  11089. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11090. };
  11091. var BoundingInfo = (function () {
  11092. function BoundingInfo(minimum, maximum) {
  11093. this.minimum = minimum;
  11094. this.maximum = maximum;
  11095. this._isLocked = false;
  11096. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11097. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11098. }
  11099. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11100. get: function () {
  11101. return this._isLocked;
  11102. },
  11103. set: function (value) {
  11104. this._isLocked = value;
  11105. },
  11106. enumerable: true,
  11107. configurable: true
  11108. });
  11109. // Methods
  11110. BoundingInfo.prototype.update = function (world) {
  11111. if (this._isLocked) {
  11112. return;
  11113. }
  11114. this.boundingBox._update(world);
  11115. this.boundingSphere._update(world);
  11116. };
  11117. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11118. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11119. return false;
  11120. return this.boundingBox.isInFrustum(frustumPlanes);
  11121. };
  11122. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11123. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11124. };
  11125. BoundingInfo.prototype._checkCollision = function (collider) {
  11126. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11127. };
  11128. BoundingInfo.prototype.intersectsPoint = function (point) {
  11129. if (!this.boundingSphere.centerWorld) {
  11130. return false;
  11131. }
  11132. if (!this.boundingSphere.intersectsPoint(point)) {
  11133. return false;
  11134. }
  11135. if (!this.boundingBox.intersectsPoint(point)) {
  11136. return false;
  11137. }
  11138. return true;
  11139. };
  11140. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11141. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11142. return false;
  11143. }
  11144. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11145. return false;
  11146. }
  11147. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11148. return false;
  11149. }
  11150. if (!precise) {
  11151. return true;
  11152. }
  11153. var box0 = this.boundingBox;
  11154. var box1 = boundingInfo.boundingBox;
  11155. if (!axisOverlap(box0.directions[0], box0, box1))
  11156. return false;
  11157. if (!axisOverlap(box0.directions[1], box0, box1))
  11158. return false;
  11159. if (!axisOverlap(box0.directions[2], box0, box1))
  11160. return false;
  11161. if (!axisOverlap(box1.directions[0], box0, box1))
  11162. return false;
  11163. if (!axisOverlap(box1.directions[1], box0, box1))
  11164. return false;
  11165. if (!axisOverlap(box1.directions[2], box0, box1))
  11166. return false;
  11167. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11168. return false;
  11169. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11170. return false;
  11171. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11172. return false;
  11173. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11174. return false;
  11175. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11176. return false;
  11177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11178. return false;
  11179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11180. return false;
  11181. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11182. return false;
  11183. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11184. return false;
  11185. return true;
  11186. };
  11187. return BoundingInfo;
  11188. }());
  11189. BABYLON.BoundingInfo = BoundingInfo;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.boundingInfo.js.map
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var AbstractMesh = (function (_super) {
  11195. __extends(AbstractMesh, _super);
  11196. // Constructor
  11197. function AbstractMesh(name, scene) {
  11198. var _this = _super.call(this, name, scene) || this;
  11199. _this._facetNb = 0; // facet number
  11200. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11201. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11202. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11203. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11204. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11205. _this._subDiv = {
  11206. max: 1,
  11207. X: 1,
  11208. Y: 1,
  11209. Z: 1
  11210. };
  11211. // Events
  11212. /**
  11213. * An event triggered when this mesh collides with another one
  11214. * @type {BABYLON.Observable}
  11215. */
  11216. _this.onCollideObservable = new BABYLON.Observable();
  11217. /**
  11218. * An event triggered when the collision's position changes
  11219. * @type {BABYLON.Observable}
  11220. */
  11221. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11222. /**
  11223. * An event triggered after the world matrix is updated
  11224. * @type {BABYLON.Observable}
  11225. */
  11226. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11227. // Properties
  11228. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11229. _this.position = BABYLON.Vector3.Zero();
  11230. _this._rotation = BABYLON.Vector3.Zero();
  11231. _this._scaling = BABYLON.Vector3.One();
  11232. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11233. _this.visibility = 1.0;
  11234. _this.alphaIndex = Number.MAX_VALUE;
  11235. _this.infiniteDistance = false;
  11236. _this.isVisible = true;
  11237. _this.isPickable = true;
  11238. _this.showBoundingBox = false;
  11239. _this.showSubMeshesBoundingBox = false;
  11240. _this.isBlocker = false;
  11241. _this.renderingGroupId = 0;
  11242. _this._receiveShadows = false;
  11243. _this.renderOutline = false;
  11244. _this.outlineColor = BABYLON.Color3.Red();
  11245. _this.outlineWidth = 0.02;
  11246. _this.renderOverlay = false;
  11247. _this.overlayColor = BABYLON.Color3.Red();
  11248. _this.overlayAlpha = 0.5;
  11249. _this._hasVertexAlpha = false;
  11250. _this._useVertexColors = true;
  11251. _this._computeBonesUsingShaders = true;
  11252. _this._numBoneInfluencers = 4;
  11253. _this._applyFog = true;
  11254. _this.scalingDeterminant = 1;
  11255. _this.useOctreeForRenderingSelection = true;
  11256. _this.useOctreeForPicking = true;
  11257. _this.useOctreeForCollisions = true;
  11258. _this.layerMask = 0x0FFFFFFF;
  11259. /**
  11260. * True if the mesh must be rendered in any case.
  11261. */
  11262. _this.alwaysSelectAsActiveMesh = false;
  11263. // Collisions
  11264. _this._checkCollisions = false;
  11265. _this._collisionMask = -1;
  11266. _this._collisionGroup = -1;
  11267. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11268. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11269. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11270. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11271. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11272. // Edges
  11273. _this.edgesWidth = 1;
  11274. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11275. // Cache
  11276. _this._localWorld = BABYLON.Matrix.Zero();
  11277. _this._worldMatrix = BABYLON.Matrix.Zero();
  11278. _this._absolutePosition = BABYLON.Vector3.Zero();
  11279. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11280. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11281. _this._isDirty = false;
  11282. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11283. _this._isDisposed = false;
  11284. _this._renderId = 0;
  11285. _this._intersectionsInProgress = new Array();
  11286. _this._isWorldMatrixFrozen = false;
  11287. _this._unIndexed = false;
  11288. _this._lightSources = new Array();
  11289. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11290. if (collidedMesh === void 0) { collidedMesh = null; }
  11291. //TODO move this to the collision coordinator!
  11292. if (_this.getScene().workerCollisions)
  11293. newPosition.multiplyInPlace(_this._collider.radius);
  11294. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11295. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11296. _this.position.addInPlace(_this._diffPositionForCollisions);
  11297. }
  11298. if (collidedMesh) {
  11299. _this.onCollideObservable.notifyObservers(collidedMesh);
  11300. }
  11301. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11302. };
  11303. _this.getScene().addMesh(_this);
  11304. _this._resyncLightSources();
  11305. return _this;
  11306. }
  11307. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11308. get: function () {
  11309. return AbstractMesh._BILLBOARDMODE_NONE;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11315. get: function () {
  11316. return AbstractMesh._BILLBOARDMODE_X;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11322. get: function () {
  11323. return AbstractMesh._BILLBOARDMODE_Y;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11329. get: function () {
  11330. return AbstractMesh._BILLBOARDMODE_Z;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11336. get: function () {
  11337. return AbstractMesh._BILLBOARDMODE_ALL;
  11338. },
  11339. enumerable: true,
  11340. configurable: true
  11341. });
  11342. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11343. /**
  11344. * Read-only : the number of facets in the mesh
  11345. */
  11346. get: function () {
  11347. return this._facetNb;
  11348. },
  11349. enumerable: true,
  11350. configurable: true
  11351. });
  11352. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11353. /**
  11354. * The number (integer) of subdivisions per axis in the partioning space
  11355. */
  11356. get: function () {
  11357. return this._partitioningSubdivisions;
  11358. },
  11359. set: function (nb) {
  11360. this._partitioningSubdivisions = nb;
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11366. /**
  11367. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11368. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11369. */
  11370. get: function () {
  11371. return this._partitioningBBoxRatio;
  11372. },
  11373. set: function (ratio) {
  11374. this._partitioningBBoxRatio = ratio;
  11375. },
  11376. enumerable: true,
  11377. configurable: true
  11378. });
  11379. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11380. /**
  11381. * Read-only boolean : is the feature facetData enabled ?
  11382. */
  11383. get: function () {
  11384. return this._facetDataEnabled;
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11390. set: function (callback) {
  11391. if (this._onCollideObserver) {
  11392. this.onCollideObservable.remove(this._onCollideObserver);
  11393. }
  11394. this._onCollideObserver = this.onCollideObservable.add(callback);
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11400. set: function (callback) {
  11401. if (this._onCollisionPositionChangeObserver) {
  11402. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11403. }
  11404. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11405. },
  11406. enumerable: true,
  11407. configurable: true
  11408. });
  11409. Object.defineProperty(AbstractMesh.prototype, "material", {
  11410. get: function () {
  11411. return this._material;
  11412. },
  11413. set: function (value) {
  11414. if (this._material === value) {
  11415. return;
  11416. }
  11417. this._material = value;
  11418. if (!this.subMeshes) {
  11419. return;
  11420. }
  11421. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11422. var subMesh = _a[_i];
  11423. subMesh.setEffect(null);
  11424. }
  11425. },
  11426. enumerable: true,
  11427. configurable: true
  11428. });
  11429. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11430. get: function () {
  11431. return this._receiveShadows;
  11432. },
  11433. set: function (value) {
  11434. if (this._receiveShadows === value) {
  11435. return;
  11436. }
  11437. this._receiveShadows = value;
  11438. this._markSubMeshesAsLightDirty();
  11439. },
  11440. enumerable: true,
  11441. configurable: true
  11442. });
  11443. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11444. get: function () {
  11445. return this._hasVertexAlpha;
  11446. },
  11447. set: function (value) {
  11448. if (this._hasVertexAlpha === value) {
  11449. return;
  11450. }
  11451. this._hasVertexAlpha = value;
  11452. this._markSubMeshesAsAttributesDirty();
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11458. get: function () {
  11459. return this._useVertexColors;
  11460. },
  11461. set: function (value) {
  11462. if (this._useVertexColors === value) {
  11463. return;
  11464. }
  11465. this._useVertexColors = value;
  11466. this._markSubMeshesAsAttributesDirty();
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11472. get: function () {
  11473. return this._computeBonesUsingShaders;
  11474. },
  11475. set: function (value) {
  11476. if (this._computeBonesUsingShaders === value) {
  11477. return;
  11478. }
  11479. this._computeBonesUsingShaders = value;
  11480. this._markSubMeshesAsAttributesDirty();
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11486. get: function () {
  11487. return this._numBoneInfluencers;
  11488. },
  11489. set: function (value) {
  11490. if (this._numBoneInfluencers === value) {
  11491. return;
  11492. }
  11493. this._numBoneInfluencers = value;
  11494. this._markSubMeshesAsAttributesDirty();
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11500. get: function () {
  11501. return this._applyFog;
  11502. },
  11503. set: function (value) {
  11504. if (this._applyFog === value) {
  11505. return;
  11506. }
  11507. this._applyFog = value;
  11508. this._markSubMeshesAsMiscDirty();
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11514. get: function () {
  11515. return this._collisionMask;
  11516. },
  11517. set: function (mask) {
  11518. this._collisionMask = !isNaN(mask) ? mask : -1;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11524. get: function () {
  11525. return this._collisionGroup;
  11526. },
  11527. set: function (mask) {
  11528. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11529. },
  11530. enumerable: true,
  11531. configurable: true
  11532. });
  11533. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11534. get: function () {
  11535. return null;
  11536. },
  11537. enumerable: true,
  11538. configurable: true
  11539. });
  11540. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11541. get: function () {
  11542. return this._skeleton;
  11543. },
  11544. set: function (value) {
  11545. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11546. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11547. }
  11548. if (value && value.needInitialSkinMatrix) {
  11549. value._registerMeshWithPoseMatrix(this);
  11550. }
  11551. this._skeleton = value;
  11552. if (!this._skeleton) {
  11553. this._bonesTransformMatrices = null;
  11554. }
  11555. this._markSubMeshesAsAttributesDirty();
  11556. },
  11557. enumerable: true,
  11558. configurable: true
  11559. });
  11560. /**
  11561. * Returns the string "AbstractMesh"
  11562. */
  11563. AbstractMesh.prototype.getClassName = function () {
  11564. return "AbstractMesh";
  11565. };
  11566. /**
  11567. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11568. */
  11569. AbstractMesh.prototype.toString = function (fullDetails) {
  11570. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11571. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11572. if (this._skeleton) {
  11573. ret += ", skeleton: " + this._skeleton.name;
  11574. }
  11575. if (fullDetails) {
  11576. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11577. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11578. }
  11579. return ret;
  11580. };
  11581. AbstractMesh.prototype._resyncLightSources = function () {
  11582. this._lightSources.length = 0;
  11583. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11584. var light = _a[_i];
  11585. if (!light.isEnabled()) {
  11586. continue;
  11587. }
  11588. if (light.canAffectMesh(this)) {
  11589. this._lightSources.push(light);
  11590. }
  11591. }
  11592. this._markSubMeshesAsLightDirty();
  11593. };
  11594. AbstractMesh.prototype._resyncLighSource = function (light) {
  11595. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11596. var index = this._lightSources.indexOf(light);
  11597. if (index === -1) {
  11598. if (!isIn) {
  11599. return;
  11600. }
  11601. this._lightSources.push(light);
  11602. }
  11603. else {
  11604. if (isIn) {
  11605. return;
  11606. }
  11607. this._lightSources.splice(index, 1);
  11608. }
  11609. this._markSubMeshesAsLightDirty();
  11610. };
  11611. AbstractMesh.prototype._removeLightSource = function (light) {
  11612. var index = this._lightSources.indexOf(light);
  11613. if (index === -1) {
  11614. return;
  11615. }
  11616. this._lightSources.splice(index, 1);
  11617. };
  11618. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11619. if (!this.subMeshes) {
  11620. return;
  11621. }
  11622. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11623. var subMesh = _a[_i];
  11624. if (subMesh._materialDefines) {
  11625. func(subMesh._materialDefines);
  11626. }
  11627. }
  11628. };
  11629. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11630. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11631. };
  11632. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11633. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11634. };
  11635. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11636. if (!this.subMeshes) {
  11637. return;
  11638. }
  11639. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11640. var subMesh = _a[_i];
  11641. var material = subMesh.getMaterial();
  11642. if (material) {
  11643. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11644. }
  11645. }
  11646. };
  11647. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11648. /**
  11649. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11650. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11651. * Default : (0.0, 0.0, 0.0)
  11652. */
  11653. get: function () {
  11654. return this._rotation;
  11655. },
  11656. set: function (newRotation) {
  11657. this._rotation = newRotation;
  11658. },
  11659. enumerable: true,
  11660. configurable: true
  11661. });
  11662. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11663. /**
  11664. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11665. * Default : (1.0, 1.0, 1.0)
  11666. */
  11667. get: function () {
  11668. return this._scaling;
  11669. },
  11670. set: function (newScaling) {
  11671. this._scaling = newScaling;
  11672. if (this.physicsImpostor) {
  11673. this.physicsImpostor.forceUpdate();
  11674. }
  11675. },
  11676. enumerable: true,
  11677. configurable: true
  11678. });
  11679. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11680. /**
  11681. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11682. * It's null by default.
  11683. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  11684. */
  11685. get: function () {
  11686. return this._rotationQuaternion;
  11687. },
  11688. set: function (quaternion) {
  11689. this._rotationQuaternion = quaternion;
  11690. //reset the rotation vector.
  11691. if (quaternion && this.rotation.length()) {
  11692. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11693. }
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. // Methods
  11699. /**
  11700. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11701. * Returns the AbstractMesh.
  11702. */
  11703. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11704. this._poseMatrix.copyFrom(matrix);
  11705. return this;
  11706. };
  11707. /**
  11708. * Returns the mesh Pose matrix.
  11709. * Returned object : Matrix
  11710. */
  11711. AbstractMesh.prototype.getPoseMatrix = function () {
  11712. return this._poseMatrix;
  11713. };
  11714. /**
  11715. * Disables the mesh edger rendering mode.
  11716. * Returns the AbstractMesh.
  11717. */
  11718. AbstractMesh.prototype.disableEdgesRendering = function () {
  11719. if (this._edgesRenderer !== undefined) {
  11720. this._edgesRenderer.dispose();
  11721. this._edgesRenderer = undefined;
  11722. }
  11723. return this;
  11724. };
  11725. /**
  11726. * Enables the edge rendering mode on the mesh.
  11727. * This mode makes the mesh edges visible.
  11728. * Returns the AbstractMesh.
  11729. */
  11730. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11731. if (epsilon === void 0) { epsilon = 0.95; }
  11732. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11733. this.disableEdgesRendering();
  11734. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11735. return this;
  11736. };
  11737. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11738. /**
  11739. * Returns true if the mesh is blocked. Used by the class Mesh.
  11740. * Returns the boolean `false` by default.
  11741. */
  11742. get: function () {
  11743. return false;
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. /**
  11749. * Returns the mesh itself by default, used by the class Mesh.
  11750. * Returned type : AbstractMesh
  11751. */
  11752. AbstractMesh.prototype.getLOD = function (camera) {
  11753. return this;
  11754. };
  11755. /**
  11756. * Returns 0 by default, used by the class Mesh.
  11757. * Returns an integer.
  11758. */
  11759. AbstractMesh.prototype.getTotalVertices = function () {
  11760. return 0;
  11761. };
  11762. /**
  11763. * Returns null by default, used by the class Mesh.
  11764. * Returned type : integer array
  11765. */
  11766. AbstractMesh.prototype.getIndices = function () {
  11767. return null;
  11768. };
  11769. /**
  11770. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11771. * Returned type : float array or Float32Array
  11772. */
  11773. AbstractMesh.prototype.getVerticesData = function (kind) {
  11774. return null;
  11775. };
  11776. /**
  11777. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11778. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11779. * The `data` are either a numeric array either a Float32Array.
  11780. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11781. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  11782. * Note that a new underlying VertexBuffer object is created each call.
  11783. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11784. *
  11785. * Possible `kind` values :
  11786. * - BABYLON.VertexBuffer.PositionKind
  11787. * - BABYLON.VertexBuffer.UVKind
  11788. * - BABYLON.VertexBuffer.UV2Kind
  11789. * - BABYLON.VertexBuffer.UV3Kind
  11790. * - BABYLON.VertexBuffer.UV4Kind
  11791. * - BABYLON.VertexBuffer.UV5Kind
  11792. * - BABYLON.VertexBuffer.UV6Kind
  11793. * - BABYLON.VertexBuffer.ColorKind
  11794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11798. *
  11799. * Returns the Mesh.
  11800. */
  11801. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11802. return null;
  11803. };
  11804. /**
  11805. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11806. * If the mesh has no geometry, it is simply returned as it is.
  11807. * The `data` are either a numeric array either a Float32Array.
  11808. * No new underlying VertexBuffer object is created.
  11809. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11810. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11811. *
  11812. * Possible `kind` values :
  11813. * - BABYLON.VertexBuffer.PositionKind
  11814. * - BABYLON.VertexBuffer.UVKind
  11815. * - BABYLON.VertexBuffer.UV2Kind
  11816. * - BABYLON.VertexBuffer.UV3Kind
  11817. * - BABYLON.VertexBuffer.UV4Kind
  11818. * - BABYLON.VertexBuffer.UV5Kind
  11819. * - BABYLON.VertexBuffer.UV6Kind
  11820. * - BABYLON.VertexBuffer.ColorKind
  11821. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11822. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11823. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11824. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11825. *
  11826. * Returns the Mesh.
  11827. */
  11828. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11829. return null;
  11830. };
  11831. /**
  11832. * Sets the mesh indices.
  11833. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11834. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11835. * This method creates a new index buffer each call.
  11836. * Returns the Mesh.
  11837. */
  11838. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11839. return null;
  11840. };
  11841. /** Returns false by default, used by the class Mesh.
  11842. * Returns a boolean
  11843. */
  11844. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11845. return false;
  11846. };
  11847. /**
  11848. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11849. * Returns a BoundingInfo
  11850. */
  11851. AbstractMesh.prototype.getBoundingInfo = function () {
  11852. if (this._masterMesh) {
  11853. return this._masterMesh.getBoundingInfo();
  11854. }
  11855. if (!this._boundingInfo) {
  11856. this._updateBoundingInfo();
  11857. }
  11858. return this._boundingInfo;
  11859. };
  11860. /**
  11861. * Sets a mesh new object BoundingInfo.
  11862. * Returns the AbstractMesh.
  11863. */
  11864. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11865. this._boundingInfo = boundingInfo;
  11866. return this;
  11867. };
  11868. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11869. get: function () {
  11870. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. AbstractMesh.prototype._preActivate = function () {
  11876. };
  11877. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11878. };
  11879. AbstractMesh.prototype._activate = function (renderId) {
  11880. this._renderId = renderId;
  11881. };
  11882. /**
  11883. * Returns the last update of the World matrix
  11884. * Returns a Matrix.
  11885. */
  11886. AbstractMesh.prototype.getWorldMatrix = function () {
  11887. if (this._masterMesh) {
  11888. return this._masterMesh.getWorldMatrix();
  11889. }
  11890. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11891. this.computeWorldMatrix();
  11892. }
  11893. return this._worldMatrix;
  11894. };
  11895. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11896. /**
  11897. * Returns directly the last state of the mesh World matrix.
  11898. * A Matrix is returned.
  11899. */
  11900. get: function () {
  11901. return this._worldMatrix;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11907. /**
  11908. * Returns the current mesh absolute position.
  11909. * Retuns a Vector3.
  11910. */
  11911. get: function () {
  11912. return this._absolutePosition;
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. /**
  11918. * Prevents the World matrix to be computed any longer.
  11919. * Returns the AbstractMesh.
  11920. */
  11921. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11922. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11923. this.computeWorldMatrix(true);
  11924. this._isWorldMatrixFrozen = true;
  11925. return this;
  11926. };
  11927. /**
  11928. * Allows back the World matrix computation.
  11929. * Returns the AbstractMesh.
  11930. */
  11931. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11932. this._isWorldMatrixFrozen = false;
  11933. this.computeWorldMatrix(true);
  11934. return this;
  11935. };
  11936. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11937. /**
  11938. * True if the World matrix has been frozen.
  11939. * Returns a boolean.
  11940. */
  11941. get: function () {
  11942. return this._isWorldMatrixFrozen;
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. /**
  11948. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11949. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11950. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11951. * The passed axis is also normalized.
  11952. * Returns the AbstractMesh.
  11953. */
  11954. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11955. axis.normalize();
  11956. if (!this.rotationQuaternion) {
  11957. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11958. this.rotation = BABYLON.Vector3.Zero();
  11959. }
  11960. var rotationQuaternion;
  11961. if (!space || space === BABYLON.Space.LOCAL) {
  11962. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11963. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11964. }
  11965. else {
  11966. if (this.parent) {
  11967. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11968. invertParentWorldMatrix.invert();
  11969. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11970. }
  11971. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11972. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11973. }
  11974. return this;
  11975. };
  11976. /**
  11977. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  11978. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11979. * The passed axis is also normalized.
  11980. * Returns the AbstractMesh.
  11981. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  11982. */
  11983. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  11984. axis.normalize();
  11985. if (!this.rotationQuaternion) {
  11986. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11987. this.rotation.copyFromFloats(0, 0, 0);
  11988. }
  11989. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  11990. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  11991. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  11992. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  11993. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  11994. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  11995. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  11996. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  11997. this.rotationQuaternion.multiplyInPlace(BABYLON.Tmp.Quaternion[0]);
  11998. return this;
  11999. };
  12000. /**
  12001. * Translates the mesh along the axis vector for the passed distance in the given space.
  12002. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12003. * Returns the AbstractMesh.
  12004. */
  12005. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12006. var displacementVector = axis.scale(distance);
  12007. if (!space || space === BABYLON.Space.LOCAL) {
  12008. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12009. this.setPositionWithLocalVector(tempV3);
  12010. }
  12011. else {
  12012. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12013. }
  12014. return this;
  12015. };
  12016. /**
  12017. * Adds a rotation step to the mesh current rotation.
  12018. * x, y, z are Euler angles expressed in radians.
  12019. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12020. * This means this rotation is made in the mesh local space only.
  12021. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12022. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12023. * ```javascript
  12024. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12025. * ```
  12026. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12027. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12028. * Returns the AbstractMesh.
  12029. */
  12030. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12031. var rotationQuaternion;
  12032. if (this.rotationQuaternion) {
  12033. rotationQuaternion = this.rotationQuaternion;
  12034. }
  12035. else {
  12036. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12037. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12038. }
  12039. var accumulation = BABYLON.Tmp.Quaternion[0];
  12040. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12041. rotationQuaternion.multiplyInPlace(accumulation);
  12042. if (!this.rotationQuaternion) {
  12043. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12044. }
  12045. return this;
  12046. };
  12047. /**
  12048. * Retuns the mesh absolute position in the World.
  12049. * Returns a Vector3.
  12050. */
  12051. AbstractMesh.prototype.getAbsolutePosition = function () {
  12052. this.computeWorldMatrix();
  12053. return this._absolutePosition;
  12054. };
  12055. /**
  12056. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12057. * Returns the AbstractMesh.
  12058. */
  12059. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12060. if (!absolutePosition) {
  12061. return;
  12062. }
  12063. var absolutePositionX;
  12064. var absolutePositionY;
  12065. var absolutePositionZ;
  12066. if (absolutePosition.x === undefined) {
  12067. if (arguments.length < 3) {
  12068. return;
  12069. }
  12070. absolutePositionX = arguments[0];
  12071. absolutePositionY = arguments[1];
  12072. absolutePositionZ = arguments[2];
  12073. }
  12074. else {
  12075. absolutePositionX = absolutePosition.x;
  12076. absolutePositionY = absolutePosition.y;
  12077. absolutePositionZ = absolutePosition.z;
  12078. }
  12079. if (this.parent) {
  12080. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12081. invertParentWorldMatrix.invert();
  12082. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12083. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12084. }
  12085. else {
  12086. this.position.x = absolutePositionX;
  12087. this.position.y = absolutePositionY;
  12088. this.position.z = absolutePositionZ;
  12089. }
  12090. return this;
  12091. };
  12092. // ================================== Point of View Movement =================================
  12093. /**
  12094. * Perform relative position change from the point of view of behind the front of the mesh.
  12095. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12096. * Supports definition of mesh facing forward or backward.
  12097. * @param {number} amountRight
  12098. * @param {number} amountUp
  12099. * @param {number} amountForward
  12100. *
  12101. * Returns the AbstractMesh.
  12102. */
  12103. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12104. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12105. return this;
  12106. };
  12107. /**
  12108. * Calculate relative position change from the point of view of behind the front of the mesh.
  12109. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12110. * Supports definition of mesh facing forward or backward.
  12111. * @param {number} amountRight
  12112. * @param {number} amountUp
  12113. * @param {number} amountForward
  12114. *
  12115. * Returns a new Vector3.
  12116. */
  12117. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12118. var rotMatrix = new BABYLON.Matrix();
  12119. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12120. rotQuaternion.toRotationMatrix(rotMatrix);
  12121. var translationDelta = BABYLON.Vector3.Zero();
  12122. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12123. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12124. return translationDelta;
  12125. };
  12126. // ================================== Point of View Rotation =================================
  12127. /**
  12128. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12129. * Supports definition of mesh facing forward or backward.
  12130. * @param {number} flipBack
  12131. * @param {number} twirlClockwise
  12132. * @param {number} tiltRight
  12133. *
  12134. * Returns the AbstractMesh.
  12135. */
  12136. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12137. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12138. return this;
  12139. };
  12140. /**
  12141. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12142. * Supports definition of mesh facing forward or backward.
  12143. * @param {number} flipBack
  12144. * @param {number} twirlClockwise
  12145. * @param {number} tiltRight
  12146. *
  12147. * Returns a new Vector3.
  12148. */
  12149. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12150. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12151. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12152. };
  12153. /**
  12154. * Sets a new pivot matrix to the mesh.
  12155. * Returns the AbstractMesh.
  12156. */
  12157. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12158. this._pivotMatrix = matrix;
  12159. this._cache.pivotMatrixUpdated = true;
  12160. return this;
  12161. };
  12162. /**
  12163. * Returns the mesh pivot matrix.
  12164. * Default : Identity.
  12165. * A Matrix is returned.
  12166. */
  12167. AbstractMesh.prototype.getPivotMatrix = function () {
  12168. return this._pivotMatrix;
  12169. };
  12170. AbstractMesh.prototype._isSynchronized = function () {
  12171. if (this._isDirty) {
  12172. return false;
  12173. }
  12174. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12175. return false;
  12176. if (this._cache.pivotMatrixUpdated) {
  12177. return false;
  12178. }
  12179. if (this.infiniteDistance) {
  12180. return false;
  12181. }
  12182. if (!this._cache.position.equals(this.position))
  12183. return false;
  12184. if (this.rotationQuaternion) {
  12185. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12186. return false;
  12187. }
  12188. if (!this._cache.rotation.equals(this.rotation))
  12189. return false;
  12190. if (!this._cache.scaling.equals(this.scaling))
  12191. return false;
  12192. return true;
  12193. };
  12194. AbstractMesh.prototype._initCache = function () {
  12195. _super.prototype._initCache.call(this);
  12196. this._cache.localMatrixUpdated = false;
  12197. this._cache.position = BABYLON.Vector3.Zero();
  12198. this._cache.scaling = BABYLON.Vector3.Zero();
  12199. this._cache.rotation = BABYLON.Vector3.Zero();
  12200. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12201. this._cache.billboardMode = -1;
  12202. };
  12203. AbstractMesh.prototype.markAsDirty = function (property) {
  12204. if (property === "rotation") {
  12205. this.rotationQuaternion = null;
  12206. }
  12207. this._currentRenderId = Number.MAX_VALUE;
  12208. this._isDirty = true;
  12209. return this;
  12210. };
  12211. /**
  12212. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12213. * Returns the AbstractMesh.
  12214. */
  12215. AbstractMesh.prototype._updateBoundingInfo = function () {
  12216. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12217. this._boundingInfo.update(this.worldMatrixFromCache);
  12218. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12219. return this;
  12220. };
  12221. /**
  12222. * Update a mesh's children BoundingInfo objects only.
  12223. * Returns the AbstractMesh.
  12224. */
  12225. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12226. if (!this.subMeshes) {
  12227. return;
  12228. }
  12229. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12230. var subMesh = this.subMeshes[subIndex];
  12231. if (!subMesh.IsGlobal) {
  12232. subMesh.updateBoundingInfo(matrix);
  12233. }
  12234. }
  12235. return this;
  12236. };
  12237. /**
  12238. * Computes the mesh World matrix and returns it.
  12239. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12240. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12241. * If the parameter `force`is set to `true`, the actual computation is done.
  12242. * Returns the mesh World Matrix.
  12243. */
  12244. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12245. if (this._isWorldMatrixFrozen) {
  12246. return this._worldMatrix;
  12247. }
  12248. if (!force && this.isSynchronized(true)) {
  12249. this._currentRenderId = this.getScene().getRenderId();
  12250. return this._worldMatrix;
  12251. }
  12252. this._cache.position.copyFrom(this.position);
  12253. this._cache.scaling.copyFrom(this.scaling);
  12254. this._cache.pivotMatrixUpdated = false;
  12255. this._cache.billboardMode = this.billboardMode;
  12256. this._currentRenderId = this.getScene().getRenderId();
  12257. this._isDirty = false;
  12258. // Scaling
  12259. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12260. // Rotation
  12261. //rotate, if quaternion is set and rotation was used
  12262. if (this.rotationQuaternion) {
  12263. var len = this.rotation.length();
  12264. if (len) {
  12265. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12266. this.rotation.copyFromFloats(0, 0, 0);
  12267. }
  12268. }
  12269. if (this.rotationQuaternion) {
  12270. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12271. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12272. }
  12273. else {
  12274. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12275. this._cache.rotation.copyFrom(this.rotation);
  12276. }
  12277. // Translation
  12278. if (this.infiniteDistance && !this.parent) {
  12279. var camera = this.getScene().activeCamera;
  12280. if (camera) {
  12281. var cameraWorldMatrix = camera.getWorldMatrix();
  12282. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12283. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12284. }
  12285. }
  12286. else {
  12287. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12288. }
  12289. // Composing transformations
  12290. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12291. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12292. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12293. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12294. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12295. // Need to decompose each rotation here
  12296. var currentPosition = BABYLON.Tmp.Vector3[3];
  12297. if (this.parent && this.parent.getWorldMatrix) {
  12298. if (this._meshToBoneReferal) {
  12299. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12300. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12301. }
  12302. else {
  12303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12304. }
  12305. }
  12306. else {
  12307. currentPosition.copyFrom(this.position);
  12308. }
  12309. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12310. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12311. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12312. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12313. }
  12314. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12315. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12316. }
  12317. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12318. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12319. }
  12320. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12321. }
  12322. else {
  12323. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12324. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12325. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12326. }
  12327. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12328. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12329. }
  12330. // Local world
  12331. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12332. // Parent
  12333. if (this.parent && this.parent.getWorldMatrix) {
  12334. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12335. if (this._meshToBoneReferal) {
  12336. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12337. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12338. }
  12339. else {
  12340. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12341. }
  12342. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12343. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12344. this._worldMatrix.copyFrom(this._localWorld);
  12345. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12346. }
  12347. else {
  12348. if (this._meshToBoneReferal) {
  12349. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12350. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12351. }
  12352. else {
  12353. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12354. }
  12355. }
  12356. this._markSyncedWithParent();
  12357. }
  12358. else {
  12359. this._worldMatrix.copyFrom(this._localWorld);
  12360. }
  12361. // Bounding info
  12362. this._updateBoundingInfo();
  12363. // Absolute position
  12364. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12365. // Callbacks
  12366. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12367. if (!this._poseMatrix) {
  12368. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12369. }
  12370. return this._worldMatrix;
  12371. };
  12372. /**
  12373. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12374. * @param func: callback function to add
  12375. *
  12376. * Returns the AbstractMesh.
  12377. */
  12378. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12379. this.onAfterWorldMatrixUpdateObservable.add(func);
  12380. return this;
  12381. };
  12382. /**
  12383. * Removes a registered callback function.
  12384. * Returns the AbstractMesh.
  12385. */
  12386. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12387. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12388. return this;
  12389. };
  12390. /**
  12391. * Sets the mesh position in its local space.
  12392. * Returns the AbstractMesh.
  12393. */
  12394. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12395. this.computeWorldMatrix();
  12396. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12397. return this;
  12398. };
  12399. /**
  12400. * Returns the mesh position in the local space from the current World matrix values.
  12401. * Returns a new Vector3.
  12402. */
  12403. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12404. this.computeWorldMatrix();
  12405. var invLocalWorldMatrix = this._localWorld.clone();
  12406. invLocalWorldMatrix.invert();
  12407. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12408. };
  12409. /**
  12410. * Translates the mesh along the passed Vector3 in its local space.
  12411. * Returns the AbstractMesh.
  12412. */
  12413. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12414. this.computeWorldMatrix(true);
  12415. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12416. return this;
  12417. };
  12418. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12419. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12420. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12421. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12422. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12423. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12424. /// <returns>Mesh oriented towards targetMesh</returns>
  12425. if (yawCor === void 0) { yawCor = 0; }
  12426. if (pitchCor === void 0) { pitchCor = 0; }
  12427. if (rollCor === void 0) { rollCor = 0; }
  12428. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12429. var dv = AbstractMesh._lookAtVectorCache;
  12430. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12431. targetPoint.subtractToRef(pos, dv);
  12432. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12433. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12434. var pitch = Math.atan2(dv.y, len);
  12435. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12436. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12437. return this;
  12438. };
  12439. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12440. this._meshToBoneReferal = affectedMesh;
  12441. this.parent = bone;
  12442. if (bone.getWorldMatrix().determinant() < 0) {
  12443. this.scalingDeterminant *= -1;
  12444. }
  12445. return this;
  12446. };
  12447. AbstractMesh.prototype.detachFromBone = function () {
  12448. if (this.parent.getWorldMatrix().determinant() < 0) {
  12449. this.scalingDeterminant *= -1;
  12450. }
  12451. this._meshToBoneReferal = null;
  12452. this.parent = null;
  12453. return this;
  12454. };
  12455. /**
  12456. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12457. * A mesh is in the frustum if its bounding box intersects the frustum.
  12458. * Boolean returned.
  12459. */
  12460. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12461. return this._boundingInfo.isInFrustum(frustumPlanes);
  12462. };
  12463. /**
  12464. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12465. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12466. * Boolean returned.
  12467. */
  12468. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12469. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12470. ;
  12471. };
  12472. /**
  12473. * True if the mesh intersects another mesh or a SolidParticle object.
  12474. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  12475. * Returns a boolean.
  12476. */
  12477. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12478. if (!this._boundingInfo || !mesh._boundingInfo) {
  12479. return false;
  12480. }
  12481. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12482. };
  12483. /**
  12484. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12485. * Returns a boolean.
  12486. */
  12487. AbstractMesh.prototype.intersectsPoint = function (point) {
  12488. if (!this._boundingInfo) {
  12489. return false;
  12490. }
  12491. return this._boundingInfo.intersectsPoint(point);
  12492. };
  12493. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12494. return this.physicsImpostor;
  12495. };
  12496. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12497. if (!camera) {
  12498. camera = this.getScene().activeCamera;
  12499. }
  12500. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12501. };
  12502. /**
  12503. * Returns the distance from the mesh to the active camera.
  12504. * Returns a float.
  12505. */
  12506. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12507. if (!camera) {
  12508. camera = this.getScene().activeCamera;
  12509. }
  12510. return this.absolutePosition.subtract(camera.position).length();
  12511. };
  12512. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12513. if (!this.physicsImpostor) {
  12514. return;
  12515. }
  12516. this.physicsImpostor.applyImpulse(force, contactPoint);
  12517. return this;
  12518. };
  12519. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12520. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12521. return;
  12522. }
  12523. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12524. mainPivot: pivot1,
  12525. connectedPivot: pivot2,
  12526. nativeParams: options
  12527. });
  12528. return this;
  12529. };
  12530. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12531. // Collisions
  12532. /**
  12533. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12534. * Default `false`.
  12535. */
  12536. get: function () {
  12537. return this._checkCollisions;
  12538. },
  12539. set: function (collisionEnabled) {
  12540. this._checkCollisions = collisionEnabled;
  12541. if (this.getScene().workerCollisions) {
  12542. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12543. }
  12544. },
  12545. enumerable: true,
  12546. configurable: true
  12547. });
  12548. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12549. var globalPosition = this.getAbsolutePosition();
  12550. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12551. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12552. if (!this._collider) {
  12553. this._collider = new BABYLON.Collider();
  12554. }
  12555. this._collider.radius = this.ellipsoid;
  12556. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12557. return this;
  12558. };
  12559. // Submeshes octree
  12560. /**
  12561. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12562. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12563. * Returns an Octree of submeshes.
  12564. */
  12565. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12566. if (maxCapacity === void 0) { maxCapacity = 64; }
  12567. if (maxDepth === void 0) { maxDepth = 2; }
  12568. if (!this._submeshesOctree) {
  12569. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12570. }
  12571. this.computeWorldMatrix(true);
  12572. // Update octree
  12573. var bbox = this.getBoundingInfo().boundingBox;
  12574. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12575. return this._submeshesOctree;
  12576. };
  12577. // Collisions
  12578. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12579. this._generatePointsArray();
  12580. // Transformation
  12581. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12582. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12583. subMesh._lastColliderWorldVertices = [];
  12584. subMesh._trianglePlanes = [];
  12585. var start = subMesh.verticesStart;
  12586. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12587. for (var i = start; i < end; i++) {
  12588. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12589. }
  12590. }
  12591. // Collide
  12592. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12593. if (collider.collisionFound) {
  12594. collider.collidedMesh = this;
  12595. }
  12596. return this;
  12597. };
  12598. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12599. var subMeshes;
  12600. var len;
  12601. // Octrees
  12602. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12603. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12604. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12605. len = intersections.length;
  12606. subMeshes = intersections.data;
  12607. }
  12608. else {
  12609. subMeshes = this.subMeshes;
  12610. len = subMeshes.length;
  12611. }
  12612. for (var index = 0; index < len; index++) {
  12613. var subMesh = subMeshes[index];
  12614. // Bounding test
  12615. if (len > 1 && !subMesh._checkCollision(collider))
  12616. continue;
  12617. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12618. }
  12619. return this;
  12620. };
  12621. AbstractMesh.prototype._checkCollision = function (collider) {
  12622. // Bounding box test
  12623. if (!this._boundingInfo._checkCollision(collider))
  12624. return this;
  12625. // Transformation matrix
  12626. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12627. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12628. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12629. return this;
  12630. };
  12631. // Picking
  12632. AbstractMesh.prototype._generatePointsArray = function () {
  12633. return false;
  12634. };
  12635. /**
  12636. * Checks if the passed Ray intersects with the mesh.
  12637. * Returns an object PickingInfo.
  12638. */
  12639. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12640. var pickingInfo = new BABYLON.PickingInfo();
  12641. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12642. return pickingInfo;
  12643. }
  12644. if (!this._generatePointsArray()) {
  12645. return pickingInfo;
  12646. }
  12647. var intersectInfo = null;
  12648. // Octrees
  12649. var subMeshes;
  12650. var len;
  12651. if (this._submeshesOctree && this.useOctreeForPicking) {
  12652. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12653. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12654. len = intersections.length;
  12655. subMeshes = intersections.data;
  12656. }
  12657. else {
  12658. subMeshes = this.subMeshes;
  12659. len = subMeshes.length;
  12660. }
  12661. for (var index = 0; index < len; index++) {
  12662. var subMesh = subMeshes[index];
  12663. // Bounding test
  12664. if (len > 1 && !subMesh.canIntersects(ray))
  12665. continue;
  12666. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12667. if (currentIntersectInfo) {
  12668. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12669. intersectInfo = currentIntersectInfo;
  12670. intersectInfo.subMeshId = index;
  12671. if (fastCheck) {
  12672. break;
  12673. }
  12674. }
  12675. }
  12676. }
  12677. if (intersectInfo) {
  12678. // Get picked point
  12679. var world = this.getWorldMatrix();
  12680. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12681. var direction = ray.direction.clone();
  12682. direction = direction.scale(intersectInfo.distance);
  12683. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12684. var pickedPoint = worldOrigin.add(worldDirection);
  12685. // Return result
  12686. pickingInfo.hit = true;
  12687. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12688. pickingInfo.pickedPoint = pickedPoint;
  12689. pickingInfo.pickedMesh = this;
  12690. pickingInfo.bu = intersectInfo.bu;
  12691. pickingInfo.bv = intersectInfo.bv;
  12692. pickingInfo.faceId = intersectInfo.faceId;
  12693. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12694. return pickingInfo;
  12695. }
  12696. return pickingInfo;
  12697. };
  12698. /**
  12699. * Clones the mesh, used by the class Mesh.
  12700. * Just returns `null` for an AbstractMesh.
  12701. */
  12702. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12703. return null;
  12704. };
  12705. /**
  12706. * Disposes all the mesh submeshes.
  12707. * Returns the AbstractMesh.
  12708. */
  12709. AbstractMesh.prototype.releaseSubMeshes = function () {
  12710. if (this.subMeshes) {
  12711. while (this.subMeshes.length) {
  12712. this.subMeshes[0].dispose();
  12713. }
  12714. }
  12715. else {
  12716. this.subMeshes = new Array();
  12717. }
  12718. return this;
  12719. };
  12720. /**
  12721. * Disposes the AbstractMesh.
  12722. * Some internal references are kept for further use.
  12723. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12724. * Returns nothing.
  12725. */
  12726. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12727. var _this = this;
  12728. var index;
  12729. // Action manager
  12730. if (this.actionManager) {
  12731. this.actionManager.dispose();
  12732. this.actionManager = null;
  12733. }
  12734. // Skeleton
  12735. this.skeleton = null;
  12736. // Animations
  12737. this.getScene().stopAnimation(this);
  12738. // Physics
  12739. if (this.physicsImpostor) {
  12740. this.physicsImpostor.dispose();
  12741. }
  12742. // Intersections in progress
  12743. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12744. var other = this._intersectionsInProgress[index];
  12745. var pos = other._intersectionsInProgress.indexOf(this);
  12746. other._intersectionsInProgress.splice(pos, 1);
  12747. }
  12748. this._intersectionsInProgress = [];
  12749. // Lights
  12750. var lights = this.getScene().lights;
  12751. lights.forEach(function (light) {
  12752. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12753. if (meshIndex !== -1) {
  12754. light.includedOnlyMeshes.splice(meshIndex, 1);
  12755. }
  12756. meshIndex = light.excludedMeshes.indexOf(_this);
  12757. if (meshIndex !== -1) {
  12758. light.excludedMeshes.splice(meshIndex, 1);
  12759. }
  12760. // Shadow generators
  12761. var generator = light.getShadowGenerator();
  12762. if (generator) {
  12763. var shadowMap = generator.getShadowMap();
  12764. meshIndex = shadowMap.renderList.indexOf(_this);
  12765. if (meshIndex !== -1) {
  12766. shadowMap.renderList.splice(meshIndex, 1);
  12767. }
  12768. }
  12769. });
  12770. // Edges
  12771. if (this._edgesRenderer) {
  12772. this._edgesRenderer.dispose();
  12773. this._edgesRenderer = null;
  12774. }
  12775. // SubMeshes
  12776. if (this.getClassName() !== "InstancedMesh") {
  12777. this.releaseSubMeshes();
  12778. }
  12779. // Octree
  12780. var sceneOctree = this.getScene().selectionOctree;
  12781. if (sceneOctree) {
  12782. var index = sceneOctree.dynamicContent.indexOf(this);
  12783. if (index !== -1) {
  12784. sceneOctree.dynamicContent.splice(index, 1);
  12785. }
  12786. }
  12787. // Engine
  12788. this.getScene().getEngine().wipeCaches();
  12789. // Remove from scene
  12790. this.getScene().removeMesh(this);
  12791. if (!doNotRecurse) {
  12792. // Particles
  12793. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12794. if (this.getScene().particleSystems[index].emitter === this) {
  12795. this.getScene().particleSystems[index].dispose();
  12796. index--;
  12797. }
  12798. }
  12799. // Children
  12800. var objects = this.getDescendants(true);
  12801. for (index = 0; index < objects.length; index++) {
  12802. objects[index].dispose();
  12803. }
  12804. }
  12805. else {
  12806. var childMeshes = this.getChildMeshes(true);
  12807. for (index = 0; index < childMeshes.length; index++) {
  12808. var child = childMeshes[index];
  12809. child.parent = null;
  12810. child.computeWorldMatrix(true);
  12811. }
  12812. }
  12813. // facet data
  12814. if (this._facetDataEnabled) {
  12815. this.disableFacetData();
  12816. }
  12817. this.onAfterWorldMatrixUpdateObservable.clear();
  12818. this.onCollideObservable.clear();
  12819. this.onCollisionPositionChangeObservable.clear();
  12820. this._isDisposed = true;
  12821. _super.prototype.dispose.call(this);
  12822. };
  12823. /**
  12824. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12825. * This Vector3 is expressed in the World space.
  12826. */
  12827. AbstractMesh.prototype.getDirection = function (localAxis) {
  12828. var result = BABYLON.Vector3.Zero();
  12829. this.getDirectionToRef(localAxis, result);
  12830. return result;
  12831. };
  12832. /**
  12833. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12834. * localAxis is expressed in the mesh local space.
  12835. * result is computed in the Wordl space from the mesh World matrix.
  12836. * Returns the AbstractMesh.
  12837. */
  12838. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12839. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12840. return this;
  12841. };
  12842. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12844. if (this.getScene().getRenderId() == 0) {
  12845. this.computeWorldMatrix(true);
  12846. }
  12847. var wm = this.getWorldMatrix();
  12848. if (space == BABYLON.Space.WORLD) {
  12849. var tmat = BABYLON.Tmp.Matrix[0];
  12850. wm.invertToRef(tmat);
  12851. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12852. }
  12853. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12854. this._pivotMatrix.m[12] = -point.x;
  12855. this._pivotMatrix.m[13] = -point.y;
  12856. this._pivotMatrix.m[14] = -point.z;
  12857. this._cache.pivotMatrixUpdated = true;
  12858. return this;
  12859. };
  12860. /**
  12861. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12862. */
  12863. AbstractMesh.prototype.getPivotPoint = function () {
  12864. var point = BABYLON.Vector3.Zero();
  12865. this.getPivotPointToRef(point);
  12866. return point;
  12867. };
  12868. /**
  12869. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12870. * Returns the AbstractMesh.
  12871. */
  12872. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12873. result.x = -this._pivotMatrix.m[12];
  12874. result.y = -this._pivotMatrix.m[13];
  12875. result.z = -this._pivotMatrix.m[14];
  12876. return this;
  12877. };
  12878. /**
  12879. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12880. */
  12881. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12882. var point = BABYLON.Vector3.Zero();
  12883. this.getAbsolutePivotPointToRef(point);
  12884. return point;
  12885. };
  12886. /**
  12887. * Defines the passed mesh as the parent of the current mesh.
  12888. * Returns the AbstractMesh.
  12889. */
  12890. AbstractMesh.prototype.setParent = function (mesh) {
  12891. var child = this;
  12892. var parent = mesh;
  12893. if (mesh == null) {
  12894. var rotation = BABYLON.Tmp.Quaternion[0];
  12895. var position = BABYLON.Tmp.Vector3[0];
  12896. var scale = BABYLON.Tmp.Vector3[1];
  12897. child.getWorldMatrix().decompose(scale, rotation, position);
  12898. if (child.rotationQuaternion) {
  12899. child.rotationQuaternion.copyFrom(rotation);
  12900. }
  12901. else {
  12902. rotation.toEulerAnglesToRef(child.rotation);
  12903. }
  12904. child.position.x = position.x;
  12905. child.position.y = position.y;
  12906. child.position.z = position.z;
  12907. }
  12908. else {
  12909. var rotation = BABYLON.Tmp.Quaternion[0];
  12910. var position = BABYLON.Tmp.Vector3[0];
  12911. var scale = BABYLON.Tmp.Vector3[1];
  12912. var m1 = BABYLON.Tmp.Matrix[0];
  12913. var m2 = BABYLON.Tmp.Matrix[1];
  12914. parent.getWorldMatrix().decompose(scale, rotation, position);
  12915. rotation.toRotationMatrix(m1);
  12916. m2.setTranslation(position);
  12917. m2.multiplyToRef(m1, m1);
  12918. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12919. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12920. m.decompose(scale, rotation, position);
  12921. if (child.rotationQuaternion) {
  12922. child.rotationQuaternion.copyFrom(rotation);
  12923. }
  12924. else {
  12925. rotation.toEulerAnglesToRef(child.rotation);
  12926. }
  12927. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12928. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12929. m.decompose(scale, rotation, position);
  12930. child.position.x = position.x;
  12931. child.position.y = position.y;
  12932. child.position.z = position.z;
  12933. }
  12934. child.parent = parent;
  12935. return this;
  12936. };
  12937. /**
  12938. * Adds the passed mesh as a child to the current mesh.
  12939. * Returns the AbstractMesh.
  12940. */
  12941. AbstractMesh.prototype.addChild = function (mesh) {
  12942. mesh.setParent(this);
  12943. return this;
  12944. };
  12945. /**
  12946. * Removes the passed mesh from the current mesh children list.
  12947. * Returns the AbstractMesh.
  12948. */
  12949. AbstractMesh.prototype.removeChild = function (mesh) {
  12950. mesh.setParent(null);
  12951. return this;
  12952. };
  12953. /**
  12954. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12955. * Returns the AbstractMesh.
  12956. */
  12957. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12958. result.x = this._pivotMatrix.m[12];
  12959. result.y = this._pivotMatrix.m[13];
  12960. result.z = this._pivotMatrix.m[14];
  12961. this.getPivotPointToRef(result);
  12962. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12963. return this;
  12964. };
  12965. // Facet data
  12966. /**
  12967. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12968. * Returns the AbstractMesh.
  12969. */
  12970. AbstractMesh.prototype._initFacetData = function () {
  12971. if (!this._facetNormals) {
  12972. this._facetNormals = new Array();
  12973. }
  12974. if (!this._facetPositions) {
  12975. this._facetPositions = new Array();
  12976. }
  12977. if (!this._facetPartitioning) {
  12978. this._facetPartitioning = new Array();
  12979. }
  12980. this._facetNb = this.getIndices().length / 3;
  12981. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12982. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12983. for (var f = 0; f < this._facetNb; f++) {
  12984. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12985. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12986. }
  12987. this._facetDataEnabled = true;
  12988. return this;
  12989. };
  12990. /**
  12991. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12992. * This method can be called within the render loop.
  12993. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  12994. * Returns the AbstractMesh.
  12995. */
  12996. AbstractMesh.prototype.updateFacetData = function () {
  12997. if (!this._facetDataEnabled) {
  12998. this._initFacetData();
  12999. }
  13000. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13001. var indices = this.getIndices();
  13002. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13003. var bInfo = this.getBoundingInfo();
  13004. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13005. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13006. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13007. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13008. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13009. this._subDiv.max = this._partitioningSubdivisions;
  13010. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13011. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13012. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13013. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13014. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13015. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13016. // set the parameters for ComputeNormals()
  13017. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13018. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13019. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13020. this._facetParameters.bInfo = bInfo;
  13021. this._facetParameters.bbSize = this._bbSize;
  13022. this._facetParameters.subDiv = this._subDiv;
  13023. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13024. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13025. return this;
  13026. };
  13027. /**
  13028. * Returns the facetLocalNormals array.
  13029. * The normals are expressed in the mesh local space.
  13030. */
  13031. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13032. if (!this._facetNormals) {
  13033. this.updateFacetData();
  13034. }
  13035. return this._facetNormals;
  13036. };
  13037. /**
  13038. * Returns the facetLocalPositions array.
  13039. * The facet positions are expressed in the mesh local space.
  13040. */
  13041. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13042. if (!this._facetPositions) {
  13043. this.updateFacetData();
  13044. }
  13045. return this._facetPositions;
  13046. };
  13047. /**
  13048. * Returns the facetLocalPartioning array.
  13049. */
  13050. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13051. if (!this._facetPartitioning) {
  13052. this.updateFacetData();
  13053. }
  13054. return this._facetPartitioning;
  13055. };
  13056. /**
  13057. * Returns the i-th facet position in the world system.
  13058. * This method allocates a new Vector3 per call.
  13059. */
  13060. AbstractMesh.prototype.getFacetPosition = function (i) {
  13061. var pos = BABYLON.Vector3.Zero();
  13062. this.getFacetPositionToRef(i, pos);
  13063. return pos;
  13064. };
  13065. /**
  13066. * Sets the reference Vector3 with the i-th facet position in the world system.
  13067. * Returns the AbstractMesh.
  13068. */
  13069. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13070. var localPos = (this.getFacetLocalPositions())[i];
  13071. var world = this.getWorldMatrix();
  13072. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13073. return this;
  13074. };
  13075. /**
  13076. * Returns the i-th facet normal in the world system.
  13077. * This method allocates a new Vector3 per call.
  13078. */
  13079. AbstractMesh.prototype.getFacetNormal = function (i) {
  13080. var norm = BABYLON.Vector3.Zero();
  13081. this.getFacetNormalToRef(i, norm);
  13082. return norm;
  13083. };
  13084. /**
  13085. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13086. * Returns the AbstractMesh.
  13087. */
  13088. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13089. var localNorm = (this.getFacetLocalNormals())[i];
  13090. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13091. return this;
  13092. };
  13093. /**
  13094. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  13095. */
  13096. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13097. var bInfo = this.getBoundingInfo();
  13098. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13099. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13100. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13101. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13102. return null;
  13103. }
  13104. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13105. };
  13106. /**
  13107. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13108. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13109. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13110. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13111. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13112. */
  13113. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13114. if (checkFace === void 0) { checkFace = false; }
  13115. if (facing === void 0) { facing = true; }
  13116. var world = this.getWorldMatrix();
  13117. var invMat = BABYLON.Tmp.Matrix[5];
  13118. world.invertToRef(invMat);
  13119. var invVect = BABYLON.Tmp.Vector3[8];
  13120. var closest = null;
  13121. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13122. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13123. if (projected) {
  13124. // tranform the local computed projected vector to world coordinates
  13125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13126. }
  13127. return closest;
  13128. };
  13129. /**
  13130. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13131. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13132. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13133. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13134. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13135. */
  13136. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13137. if (checkFace === void 0) { checkFace = false; }
  13138. if (facing === void 0) { facing = true; }
  13139. var closest = null;
  13140. var tmpx = 0.0;
  13141. var tmpy = 0.0;
  13142. var tmpz = 0.0;
  13143. var d = 0.0; // tmp dot facet normal * facet position
  13144. var t0 = 0.0;
  13145. var projx = 0.0;
  13146. var projy = 0.0;
  13147. var projz = 0.0;
  13148. // Get all the facets in the same partitioning block than (x, y, z)
  13149. var facetPositions = this.getFacetLocalPositions();
  13150. var facetNormals = this.getFacetLocalNormals();
  13151. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13152. if (!facetsInBlock) {
  13153. return null;
  13154. }
  13155. // Get the closest facet to (x, y, z)
  13156. var shortest = Number.MAX_VALUE; // init distance vars
  13157. var tmpDistance = shortest;
  13158. var fib; // current facet in the block
  13159. var norm; // current facet normal
  13160. var p0; // current facet barycenter position
  13161. // loop on all the facets in the current partitioning block
  13162. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13163. fib = facetsInBlock[idx];
  13164. norm = facetNormals[fib];
  13165. p0 = facetPositions[fib];
  13166. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13167. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13168. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13169. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13170. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13171. projx = x + norm.x * t0;
  13172. projy = y + norm.y * t0;
  13173. projz = z + norm.z * t0;
  13174. tmpx = projx - x;
  13175. tmpy = projy - y;
  13176. tmpz = projz - z;
  13177. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13178. if (tmpDistance < shortest) {
  13179. shortest = tmpDistance;
  13180. closest = fib;
  13181. if (projected) {
  13182. projected.x = projx;
  13183. projected.y = projy;
  13184. projected.z = projz;
  13185. }
  13186. }
  13187. }
  13188. }
  13189. return closest;
  13190. };
  13191. /**
  13192. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13193. */
  13194. AbstractMesh.prototype.getFacetDataParameters = function () {
  13195. return this._facetParameters;
  13196. };
  13197. /**
  13198. * Disables the feature FacetData and frees the related memory.
  13199. * Returns the AbstractMesh.
  13200. */
  13201. AbstractMesh.prototype.disableFacetData = function () {
  13202. if (this._facetDataEnabled) {
  13203. this._facetDataEnabled = false;
  13204. this._facetPositions = null;
  13205. this._facetNormals = null;
  13206. this._facetPartitioning = null;
  13207. this._facetParameters = null;
  13208. }
  13209. return this;
  13210. };
  13211. /**
  13212. * Creates new normals data for the mesh.
  13213. * @param updatable.
  13214. */
  13215. AbstractMesh.prototype.createNormals = function (updatable) {
  13216. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13217. var indices = this.getIndices();
  13218. var normals;
  13219. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13220. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13221. }
  13222. else {
  13223. normals = [];
  13224. }
  13225. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13226. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13227. };
  13228. return AbstractMesh;
  13229. }(BABYLON.Node));
  13230. // Statics
  13231. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13232. AbstractMesh._BILLBOARDMODE_X = 1;
  13233. AbstractMesh._BILLBOARDMODE_Y = 2;
  13234. AbstractMesh._BILLBOARDMODE_Z = 4;
  13235. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13236. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13237. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13238. BABYLON.AbstractMesh = AbstractMesh;
  13239. })(BABYLON || (BABYLON = {}));
  13240. //# sourceMappingURL=babylon.abstractMesh.js.map
  13241. var BABYLON;
  13242. (function (BABYLON) {
  13243. var Light = (function (_super) {
  13244. __extends(Light, _super);
  13245. /**
  13246. * Creates a Light object in the scene.
  13247. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13248. */
  13249. function Light(name, scene) {
  13250. var _this = _super.call(this, name, scene) || this;
  13251. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13252. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13253. _this.intensity = 1.0;
  13254. _this.range = Number.MAX_VALUE;
  13255. /**
  13256. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13257. * of light.
  13258. */
  13259. _this._photometricScale = 1.0;
  13260. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13261. _this._radius = 0.00001;
  13262. _this.renderPriority = 0;
  13263. /**
  13264. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13265. * the current shadow generator.
  13266. */
  13267. _this.shadowEnabled = true;
  13268. _this._excludeWithLayerMask = 0;
  13269. _this._includeOnlyWithLayerMask = 0;
  13270. _this._lightmapMode = 0;
  13271. _this._excludedMeshesIds = new Array();
  13272. _this._includedOnlyMeshesIds = new Array();
  13273. _this.getScene().addLight(_this);
  13274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13275. _this._buildUniformLayout();
  13276. _this.includedOnlyMeshes = new Array();
  13277. _this.excludedMeshes = new Array();
  13278. _this._resyncMeshes();
  13279. return _this;
  13280. }
  13281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13282. /**
  13283. * If every light affecting the material is in this lightmapMode,
  13284. * material.lightmapTexture adds or multiplies
  13285. * (depends on material.useLightmapAsShadowmap)
  13286. * after every other light calculations.
  13287. */
  13288. get: function () {
  13289. return Light._LIGHTMAP_DEFAULT;
  13290. },
  13291. enumerable: true,
  13292. configurable: true
  13293. });
  13294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13295. /**
  13296. * material.lightmapTexture as only diffuse lighting from this light
  13297. * adds pnly specular lighting from this light
  13298. * adds dynamic shadows
  13299. */
  13300. get: function () {
  13301. return Light._LIGHTMAP_SPECULAR;
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13307. /**
  13308. * material.lightmapTexture as only lighting
  13309. * no light calculation from this light
  13310. * only adds dynamic shadows from this light
  13311. */
  13312. get: function () {
  13313. return Light._LIGHTMAP_SHADOWSONLY;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13319. /**
  13320. * Each light type uses the default quantity according to its type:
  13321. * point/spot lights use luminous intensity
  13322. * directional lights use illuminance
  13323. */
  13324. get: function () {
  13325. return Light._INTENSITYMODE_AUTOMATIC;
  13326. },
  13327. enumerable: true,
  13328. configurable: true
  13329. });
  13330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13331. /**
  13332. * lumen (lm)
  13333. */
  13334. get: function () {
  13335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13336. },
  13337. enumerable: true,
  13338. configurable: true
  13339. });
  13340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13341. /**
  13342. * candela (lm/sr)
  13343. */
  13344. get: function () {
  13345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13346. },
  13347. enumerable: true,
  13348. configurable: true
  13349. });
  13350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13351. /**
  13352. * lux (lm/m^2)
  13353. */
  13354. get: function () {
  13355. return Light._INTENSITYMODE_ILLUMINANCE;
  13356. },
  13357. enumerable: true,
  13358. configurable: true
  13359. });
  13360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13361. /**
  13362. * nit (cd/m^2)
  13363. */
  13364. get: function () {
  13365. return Light._INTENSITYMODE_LUMINANCE;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13371. /**
  13372. * Light type const id of the point light.
  13373. */
  13374. get: function () {
  13375. return Light._LIGHTTYPEID_POINTLIGHT;
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13381. /**
  13382. * Light type const id of the directional light.
  13383. */
  13384. get: function () {
  13385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13391. /**
  13392. * Light type const id of the spot light.
  13393. */
  13394. get: function () {
  13395. return Light._LIGHTTYPEID_SPOTLIGHT;
  13396. },
  13397. enumerable: true,
  13398. configurable: true
  13399. });
  13400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13401. /**
  13402. * Light type const id of the hemispheric light.
  13403. */
  13404. get: function () {
  13405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. Object.defineProperty(Light.prototype, "intensityMode", {
  13411. /**
  13412. * Gets the photometric scale used to interpret the intensity.
  13413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13414. */
  13415. get: function () {
  13416. return this._intensityMode;
  13417. },
  13418. /**
  13419. * Sets the photometric scale used to interpret the intensity.
  13420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13421. */
  13422. set: function (value) {
  13423. this._intensityMode = value;
  13424. this._computePhotometricScale();
  13425. },
  13426. enumerable: true,
  13427. configurable: true
  13428. });
  13429. ;
  13430. ;
  13431. Object.defineProperty(Light.prototype, "radius", {
  13432. /**
  13433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13434. */
  13435. get: function () {
  13436. return this._radius;
  13437. },
  13438. /**
  13439. * sets the light radius used by PBR Materials to simulate soft area lights.
  13440. */
  13441. set: function (value) {
  13442. this._radius = value;
  13443. this._computePhotometricScale();
  13444. },
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. ;
  13449. ;
  13450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13451. get: function () {
  13452. return this._includedOnlyMeshes;
  13453. },
  13454. set: function (value) {
  13455. this._includedOnlyMeshes = value;
  13456. this._hookArrayForIncludedOnly(value);
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13462. get: function () {
  13463. return this._excludedMeshes;
  13464. },
  13465. set: function (value) {
  13466. this._excludedMeshes = value;
  13467. this._hookArrayForExcluded(value);
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13473. get: function () {
  13474. return this._excludeWithLayerMask;
  13475. },
  13476. set: function (value) {
  13477. this._excludeWithLayerMask = value;
  13478. this._resyncMeshes();
  13479. },
  13480. enumerable: true,
  13481. configurable: true
  13482. });
  13483. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13484. get: function () {
  13485. return this._includeOnlyWithLayerMask;
  13486. },
  13487. set: function (value) {
  13488. this._includeOnlyWithLayerMask = value;
  13489. this._resyncMeshes();
  13490. },
  13491. enumerable: true,
  13492. configurable: true
  13493. });
  13494. Object.defineProperty(Light.prototype, "lightmapMode", {
  13495. get: function () {
  13496. return this._lightmapMode;
  13497. },
  13498. set: function (value) {
  13499. if (this._lightmapMode === value) {
  13500. return;
  13501. }
  13502. this._lightmapMode = value;
  13503. this._markMeshesAsLightDirty();
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Light.prototype._buildUniformLayout = function () {
  13509. // Overridden
  13510. };
  13511. /**
  13512. * Returns the string "Light".
  13513. */
  13514. Light.prototype.getClassName = function () {
  13515. return "Light";
  13516. };
  13517. /**
  13518. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13519. */
  13520. Light.prototype.toString = function (fullDetails) {
  13521. var ret = "Name: " + this.name;
  13522. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13523. if (this.animations) {
  13524. for (var i = 0; i < this.animations.length; i++) {
  13525. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13526. }
  13527. }
  13528. if (fullDetails) {
  13529. }
  13530. return ret;
  13531. };
  13532. /**
  13533. * Set the enabled state of this node.
  13534. * @param {boolean} value - the new enabled state
  13535. * @see isEnabled
  13536. */
  13537. Light.prototype.setEnabled = function (value) {
  13538. _super.prototype.setEnabled.call(this, value);
  13539. this._resyncMeshes();
  13540. };
  13541. /**
  13542. * Returns the Light associated shadow generator.
  13543. */
  13544. Light.prototype.getShadowGenerator = function () {
  13545. return this._shadowGenerator;
  13546. };
  13547. /**
  13548. * Returns a Vector3, the absolute light position in the World.
  13549. */
  13550. Light.prototype.getAbsolutePosition = function () {
  13551. return BABYLON.Vector3.Zero();
  13552. };
  13553. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13554. };
  13555. Light.prototype._getWorldMatrix = function () {
  13556. return BABYLON.Matrix.Identity();
  13557. };
  13558. /**
  13559. * Boolean : True if the light will affect the passed mesh.
  13560. */
  13561. Light.prototype.canAffectMesh = function (mesh) {
  13562. if (!mesh) {
  13563. return true;
  13564. }
  13565. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13566. return false;
  13567. }
  13568. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13569. return false;
  13570. }
  13571. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13572. return false;
  13573. }
  13574. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13575. return false;
  13576. }
  13577. return true;
  13578. };
  13579. /**
  13580. * Returns the light World matrix.
  13581. */
  13582. Light.prototype.getWorldMatrix = function () {
  13583. this._currentRenderId = this.getScene().getRenderId();
  13584. var worldMatrix = this._getWorldMatrix();
  13585. if (this.parent && this.parent.getWorldMatrix) {
  13586. if (!this._parentedWorldMatrix) {
  13587. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13588. }
  13589. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13590. this._markSyncedWithParent();
  13591. return this._parentedWorldMatrix;
  13592. }
  13593. return worldMatrix;
  13594. };
  13595. /**
  13596. * Sort function to order lights for rendering.
  13597. * @param a First Light object to compare to second.
  13598. * @param b Second Light object to compare first.
  13599. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13600. */
  13601. Light.compareLightsPriority = function (a, b) {
  13602. //shadow-casting lights have priority over non-shadow-casting lights
  13603. //the renderPrioirty is a secondary sort criterion
  13604. if (a.shadowEnabled !== b.shadowEnabled) {
  13605. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13606. }
  13607. return b.renderPriority - a.renderPriority;
  13608. };
  13609. /**
  13610. * Disposes the light.
  13611. */
  13612. Light.prototype.dispose = function () {
  13613. if (this._shadowGenerator) {
  13614. this._shadowGenerator.dispose();
  13615. this._shadowGenerator = null;
  13616. }
  13617. // Animations
  13618. this.getScene().stopAnimation(this);
  13619. // Remove from meshes
  13620. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13621. var mesh = _a[_i];
  13622. mesh._removeLightSource(this);
  13623. }
  13624. this._uniformBuffer.dispose();
  13625. // Remove from scene
  13626. this.getScene().removeLight(this);
  13627. _super.prototype.dispose.call(this);
  13628. };
  13629. /**
  13630. * Returns the light type ID (integer).
  13631. */
  13632. Light.prototype.getTypeID = function () {
  13633. return 0;
  13634. };
  13635. /**
  13636. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13637. */
  13638. Light.prototype.getScaledIntensity = function () {
  13639. return this._photometricScale * this.intensity;
  13640. };
  13641. /**
  13642. * Returns a new Light object, named "name", from the current one.
  13643. */
  13644. Light.prototype.clone = function (name) {
  13645. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13646. };
  13647. /**
  13648. * Serializes the current light into a Serialization object.
  13649. * Returns the serialized object.
  13650. */
  13651. Light.prototype.serialize = function () {
  13652. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13653. // Type
  13654. serializationObject.type = this.getTypeID();
  13655. // Parent
  13656. if (this.parent) {
  13657. serializationObject.parentId = this.parent.id;
  13658. }
  13659. // Inclusion / exclusions
  13660. if (this.excludedMeshes.length > 0) {
  13661. serializationObject.excludedMeshesIds = [];
  13662. this.excludedMeshes.forEach(function (mesh) {
  13663. serializationObject.excludedMeshesIds.push(mesh.id);
  13664. });
  13665. }
  13666. if (this.includedOnlyMeshes.length > 0) {
  13667. serializationObject.includedOnlyMeshesIds = [];
  13668. this.includedOnlyMeshes.forEach(function (mesh) {
  13669. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13670. });
  13671. }
  13672. // Animations
  13673. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13674. serializationObject.ranges = this.serializeAnimationRanges();
  13675. return serializationObject;
  13676. };
  13677. /**
  13678. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13679. * This new light is named "name" and added to the passed scene.
  13680. */
  13681. Light.GetConstructorFromName = function (type, name, scene) {
  13682. switch (type) {
  13683. case 0:
  13684. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13685. case 1:
  13686. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13687. case 2:
  13688. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13689. case 3:
  13690. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13691. }
  13692. };
  13693. /**
  13694. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13695. */
  13696. Light.Parse = function (parsedLight, scene) {
  13697. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13698. // Inclusion / exclusions
  13699. if (parsedLight.excludedMeshesIds) {
  13700. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13701. }
  13702. if (parsedLight.includedOnlyMeshesIds) {
  13703. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13704. }
  13705. // Parent
  13706. if (parsedLight.parentId) {
  13707. light._waitingParentId = parsedLight.parentId;
  13708. }
  13709. // Animations
  13710. if (parsedLight.animations) {
  13711. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13712. var parsedAnimation = parsedLight.animations[animationIndex];
  13713. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13714. }
  13715. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13716. }
  13717. if (parsedLight.autoAnimate) {
  13718. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13719. }
  13720. return light;
  13721. };
  13722. Light.prototype._hookArrayForExcluded = function (array) {
  13723. var _this = this;
  13724. var oldPush = array.push;
  13725. array.push = function () {
  13726. var items = [];
  13727. for (var _i = 0; _i < arguments.length; _i++) {
  13728. items[_i] = arguments[_i];
  13729. }
  13730. var result = oldPush.apply(array, items);
  13731. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13732. var item = items_1[_a];
  13733. item._resyncLighSource(_this);
  13734. }
  13735. return result;
  13736. };
  13737. var oldSplice = array.splice;
  13738. array.splice = function (index, deleteCount) {
  13739. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13740. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13741. var item = deleted_1[_i];
  13742. item._resyncLighSource(_this);
  13743. }
  13744. return deleted;
  13745. };
  13746. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13747. var item = array_1[_i];
  13748. item._resyncLighSource(this);
  13749. }
  13750. };
  13751. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13752. var _this = this;
  13753. var oldPush = array.push;
  13754. array.push = function () {
  13755. var items = [];
  13756. for (var _i = 0; _i < arguments.length; _i++) {
  13757. items[_i] = arguments[_i];
  13758. }
  13759. var result = oldPush.apply(array, items);
  13760. _this._resyncMeshes();
  13761. return result;
  13762. };
  13763. var oldSplice = array.splice;
  13764. array.splice = function (index, deleteCount) {
  13765. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13766. _this._resyncMeshes();
  13767. return deleted;
  13768. };
  13769. this._resyncMeshes();
  13770. };
  13771. Light.prototype._resyncMeshes = function () {
  13772. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13773. var mesh = _a[_i];
  13774. mesh._resyncLighSource(this);
  13775. }
  13776. };
  13777. Light.prototype._markMeshesAsLightDirty = function () {
  13778. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13779. var mesh = _a[_i];
  13780. if (mesh._lightSources.indexOf(this) !== -1) {
  13781. mesh._markSubMeshesAsLightDirty();
  13782. }
  13783. }
  13784. };
  13785. /**
  13786. * Recomputes the cached photometric scale if needed.
  13787. */
  13788. Light.prototype._computePhotometricScale = function () {
  13789. this._photometricScale = this._getPhotometricScale();
  13790. this.getScene().resetCachedMaterial();
  13791. };
  13792. /**
  13793. * Returns the Photometric Scale according to the light type and intensity mode.
  13794. */
  13795. Light.prototype._getPhotometricScale = function () {
  13796. var photometricScale = 0.0;
  13797. var lightTypeID = this.getTypeID();
  13798. //get photometric mode
  13799. var photometricMode = this.intensityMode;
  13800. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13801. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13802. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13803. }
  13804. else {
  13805. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13806. }
  13807. }
  13808. //compute photometric scale
  13809. switch (lightTypeID) {
  13810. case Light.LIGHTTYPEID_POINTLIGHT:
  13811. case Light.LIGHTTYPEID_SPOTLIGHT:
  13812. switch (photometricMode) {
  13813. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13814. photometricScale = 1.0 / (4.0 * Math.PI);
  13815. break;
  13816. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13817. photometricScale = 1.0;
  13818. break;
  13819. case Light.INTENSITYMODE_LUMINANCE:
  13820. photometricScale = this.radius * this.radius;
  13821. break;
  13822. }
  13823. break;
  13824. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13825. switch (photometricMode) {
  13826. case Light.INTENSITYMODE_ILLUMINANCE:
  13827. photometricScale = 1.0;
  13828. break;
  13829. case Light.INTENSITYMODE_LUMINANCE:
  13830. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13831. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13832. var apexAngleRadians = this.radius;
  13833. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13834. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13835. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13836. photometricScale = solidAngle;
  13837. break;
  13838. }
  13839. break;
  13840. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13841. // No fall off in hemisperic light.
  13842. photometricScale = 1.0;
  13843. break;
  13844. }
  13845. return photometricScale;
  13846. };
  13847. Light.prototype._reorderLightsInScene = function () {
  13848. var scene = this.getScene();
  13849. if (this.renderPriority != 0) {
  13850. scene.requireLightSorting = true;
  13851. }
  13852. this.getScene().sortLightsByPriority();
  13853. };
  13854. return Light;
  13855. }(BABYLON.Node));
  13856. //lightmapMode Consts
  13857. Light._LIGHTMAP_DEFAULT = 0;
  13858. Light._LIGHTMAP_SPECULAR = 1;
  13859. Light._LIGHTMAP_SHADOWSONLY = 2;
  13860. // Intensity Mode Consts
  13861. Light._INTENSITYMODE_AUTOMATIC = 0;
  13862. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13863. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13864. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13865. Light._INTENSITYMODE_LUMINANCE = 4;
  13866. // Light types ids const.
  13867. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13868. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13869. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13870. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13871. __decorate([
  13872. BABYLON.serializeAsColor3()
  13873. ], Light.prototype, "diffuse", void 0);
  13874. __decorate([
  13875. BABYLON.serializeAsColor3()
  13876. ], Light.prototype, "specular", void 0);
  13877. __decorate([
  13878. BABYLON.serialize()
  13879. ], Light.prototype, "intensity", void 0);
  13880. __decorate([
  13881. BABYLON.serialize()
  13882. ], Light.prototype, "range", void 0);
  13883. __decorate([
  13884. BABYLON.serialize()
  13885. ], Light.prototype, "intensityMode", null);
  13886. __decorate([
  13887. BABYLON.serialize()
  13888. ], Light.prototype, "radius", null);
  13889. __decorate([
  13890. BABYLON.serialize()
  13891. ], Light.prototype, "_renderPriority", void 0);
  13892. __decorate([
  13893. BABYLON.expandToProperty("_reorderLightsInScene")
  13894. ], Light.prototype, "renderPriority", void 0);
  13895. __decorate([
  13896. BABYLON.serialize()
  13897. ], Light.prototype, "shadowEnabled", void 0);
  13898. __decorate([
  13899. BABYLON.serialize("excludeWithLayerMask")
  13900. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13901. __decorate([
  13902. BABYLON.serialize("includeOnlyWithLayerMask")
  13903. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13904. __decorate([
  13905. BABYLON.serialize("lightmapMode")
  13906. ], Light.prototype, "_lightmapMode", void 0);
  13907. BABYLON.Light = Light;
  13908. })(BABYLON || (BABYLON = {}));
  13909. //# sourceMappingURL=babylon.light.js.map
  13910. var BABYLON;
  13911. (function (BABYLON) {
  13912. var Camera = (function (_super) {
  13913. __extends(Camera, _super);
  13914. function Camera(name, position, scene) {
  13915. var _this = _super.call(this, name, scene) || this;
  13916. _this.upVector = BABYLON.Vector3.Up();
  13917. _this.orthoLeft = null;
  13918. _this.orthoRight = null;
  13919. _this.orthoBottom = null;
  13920. _this.orthoTop = null;
  13921. _this.fov = 0.8;
  13922. _this.minZ = 1.0;
  13923. _this.maxZ = 10000.0;
  13924. _this.inertia = 0.9;
  13925. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13926. _this.isIntermediate = false;
  13927. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13928. _this.layerMask = 0x0FFFFFFF;
  13929. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13930. // Camera rig members
  13931. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13932. _this._rigCameras = new Array();
  13933. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13934. _this.customRenderTargets = new Array();
  13935. // Cache
  13936. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13937. _this._projectionMatrix = new BABYLON.Matrix();
  13938. _this._doNotComputeProjectionMatrix = false;
  13939. _this._postProcesses = new Array();
  13940. _this._transformMatrix = BABYLON.Matrix.Zero();
  13941. _this._activeMeshes = new BABYLON.SmartArray(256);
  13942. _this._globalPosition = BABYLON.Vector3.Zero();
  13943. _this._refreshFrustumPlanes = true;
  13944. _this.getScene().addCamera(_this);
  13945. if (!_this.getScene().activeCamera) {
  13946. _this.getScene().activeCamera = _this;
  13947. }
  13948. _this.position = position;
  13949. return _this;
  13950. }
  13951. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13952. get: function () {
  13953. return Camera._PERSPECTIVE_CAMERA;
  13954. },
  13955. enumerable: true,
  13956. configurable: true
  13957. });
  13958. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13959. get: function () {
  13960. return Camera._ORTHOGRAPHIC_CAMERA;
  13961. },
  13962. enumerable: true,
  13963. configurable: true
  13964. });
  13965. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13966. get: function () {
  13967. return Camera._FOVMODE_VERTICAL_FIXED;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13973. get: function () {
  13974. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13980. get: function () {
  13981. return Camera._RIG_MODE_NONE;
  13982. },
  13983. enumerable: true,
  13984. configurable: true
  13985. });
  13986. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13987. get: function () {
  13988. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13989. },
  13990. enumerable: true,
  13991. configurable: true
  13992. });
  13993. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13994. get: function () {
  13995. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14001. get: function () {
  14002. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14003. },
  14004. enumerable: true,
  14005. configurable: true
  14006. });
  14007. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14008. get: function () {
  14009. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14010. },
  14011. enumerable: true,
  14012. configurable: true
  14013. });
  14014. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14015. get: function () {
  14016. return Camera._RIG_MODE_VR;
  14017. },
  14018. enumerable: true,
  14019. configurable: true
  14020. });
  14021. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14022. get: function () {
  14023. return Camera._RIG_MODE_WEBVR;
  14024. },
  14025. enumerable: true,
  14026. configurable: true
  14027. });
  14028. Camera.prototype.getClassName = function () {
  14029. return "Camera";
  14030. };
  14031. /**
  14032. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14033. */
  14034. Camera.prototype.toString = function (fullDetails) {
  14035. var ret = "Name: " + this.name;
  14036. ret += ", type: " + this.getClassName();
  14037. if (this.animations) {
  14038. for (var i = 0; i < this.animations.length; i++) {
  14039. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14040. }
  14041. }
  14042. if (fullDetails) {
  14043. }
  14044. return ret;
  14045. };
  14046. Object.defineProperty(Camera.prototype, "globalPosition", {
  14047. get: function () {
  14048. return this._globalPosition;
  14049. },
  14050. enumerable: true,
  14051. configurable: true
  14052. });
  14053. Camera.prototype.getActiveMeshes = function () {
  14054. return this._activeMeshes;
  14055. };
  14056. Camera.prototype.isActiveMesh = function (mesh) {
  14057. return (this._activeMeshes.indexOf(mesh) !== -1);
  14058. };
  14059. //Cache
  14060. Camera.prototype._initCache = function () {
  14061. _super.prototype._initCache.call(this);
  14062. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14063. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14064. this._cache.mode = undefined;
  14065. this._cache.minZ = undefined;
  14066. this._cache.maxZ = undefined;
  14067. this._cache.fov = undefined;
  14068. this._cache.fovMode = undefined;
  14069. this._cache.aspectRatio = undefined;
  14070. this._cache.orthoLeft = undefined;
  14071. this._cache.orthoRight = undefined;
  14072. this._cache.orthoBottom = undefined;
  14073. this._cache.orthoTop = undefined;
  14074. this._cache.renderWidth = undefined;
  14075. this._cache.renderHeight = undefined;
  14076. };
  14077. Camera.prototype._updateCache = function (ignoreParentClass) {
  14078. if (!ignoreParentClass) {
  14079. _super.prototype._updateCache.call(this);
  14080. }
  14081. var engine = this.getEngine();
  14082. this._cache.position.copyFrom(this.position);
  14083. this._cache.upVector.copyFrom(this.upVector);
  14084. this._cache.mode = this.mode;
  14085. this._cache.minZ = this.minZ;
  14086. this._cache.maxZ = this.maxZ;
  14087. this._cache.fov = this.fov;
  14088. this._cache.fovMode = this.fovMode;
  14089. this._cache.aspectRatio = engine.getAspectRatio(this);
  14090. this._cache.orthoLeft = this.orthoLeft;
  14091. this._cache.orthoRight = this.orthoRight;
  14092. this._cache.orthoBottom = this.orthoBottom;
  14093. this._cache.orthoTop = this.orthoTop;
  14094. this._cache.renderWidth = engine.getRenderWidth();
  14095. this._cache.renderHeight = engine.getRenderHeight();
  14096. };
  14097. Camera.prototype._updateFromScene = function () {
  14098. this.updateCache();
  14099. this.update();
  14100. };
  14101. // Synchronized
  14102. Camera.prototype._isSynchronized = function () {
  14103. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14104. };
  14105. Camera.prototype._isSynchronizedViewMatrix = function () {
  14106. if (!_super.prototype._isSynchronized.call(this))
  14107. return false;
  14108. return this._cache.position.equals(this.position)
  14109. && this._cache.upVector.equals(this.upVector)
  14110. && this.isSynchronizedWithParent();
  14111. };
  14112. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14113. var check = this._cache.mode === this.mode
  14114. && this._cache.minZ === this.minZ
  14115. && this._cache.maxZ === this.maxZ;
  14116. if (!check) {
  14117. return false;
  14118. }
  14119. var engine = this.getEngine();
  14120. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14121. check = this._cache.fov === this.fov
  14122. && this._cache.fovMode === this.fovMode
  14123. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14124. }
  14125. else {
  14126. check = this._cache.orthoLeft === this.orthoLeft
  14127. && this._cache.orthoRight === this.orthoRight
  14128. && this._cache.orthoBottom === this.orthoBottom
  14129. && this._cache.orthoTop === this.orthoTop
  14130. && this._cache.renderWidth === engine.getRenderWidth()
  14131. && this._cache.renderHeight === engine.getRenderHeight();
  14132. }
  14133. return check;
  14134. };
  14135. // Controls
  14136. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14137. };
  14138. Camera.prototype.detachControl = function (element) {
  14139. };
  14140. Camera.prototype.update = function () {
  14141. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14142. this._updateRigCameras();
  14143. }
  14144. this._checkInputs();
  14145. };
  14146. Camera.prototype._checkInputs = function () {
  14147. };
  14148. Object.defineProperty(Camera.prototype, "rigCameras", {
  14149. get: function () {
  14150. return this._rigCameras;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14156. get: function () {
  14157. return this._rigPostProcess;
  14158. },
  14159. enumerable: true,
  14160. configurable: true
  14161. });
  14162. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14163. // invalidate framebuffer
  14164. if (this._postProcesses.length > 0) {
  14165. this._postProcesses[0].markTextureDirty();
  14166. }
  14167. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14168. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14169. var cam = this._rigCameras[i];
  14170. var rigPostProcess = cam._rigPostProcess;
  14171. // for VR rig, there does not have to be a post process
  14172. if (rigPostProcess) {
  14173. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14174. if (isPass) {
  14175. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14176. cam.isIntermediate = this._postProcesses.length === 0;
  14177. }
  14178. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14179. rigPostProcess.markTextureDirty();
  14180. }
  14181. else {
  14182. cam._postProcesses = this._postProcesses.slice(0);
  14183. }
  14184. }
  14185. };
  14186. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14187. if (insertAt === void 0) { insertAt = null; }
  14188. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14189. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14190. return 0;
  14191. }
  14192. if (insertAt == null || insertAt < 0) {
  14193. this._postProcesses.push(postProcess);
  14194. }
  14195. else {
  14196. this._postProcesses.splice(insertAt, 0, postProcess);
  14197. }
  14198. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14199. return this._postProcesses.indexOf(postProcess);
  14200. };
  14201. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14202. if (atIndices === void 0) { atIndices = null; }
  14203. var result = [];
  14204. var i;
  14205. var index;
  14206. if (!atIndices) {
  14207. var idx = this._postProcesses.indexOf(postProcess);
  14208. if (idx !== -1) {
  14209. this._postProcesses.splice(idx, 1);
  14210. }
  14211. }
  14212. else {
  14213. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14214. // iterate descending, so can just splice as we go
  14215. for (i = atIndices.length - 1; i >= 0; i--) {
  14216. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14217. result.push(i);
  14218. continue;
  14219. }
  14220. index = atIndices[i];
  14221. this._postProcesses.splice(index, 1);
  14222. }
  14223. }
  14224. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14225. return result;
  14226. };
  14227. Camera.prototype.getWorldMatrix = function () {
  14228. if (!this._worldMatrix) {
  14229. this._worldMatrix = BABYLON.Matrix.Identity();
  14230. }
  14231. var viewMatrix = this.getViewMatrix();
  14232. viewMatrix.invertToRef(this._worldMatrix);
  14233. return this._worldMatrix;
  14234. };
  14235. Camera.prototype._getViewMatrix = function () {
  14236. return BABYLON.Matrix.Identity();
  14237. };
  14238. Camera.prototype.getViewMatrix = function (force) {
  14239. this._computedViewMatrix = this._computeViewMatrix(force);
  14240. if (!force && this._isSynchronizedViewMatrix()) {
  14241. return this._computedViewMatrix;
  14242. }
  14243. this._refreshFrustumPlanes = true;
  14244. if (!this.parent || !this.parent.getWorldMatrix) {
  14245. this._globalPosition.copyFrom(this.position);
  14246. }
  14247. else {
  14248. if (!this._worldMatrix) {
  14249. this._worldMatrix = BABYLON.Matrix.Identity();
  14250. }
  14251. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14252. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14253. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14254. this._computedViewMatrix.invert();
  14255. this._markSyncedWithParent();
  14256. }
  14257. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14258. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14259. }
  14260. this._currentRenderId = this.getScene().getRenderId();
  14261. return this._computedViewMatrix;
  14262. };
  14263. Camera.prototype._computeViewMatrix = function (force) {
  14264. if (!force && this._isSynchronizedViewMatrix()) {
  14265. return this._computedViewMatrix;
  14266. }
  14267. this._computedViewMatrix = this._getViewMatrix();
  14268. this._currentRenderId = this.getScene().getRenderId();
  14269. return this._computedViewMatrix;
  14270. };
  14271. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14272. this._doNotComputeProjectionMatrix = true;
  14273. if (projection !== undefined) {
  14274. this._projectionMatrix = projection;
  14275. }
  14276. };
  14277. ;
  14278. Camera.prototype.unfreezeProjectionMatrix = function () {
  14279. this._doNotComputeProjectionMatrix = false;
  14280. };
  14281. ;
  14282. Camera.prototype.getProjectionMatrix = function (force) {
  14283. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14284. return this._projectionMatrix;
  14285. }
  14286. this._refreshFrustumPlanes = true;
  14287. var engine = this.getEngine();
  14288. var scene = this.getScene();
  14289. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14290. if (this.minZ <= 0) {
  14291. this.minZ = 0.1;
  14292. }
  14293. if (scene.useRightHandedSystem) {
  14294. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14295. }
  14296. else {
  14297. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14298. }
  14299. return this._projectionMatrix;
  14300. }
  14301. var halfWidth = engine.getRenderWidth() / 2.0;
  14302. var halfHeight = engine.getRenderHeight() / 2.0;
  14303. if (scene.useRightHandedSystem) {
  14304. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14305. }
  14306. else {
  14307. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14308. }
  14309. return this._projectionMatrix;
  14310. };
  14311. Camera.prototype.getTranformationMatrix = function () {
  14312. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14313. return this._transformMatrix;
  14314. };
  14315. Camera.prototype.updateFrustumPlanes = function () {
  14316. if (!this._refreshFrustumPlanes) {
  14317. return;
  14318. }
  14319. this.getTranformationMatrix();
  14320. if (!this._frustumPlanes) {
  14321. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14322. }
  14323. else {
  14324. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14325. }
  14326. this._refreshFrustumPlanes = false;
  14327. };
  14328. Camera.prototype.isInFrustum = function (target) {
  14329. this.updateFrustumPlanes();
  14330. return target.isInFrustum(this._frustumPlanes);
  14331. };
  14332. Camera.prototype.isCompletelyInFrustum = function (target) {
  14333. this.updateFrustumPlanes();
  14334. return target.isCompletelyInFrustum(this._frustumPlanes);
  14335. };
  14336. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14337. if (length === void 0) { length = 100; }
  14338. if (!transform) {
  14339. transform = this.getWorldMatrix();
  14340. }
  14341. if (!origin) {
  14342. origin = this.position;
  14343. }
  14344. var forward = new BABYLON.Vector3(0, 0, 1);
  14345. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14346. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14347. return new BABYLON.Ray(origin, direction, length);
  14348. };
  14349. Camera.prototype.dispose = function () {
  14350. // Animations
  14351. this.getScene().stopAnimation(this);
  14352. // Remove from scene
  14353. this.getScene().removeCamera(this);
  14354. while (this._rigCameras.length > 0) {
  14355. this._rigCameras.pop().dispose();
  14356. }
  14357. // Postprocesses
  14358. var i = this._postProcesses.length;
  14359. while (--i >= 0) {
  14360. this._postProcesses[i].dispose(this);
  14361. }
  14362. _super.prototype.dispose.call(this);
  14363. };
  14364. Object.defineProperty(Camera.prototype, "leftCamera", {
  14365. // ---- Camera rigs section ----
  14366. get: function () {
  14367. if (this._rigCameras.length < 1) {
  14368. return undefined;
  14369. }
  14370. return this._rigCameras[0];
  14371. },
  14372. enumerable: true,
  14373. configurable: true
  14374. });
  14375. Object.defineProperty(Camera.prototype, "rightCamera", {
  14376. get: function () {
  14377. if (this._rigCameras.length < 2) {
  14378. return undefined;
  14379. }
  14380. return this._rigCameras[1];
  14381. },
  14382. enumerable: true,
  14383. configurable: true
  14384. });
  14385. Camera.prototype.getLeftTarget = function () {
  14386. if (this._rigCameras.length < 1) {
  14387. return undefined;
  14388. }
  14389. return this._rigCameras[0].getTarget();
  14390. };
  14391. Camera.prototype.getRightTarget = function () {
  14392. if (this._rigCameras.length < 2) {
  14393. return undefined;
  14394. }
  14395. return this._rigCameras[1].getTarget();
  14396. };
  14397. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14398. while (this._rigCameras.length > 0) {
  14399. this._rigCameras.pop().dispose();
  14400. }
  14401. this.cameraRigMode = mode;
  14402. this._cameraRigParams = {};
  14403. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14404. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14405. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14406. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14407. // create the rig cameras, unless none
  14408. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14409. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14410. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14411. }
  14412. switch (this.cameraRigMode) {
  14413. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14414. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14415. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14416. break;
  14417. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14418. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14419. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14420. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14421. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14422. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14423. break;
  14424. case Camera.RIG_MODE_VR:
  14425. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14426. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14427. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14428. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14429. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14430. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14431. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14432. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14433. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14434. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14435. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14436. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14437. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14438. if (metrics.compensateDistortion) {
  14439. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14440. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14441. }
  14442. break;
  14443. case Camera.RIG_MODE_WEBVR:
  14444. if (rigParams.vrDisplay) {
  14445. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14446. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14447. //Left eye
  14448. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14449. this._rigCameras[0].setCameraRigParameter("left", true);
  14450. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14451. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14452. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14453. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14454. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14455. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14456. this._rigCameras[0].parent = this;
  14457. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14458. //Right eye
  14459. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14460. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14461. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14462. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14463. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14464. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14465. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14466. this._rigCameras[1].parent = this;
  14467. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14468. }
  14469. break;
  14470. }
  14471. this._cascadePostProcessesToRigCams();
  14472. this.
  14473. update();
  14474. };
  14475. Camera.prototype._getVRProjectionMatrix = function () {
  14476. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14477. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14478. return this._projectionMatrix;
  14479. };
  14480. Camera.prototype._updateCameraRotationMatrix = function () {
  14481. //Here for WebVR
  14482. };
  14483. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14484. //Here for WebVR
  14485. };
  14486. /**
  14487. * This function MUST be overwritten by the different WebVR cameras available.
  14488. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14489. */
  14490. Camera.prototype._getWebVRProjectionMatrix = function () {
  14491. return BABYLON.Matrix.Identity();
  14492. };
  14493. /**
  14494. * This function MUST be overwritten by the different WebVR cameras available.
  14495. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14496. */
  14497. Camera.prototype._getWebVRViewMatrix = function () {
  14498. return BABYLON.Matrix.Identity();
  14499. };
  14500. Camera.prototype.setCameraRigParameter = function (name, value) {
  14501. if (!this._cameraRigParams) {
  14502. this._cameraRigParams = {};
  14503. }
  14504. this._cameraRigParams[name] = value;
  14505. //provisionnally:
  14506. if (name === "interaxialDistance") {
  14507. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14508. }
  14509. };
  14510. /**
  14511. * needs to be overridden by children so sub has required properties to be copied
  14512. */
  14513. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14514. return null;
  14515. };
  14516. /**
  14517. * May need to be overridden by children
  14518. */
  14519. Camera.prototype._updateRigCameras = function () {
  14520. for (var i = 0; i < this._rigCameras.length; i++) {
  14521. this._rigCameras[i].minZ = this.minZ;
  14522. this._rigCameras[i].maxZ = this.maxZ;
  14523. this._rigCameras[i].fov = this.fov;
  14524. }
  14525. // only update viewport when ANAGLYPH
  14526. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14527. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14528. }
  14529. };
  14530. Camera.prototype._setupInputs = function () {
  14531. };
  14532. Camera.prototype.serialize = function () {
  14533. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14534. // Type
  14535. serializationObject.type = this.getClassName();
  14536. // Parent
  14537. if (this.parent) {
  14538. serializationObject.parentId = this.parent.id;
  14539. }
  14540. if (this.inputs) {
  14541. this.inputs.serialize(serializationObject);
  14542. }
  14543. // Animations
  14544. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14545. serializationObject.ranges = this.serializeAnimationRanges();
  14546. return serializationObject;
  14547. };
  14548. Camera.prototype.clone = function (name) {
  14549. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14550. };
  14551. Camera.prototype.getDirection = function (localAxis) {
  14552. var result = BABYLON.Vector3.Zero();
  14553. this.getDirectionToRef(localAxis, result);
  14554. return result;
  14555. };
  14556. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14557. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14558. };
  14559. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14560. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14561. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14562. switch (type) {
  14563. case "ArcRotateCamera":
  14564. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14565. case "DeviceOrientationCamera":
  14566. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14567. case "FollowCamera":
  14568. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14569. case "ArcFollowCamera":
  14570. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14571. case "GamepadCamera":
  14572. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14573. case "TouchCamera":
  14574. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14575. case "VirtualJoysticksCamera":
  14576. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14577. case "WebVRFreeCamera":
  14578. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14579. case "WebVRGamepadCamera":
  14580. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14581. case "VRDeviceOrientationFreeCamera":
  14582. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14583. case "VRDeviceOrientationGamepadCamera":
  14584. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14585. case "AnaglyphArcRotateCamera":
  14586. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14587. case "AnaglyphFreeCamera":
  14588. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14589. case "AnaglyphGamepadCamera":
  14590. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14591. case "AnaglyphUniversalCamera":
  14592. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14593. case "StereoscopicArcRotateCamera":
  14594. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14595. case "StereoscopicFreeCamera":
  14596. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14597. case "StereoscopicGamepadCamera":
  14598. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14599. case "StereoscopicUniversalCamera":
  14600. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14601. case "FreeCamera":
  14602. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14603. default:
  14604. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14605. }
  14606. };
  14607. Camera.Parse = function (parsedCamera, scene) {
  14608. var type = parsedCamera.type;
  14609. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14610. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14611. // Parent
  14612. if (parsedCamera.parentId) {
  14613. camera._waitingParentId = parsedCamera.parentId;
  14614. }
  14615. //If camera has an input manager, let it parse inputs settings
  14616. if (camera.inputs) {
  14617. camera.inputs.parse(parsedCamera);
  14618. camera._setupInputs();
  14619. }
  14620. if (camera.setPosition) {
  14621. camera.position.copyFromFloats(0, 0, 0);
  14622. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  14623. }
  14624. // Target
  14625. if (parsedCamera.target) {
  14626. if (camera.setTarget) {
  14627. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14628. }
  14629. }
  14630. // Apply 3d rig, when found
  14631. if (parsedCamera.cameraRigMode) {
  14632. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14633. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14634. }
  14635. // Animations
  14636. if (parsedCamera.animations) {
  14637. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14638. var parsedAnimation = parsedCamera.animations[animationIndex];
  14639. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14640. }
  14641. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14642. }
  14643. if (parsedCamera.autoAnimate) {
  14644. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14645. }
  14646. return camera;
  14647. };
  14648. return Camera;
  14649. }(BABYLON.Node));
  14650. // Statics
  14651. Camera._PERSPECTIVE_CAMERA = 0;
  14652. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14653. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14654. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14655. Camera._RIG_MODE_NONE = 0;
  14656. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14657. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14658. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14659. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14660. Camera._RIG_MODE_VR = 20;
  14661. Camera._RIG_MODE_WEBVR = 21;
  14662. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14663. __decorate([
  14664. BABYLON.serializeAsVector3()
  14665. ], Camera.prototype, "position", void 0);
  14666. __decorate([
  14667. BABYLON.serializeAsVector3()
  14668. ], Camera.prototype, "upVector", void 0);
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], Camera.prototype, "orthoLeft", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], Camera.prototype, "orthoRight", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], Camera.prototype, "orthoBottom", void 0);
  14678. __decorate([
  14679. BABYLON.serialize()
  14680. ], Camera.prototype, "orthoTop", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], Camera.prototype, "fov", void 0);
  14684. __decorate([
  14685. BABYLON.serialize()
  14686. ], Camera.prototype, "minZ", void 0);
  14687. __decorate([
  14688. BABYLON.serialize()
  14689. ], Camera.prototype, "maxZ", void 0);
  14690. __decorate([
  14691. BABYLON.serialize()
  14692. ], Camera.prototype, "inertia", void 0);
  14693. __decorate([
  14694. BABYLON.serialize()
  14695. ], Camera.prototype, "mode", void 0);
  14696. __decorate([
  14697. BABYLON.serialize()
  14698. ], Camera.prototype, "layerMask", void 0);
  14699. __decorate([
  14700. BABYLON.serialize()
  14701. ], Camera.prototype, "fovMode", void 0);
  14702. __decorate([
  14703. BABYLON.serialize()
  14704. ], Camera.prototype, "cameraRigMode", void 0);
  14705. __decorate([
  14706. BABYLON.serialize()
  14707. ], Camera.prototype, "interaxialDistance", void 0);
  14708. __decorate([
  14709. BABYLON.serialize()
  14710. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14711. BABYLON.Camera = Camera;
  14712. })(BABYLON || (BABYLON = {}));
  14713. //# sourceMappingURL=babylon.camera.js.map
  14714. var BABYLON;
  14715. (function (BABYLON) {
  14716. var RenderingManager = (function () {
  14717. function RenderingManager(scene) {
  14718. this._renderingGroups = new Array();
  14719. this._autoClearDepthStencil = {};
  14720. this._customOpaqueSortCompareFn = {};
  14721. this._customAlphaTestSortCompareFn = {};
  14722. this._customTransparentSortCompareFn = {};
  14723. this._renderinGroupInfo = null;
  14724. this._scene = scene;
  14725. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14726. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14727. }
  14728. }
  14729. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14730. if (depth === void 0) { depth = true; }
  14731. if (stencil === void 0) { stencil = true; }
  14732. if (this._depthStencilBufferAlreadyCleaned) {
  14733. return;
  14734. }
  14735. this._scene.getEngine().clear(null, false, depth, stencil);
  14736. this._depthStencilBufferAlreadyCleaned = true;
  14737. };
  14738. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14739. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14740. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14741. var info = null;
  14742. if (observable) {
  14743. if (!this._renderinGroupInfo) {
  14744. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14745. }
  14746. info = this._renderinGroupInfo;
  14747. info.scene = this._scene;
  14748. info.camera = this._scene.activeCamera;
  14749. }
  14750. // Dispatch sprites
  14751. if (renderSprites) {
  14752. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14753. var manager = this._scene.spriteManagers[index];
  14754. this.dispatchSprites(manager);
  14755. }
  14756. }
  14757. // Render
  14758. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14759. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14760. var renderingGroup = this._renderingGroups[index];
  14761. if (!renderingGroup && !observable)
  14762. continue;
  14763. this._currentIndex = index;
  14764. var renderingGroupMask = 0;
  14765. // Fire PRECLEAR stage
  14766. if (observable) {
  14767. renderingGroupMask = Math.pow(2, index);
  14768. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14769. info.renderingGroupId = index;
  14770. observable.notifyObservers(info, renderingGroupMask);
  14771. }
  14772. // Clear depth/stencil if needed
  14773. if (RenderingManager.AUTOCLEAR) {
  14774. var autoClear = this._autoClearDepthStencil[index];
  14775. if (autoClear && autoClear.autoClear) {
  14776. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14777. }
  14778. }
  14779. if (observable) {
  14780. // Fire PREOPAQUE stage
  14781. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14782. observable.notifyObservers(info, renderingGroupMask);
  14783. // Fire PRETRANSPARENT stage
  14784. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14785. observable.notifyObservers(info, renderingGroupMask);
  14786. }
  14787. if (renderingGroup)
  14788. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14789. // Fire POSTTRANSPARENT stage
  14790. if (observable) {
  14791. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14792. observable.notifyObservers(info, renderingGroupMask);
  14793. }
  14794. }
  14795. };
  14796. RenderingManager.prototype.reset = function () {
  14797. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14798. var renderingGroup = this._renderingGroups[index];
  14799. if (renderingGroup) {
  14800. renderingGroup.prepare();
  14801. }
  14802. }
  14803. };
  14804. RenderingManager.prototype.dispose = function () {
  14805. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14806. var renderingGroup = this._renderingGroups[index];
  14807. if (renderingGroup) {
  14808. renderingGroup.dispose();
  14809. }
  14810. }
  14811. this._renderingGroups.length = 0;
  14812. };
  14813. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14814. if (!this._renderingGroups[renderingGroupId]) {
  14815. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14816. }
  14817. };
  14818. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14819. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14820. this._prepareRenderingGroup(renderingGroupId);
  14821. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14822. };
  14823. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14824. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14825. this._prepareRenderingGroup(renderingGroupId);
  14826. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14827. };
  14828. RenderingManager.prototype.dispatch = function (subMesh) {
  14829. var mesh = subMesh.getMesh();
  14830. var renderingGroupId = mesh.renderingGroupId || 0;
  14831. this._prepareRenderingGroup(renderingGroupId);
  14832. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14833. };
  14834. /**
  14835. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14836. * This allowed control for front to back rendering or reversly depending of the special needs.
  14837. *
  14838. * @param renderingGroupId The rendering group id corresponding to its index
  14839. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14840. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14841. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14842. */
  14843. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14844. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14845. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14846. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14847. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14848. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14849. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14850. if (this._renderingGroups[renderingGroupId]) {
  14851. var group = this._renderingGroups[renderingGroupId];
  14852. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14853. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14854. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14855. }
  14856. };
  14857. /**
  14858. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14859. *
  14860. * @param renderingGroupId The rendering group id corresponding to its index
  14861. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14862. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14863. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14864. */
  14865. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14866. if (depth === void 0) { depth = true; }
  14867. if (stencil === void 0) { stencil = true; }
  14868. this._autoClearDepthStencil[renderingGroupId] = {
  14869. autoClear: autoClearDepthStencil,
  14870. depth: depth,
  14871. stencil: stencil
  14872. };
  14873. };
  14874. return RenderingManager;
  14875. }());
  14876. /**
  14877. * The max id used for rendering groups (not included)
  14878. */
  14879. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14880. /**
  14881. * The min id used for rendering groups (included)
  14882. */
  14883. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14884. /**
  14885. * Used to globally prevent autoclearing scenes.
  14886. */
  14887. RenderingManager.AUTOCLEAR = true;
  14888. BABYLON.RenderingManager = RenderingManager;
  14889. })(BABYLON || (BABYLON = {}));
  14890. //# sourceMappingURL=babylon.renderingManager.js.map
  14891. var BABYLON;
  14892. (function (BABYLON) {
  14893. var RenderingGroup = (function () {
  14894. /**
  14895. * Creates a new rendering group.
  14896. * @param index The rendering group index
  14897. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14898. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14899. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14900. */
  14901. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14902. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14903. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14904. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14905. this.index = index;
  14906. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14907. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14908. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14909. this._particleSystems = new BABYLON.SmartArray(256);
  14910. this._spriteManagers = new BABYLON.SmartArray(256);
  14911. this._edgesRenderers = new BABYLON.SmartArray(16);
  14912. this._scene = scene;
  14913. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14914. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14915. this.transparentSortCompareFn = transparentSortCompareFn;
  14916. }
  14917. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14918. /**
  14919. * Set the opaque sort comparison function.
  14920. * If null the sub meshes will be render in the order they were created
  14921. */
  14922. set: function (value) {
  14923. this._opaqueSortCompareFn = value;
  14924. if (value) {
  14925. this._renderOpaque = this.renderOpaqueSorted;
  14926. }
  14927. else {
  14928. this._renderOpaque = RenderingGroup.renderUnsorted;
  14929. }
  14930. },
  14931. enumerable: true,
  14932. configurable: true
  14933. });
  14934. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14935. /**
  14936. * Set the alpha test sort comparison function.
  14937. * If null the sub meshes will be render in the order they were created
  14938. */
  14939. set: function (value) {
  14940. this._alphaTestSortCompareFn = value;
  14941. if (value) {
  14942. this._renderAlphaTest = this.renderAlphaTestSorted;
  14943. }
  14944. else {
  14945. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14946. }
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14952. /**
  14953. * Set the transparent sort comparison function.
  14954. * If null the sub meshes will be render in the order they were created
  14955. */
  14956. set: function (value) {
  14957. if (value) {
  14958. this._transparentSortCompareFn = value;
  14959. }
  14960. else {
  14961. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14962. }
  14963. this._renderTransparent = this.renderTransparentSorted;
  14964. },
  14965. enumerable: true,
  14966. configurable: true
  14967. });
  14968. /**
  14969. * Render all the sub meshes contained in the group.
  14970. * @param customRenderFunction Used to override the default render behaviour of the group.
  14971. * @returns true if rendered some submeshes.
  14972. */
  14973. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14974. if (customRenderFunction) {
  14975. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14976. return;
  14977. }
  14978. var engine = this._scene.getEngine();
  14979. // Opaque
  14980. if (this._opaqueSubMeshes.length !== 0) {
  14981. this._renderOpaque(this._opaqueSubMeshes);
  14982. }
  14983. // Alpha test
  14984. if (this._alphaTestSubMeshes.length !== 0) {
  14985. engine.setAlphaTesting(true);
  14986. this._renderAlphaTest(this._alphaTestSubMeshes);
  14987. engine.setAlphaTesting(false);
  14988. }
  14989. var stencilState = engine.getStencilBuffer();
  14990. engine.setStencilBuffer(false);
  14991. // Sprites
  14992. if (renderSprites) {
  14993. this._renderSprites();
  14994. }
  14995. // Particles
  14996. if (renderParticles) {
  14997. this._renderParticles(activeMeshes);
  14998. }
  14999. if (this.onBeforeTransparentRendering) {
  15000. this.onBeforeTransparentRendering();
  15001. }
  15002. // Transparent
  15003. if (this._transparentSubMeshes.length !== 0) {
  15004. this._renderTransparent(this._transparentSubMeshes);
  15005. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15006. }
  15007. engine.setStencilBuffer(stencilState);
  15008. // Edges
  15009. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15010. this._edgesRenderers.data[edgesRendererIndex].render();
  15011. }
  15012. };
  15013. /**
  15014. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15015. * @param subMeshes The submeshes to render
  15016. */
  15017. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15018. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15019. };
  15020. /**
  15021. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15022. * @param subMeshes The submeshes to render
  15023. */
  15024. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15025. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15026. };
  15027. /**
  15028. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15029. * @param subMeshes The submeshes to render
  15030. */
  15031. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15032. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15033. };
  15034. /**
  15035. * Renders the submeshes in a specified order.
  15036. * @param subMeshes The submeshes to sort before render
  15037. * @param sortCompareFn The comparison function use to sort
  15038. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15039. * @param transparent Specifies to activate blending if true
  15040. */
  15041. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15042. var subIndex = 0;
  15043. var subMesh;
  15044. for (; subIndex < subMeshes.length; subIndex++) {
  15045. subMesh = subMeshes.data[subIndex];
  15046. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15047. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15048. }
  15049. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15050. sortedArray.sort(sortCompareFn);
  15051. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15052. subMesh = sortedArray[subIndex];
  15053. subMesh.render(transparent);
  15054. }
  15055. };
  15056. /**
  15057. * Renders the submeshes in the order they were dispatched (no sort applied).
  15058. * @param subMeshes The submeshes to render
  15059. */
  15060. RenderingGroup.renderUnsorted = function (subMeshes) {
  15061. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15062. var submesh = subMeshes.data[subIndex];
  15063. submesh.render(false);
  15064. }
  15065. };
  15066. /**
  15067. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15068. * are rendered back to front if in the same alpha index.
  15069. *
  15070. * @param a The first submesh
  15071. * @param b The second submesh
  15072. * @returns The result of the comparison
  15073. */
  15074. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15075. // Alpha index first
  15076. if (a._alphaIndex > b._alphaIndex) {
  15077. return 1;
  15078. }
  15079. if (a._alphaIndex < b._alphaIndex) {
  15080. return -1;
  15081. }
  15082. // Then distance to camera
  15083. return RenderingGroup.backToFrontSortCompare(a, b);
  15084. };
  15085. /**
  15086. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15087. * are rendered back to front.
  15088. *
  15089. * @param a The first submesh
  15090. * @param b The second submesh
  15091. * @returns The result of the comparison
  15092. */
  15093. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15094. // Then distance to camera
  15095. if (a._distanceToCamera < b._distanceToCamera) {
  15096. return 1;
  15097. }
  15098. if (a._distanceToCamera > b._distanceToCamera) {
  15099. return -1;
  15100. }
  15101. return 0;
  15102. };
  15103. /**
  15104. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15105. * are rendered front to back (prevent overdraw).
  15106. *
  15107. * @param a The first submesh
  15108. * @param b The second submesh
  15109. * @returns The result of the comparison
  15110. */
  15111. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15112. // Then distance to camera
  15113. if (a._distanceToCamera < b._distanceToCamera) {
  15114. return -1;
  15115. }
  15116. if (a._distanceToCamera > b._distanceToCamera) {
  15117. return 1;
  15118. }
  15119. return 0;
  15120. };
  15121. /**
  15122. * Resets the different lists of submeshes to prepare a new frame.
  15123. */
  15124. RenderingGroup.prototype.prepare = function () {
  15125. this._opaqueSubMeshes.reset();
  15126. this._transparentSubMeshes.reset();
  15127. this._alphaTestSubMeshes.reset();
  15128. this._particleSystems.reset();
  15129. this._spriteManagers.reset();
  15130. this._edgesRenderers.reset();
  15131. };
  15132. RenderingGroup.prototype.dispose = function () {
  15133. this._opaqueSubMeshes.dispose();
  15134. this._transparentSubMeshes.dispose();
  15135. this._alphaTestSubMeshes.dispose();
  15136. this._particleSystems.dispose();
  15137. this._spriteManagers.dispose();
  15138. this._edgesRenderers.dispose();
  15139. };
  15140. /**
  15141. * Inserts the submesh in its correct queue depending on its material.
  15142. * @param subMesh The submesh to dispatch
  15143. */
  15144. RenderingGroup.prototype.dispatch = function (subMesh) {
  15145. var material = subMesh.getMaterial();
  15146. var mesh = subMesh.getMesh();
  15147. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15148. this._transparentSubMeshes.push(subMesh);
  15149. }
  15150. else if (material.needAlphaTesting()) {
  15151. this._alphaTestSubMeshes.push(subMesh);
  15152. }
  15153. else {
  15154. this._opaqueSubMeshes.push(subMesh); // Opaque
  15155. }
  15156. if (mesh._edgesRenderer) {
  15157. this._edgesRenderers.push(mesh._edgesRenderer);
  15158. }
  15159. };
  15160. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15161. this._spriteManagers.push(spriteManager);
  15162. };
  15163. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15164. this._particleSystems.push(particleSystem);
  15165. };
  15166. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15167. if (this._particleSystems.length === 0) {
  15168. return;
  15169. }
  15170. // Particles
  15171. var activeCamera = this._scene.activeCamera;
  15172. this._scene._particlesDuration.beginMonitoring();
  15173. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15174. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15175. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15176. continue;
  15177. }
  15178. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15179. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15180. }
  15181. }
  15182. this._scene._particlesDuration.endMonitoring(false);
  15183. };
  15184. RenderingGroup.prototype._renderSprites = function () {
  15185. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15186. return;
  15187. }
  15188. // Sprites
  15189. var activeCamera = this._scene.activeCamera;
  15190. this._scene._spritesDuration.beginMonitoring();
  15191. for (var id = 0; id < this._spriteManagers.length; id++) {
  15192. var spriteManager = this._spriteManagers.data[id];
  15193. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15194. spriteManager.render();
  15195. }
  15196. }
  15197. this._scene._spritesDuration.endMonitoring(false);
  15198. };
  15199. return RenderingGroup;
  15200. }());
  15201. BABYLON.RenderingGroup = RenderingGroup;
  15202. })(BABYLON || (BABYLON = {}));
  15203. //# sourceMappingURL=babylon.renderingGroup.js.map
  15204. var BABYLON;
  15205. (function (BABYLON) {
  15206. var ClickInfo = (function () {
  15207. function ClickInfo() {
  15208. this._singleClick = false;
  15209. this._doubleClick = false;
  15210. this._hasSwiped = false;
  15211. this._ignore = false;
  15212. }
  15213. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15214. get: function () {
  15215. return this._singleClick;
  15216. },
  15217. set: function (b) {
  15218. this._singleClick = b;
  15219. },
  15220. enumerable: true,
  15221. configurable: true
  15222. });
  15223. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15224. get: function () {
  15225. return this._doubleClick;
  15226. },
  15227. set: function (b) {
  15228. this._doubleClick = b;
  15229. },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15234. get: function () {
  15235. return this._hasSwiped;
  15236. },
  15237. set: function (b) {
  15238. this._hasSwiped = b;
  15239. },
  15240. enumerable: true,
  15241. configurable: true
  15242. });
  15243. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15244. get: function () {
  15245. return this._ignore;
  15246. },
  15247. set: function (b) {
  15248. this._ignore = b;
  15249. },
  15250. enumerable: true,
  15251. configurable: true
  15252. });
  15253. return ClickInfo;
  15254. }());
  15255. var PointerEventTypes = (function () {
  15256. function PointerEventTypes() {
  15257. }
  15258. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15259. get: function () {
  15260. return PointerEventTypes._POINTERDOWN;
  15261. },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15266. get: function () {
  15267. return PointerEventTypes._POINTERUP;
  15268. },
  15269. enumerable: true,
  15270. configurable: true
  15271. });
  15272. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15273. get: function () {
  15274. return PointerEventTypes._POINTERMOVE;
  15275. },
  15276. enumerable: true,
  15277. configurable: true
  15278. });
  15279. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15280. get: function () {
  15281. return PointerEventTypes._POINTERWHEEL;
  15282. },
  15283. enumerable: true,
  15284. configurable: true
  15285. });
  15286. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15287. get: function () {
  15288. return PointerEventTypes._POINTERPICK;
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15294. get: function () {
  15295. return PointerEventTypes._POINTERTAP;
  15296. },
  15297. enumerable: true,
  15298. configurable: true
  15299. });
  15300. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15301. get: function () {
  15302. return PointerEventTypes._POINTERDOUBLETAP;
  15303. },
  15304. enumerable: true,
  15305. configurable: true
  15306. });
  15307. return PointerEventTypes;
  15308. }());
  15309. PointerEventTypes._POINTERDOWN = 0x01;
  15310. PointerEventTypes._POINTERUP = 0x02;
  15311. PointerEventTypes._POINTERMOVE = 0x04;
  15312. PointerEventTypes._POINTERWHEEL = 0x08;
  15313. PointerEventTypes._POINTERPICK = 0x10;
  15314. PointerEventTypes._POINTERTAP = 0x20;
  15315. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15316. BABYLON.PointerEventTypes = PointerEventTypes;
  15317. var PointerInfoBase = (function () {
  15318. function PointerInfoBase(type, event) {
  15319. this.type = type;
  15320. this.event = event;
  15321. }
  15322. return PointerInfoBase;
  15323. }());
  15324. BABYLON.PointerInfoBase = PointerInfoBase;
  15325. /**
  15326. * This class is used to store pointer related info for the onPrePointerObservable event.
  15327. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15328. */
  15329. var PointerInfoPre = (function (_super) {
  15330. __extends(PointerInfoPre, _super);
  15331. function PointerInfoPre(type, event, localX, localY) {
  15332. var _this = _super.call(this, type, event) || this;
  15333. _this.skipOnPointerObservable = false;
  15334. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15335. return _this;
  15336. }
  15337. return PointerInfoPre;
  15338. }(PointerInfoBase));
  15339. BABYLON.PointerInfoPre = PointerInfoPre;
  15340. /**
  15341. * This type contains all the data related to a pointer event in Babylon.js.
  15342. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  15343. */
  15344. var PointerInfo = (function (_super) {
  15345. __extends(PointerInfo, _super);
  15346. function PointerInfo(type, event, pickInfo) {
  15347. var _this = _super.call(this, type, event) || this;
  15348. _this.pickInfo = pickInfo;
  15349. return _this;
  15350. }
  15351. return PointerInfo;
  15352. }(PointerInfoBase));
  15353. BABYLON.PointerInfo = PointerInfo;
  15354. /**
  15355. * This class is used by the onRenderingGroupObservable
  15356. */
  15357. var RenderingGroupInfo = (function () {
  15358. function RenderingGroupInfo() {
  15359. }
  15360. return RenderingGroupInfo;
  15361. }());
  15362. /**
  15363. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15364. * This stage will be fired no matter what
  15365. */
  15366. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15367. /**
  15368. * Called before opaque object are rendered.
  15369. * This stage will be fired only if there's 3D Opaque content to render
  15370. */
  15371. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15372. /**
  15373. * Called after the opaque objects are rendered and before the transparent ones
  15374. * This stage will be fired only if there's 3D transparent content to render
  15375. */
  15376. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15377. /**
  15378. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15379. * This stage will be fired no matter what
  15380. */
  15381. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15382. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15383. /**
  15384. * Represents a scene to be rendered by the engine.
  15385. * @see http://doc.babylonjs.com/page.php?p=21911
  15386. */
  15387. var Scene = (function () {
  15388. /**
  15389. * @constructor
  15390. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15391. */
  15392. function Scene(engine) {
  15393. // Members
  15394. this.autoClear = true;
  15395. this.autoClearDepthAndStencil = true;
  15396. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15397. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15398. this.forceWireframe = false;
  15399. this._forcePointsCloud = false;
  15400. this.forceShowBoundingBoxes = false;
  15401. this.animationsEnabled = true;
  15402. this.constantlyUpdateMeshUnderPointer = false;
  15403. this.hoverCursor = "pointer";
  15404. // Metadata
  15405. this.metadata = null;
  15406. // Events
  15407. /**
  15408. * An event triggered when the scene is disposed.
  15409. * @type {BABYLON.Observable}
  15410. */
  15411. this.onDisposeObservable = new BABYLON.Observable();
  15412. /**
  15413. * An event triggered before rendering the scene
  15414. * @type {BABYLON.Observable}
  15415. */
  15416. this.onBeforeRenderObservable = new BABYLON.Observable();
  15417. /**
  15418. * An event triggered after rendering the scene
  15419. * @type {BABYLON.Observable}
  15420. */
  15421. this.onAfterRenderObservable = new BABYLON.Observable();
  15422. /**
  15423. * An event triggered when the scene is ready
  15424. * @type {BABYLON.Observable}
  15425. */
  15426. this.onReadyObservable = new BABYLON.Observable();
  15427. /**
  15428. * An event triggered before rendering a camera
  15429. * @type {BABYLON.Observable}
  15430. */
  15431. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15432. /**
  15433. * An event triggered after rendering a camera
  15434. * @type {BABYLON.Observable}
  15435. */
  15436. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15437. /**
  15438. * An event triggered when a camera is created
  15439. * @type {BABYLON.Observable}
  15440. */
  15441. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15442. /**
  15443. * An event triggered when a camera is removed
  15444. * @type {BABYLON.Observable}
  15445. */
  15446. this.onCameraRemovedObservable = new BABYLON.Observable();
  15447. /**
  15448. * An event triggered when a light is created
  15449. * @type {BABYLON.Observable}
  15450. */
  15451. this.onNewLightAddedObservable = new BABYLON.Observable();
  15452. /**
  15453. * An event triggered when a light is removed
  15454. * @type {BABYLON.Observable}
  15455. */
  15456. this.onLightRemovedObservable = new BABYLON.Observable();
  15457. /**
  15458. * An event triggered when a geometry is created
  15459. * @type {BABYLON.Observable}
  15460. */
  15461. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15462. /**
  15463. * An event triggered when a geometry is removed
  15464. * @type {BABYLON.Observable}
  15465. */
  15466. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15467. /**
  15468. * An event triggered when a mesh is created
  15469. * @type {BABYLON.Observable}
  15470. */
  15471. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15472. /**
  15473. * An event triggered when a mesh is removed
  15474. * @type {BABYLON.Observable}
  15475. */
  15476. this.onMeshRemovedObservable = new BABYLON.Observable();
  15477. /**
  15478. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15479. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15480. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  15481. */
  15482. this.onRenderingGroupObservable = new BABYLON.Observable();
  15483. // Animations
  15484. this.animations = [];
  15485. /**
  15486. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  15487. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15488. */
  15489. this.onPrePointerObservable = new BABYLON.Observable();
  15490. /**
  15491. * Observable event triggered each time an input event is received from the rendering canvas
  15492. */
  15493. this.onPointerObservable = new BABYLON.Observable();
  15494. this._meshPickProceed = false;
  15495. this._previousHasSwiped = false;
  15496. this._currentPickResult = null;
  15497. this._previousPickResult = null;
  15498. this._isButtonPressed = false;
  15499. this._doubleClickOccured = false;
  15500. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  15501. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15502. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15503. this._startingPointerTime = 0;
  15504. this._previousStartingPointerTime = 0;
  15505. // Coordinate system
  15506. /**
  15507. * use right-handed coordinate system on this scene.
  15508. * @type {boolean}
  15509. */
  15510. this._useRightHandedSystem = false;
  15511. // Fog
  15512. /**
  15513. * is fog enabled on this scene.
  15514. * @type {boolean}
  15515. */
  15516. this._fogEnabled = true;
  15517. this._fogMode = Scene.FOGMODE_NONE;
  15518. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15519. this.fogDensity = 0.1;
  15520. this.fogStart = 0;
  15521. this.fogEnd = 1000.0;
  15522. // Lights
  15523. /**
  15524. * is shadow enabled on this scene.
  15525. * @type {boolean}
  15526. */
  15527. this._shadowsEnabled = true;
  15528. /**
  15529. * is light enabled on this scene.
  15530. * @type {boolean}
  15531. */
  15532. this._lightsEnabled = true;
  15533. /**
  15534. * All of the lights added to this scene.
  15535. * @see BABYLON.Light
  15536. * @type {BABYLON.Light[]}
  15537. */
  15538. this.lights = new Array();
  15539. // Cameras
  15540. /**
  15541. * All of the cameras added to this scene.
  15542. * @see BABYLON.Camera
  15543. * @type {BABYLON.Camera[]}
  15544. */
  15545. this.cameras = new Array();
  15546. this.activeCameras = new Array();
  15547. // Meshes
  15548. /**
  15549. * All of the (abstract) meshes added to this scene.
  15550. * @see BABYLON.AbstractMesh
  15551. * @type {BABYLON.AbstractMesh[]}
  15552. */
  15553. this.meshes = new Array();
  15554. // Geometries
  15555. this._geometries = new Array();
  15556. this.materials = new Array();
  15557. this.multiMaterials = new Array();
  15558. // Textures
  15559. this._texturesEnabled = true;
  15560. this.textures = new Array();
  15561. // Particles
  15562. this.particlesEnabled = true;
  15563. this.particleSystems = new Array();
  15564. // Sprites
  15565. this.spritesEnabled = true;
  15566. this.spriteManagers = new Array();
  15567. // Layers
  15568. this.layers = new Array();
  15569. this.highlightLayers = new Array();
  15570. // Skeletons
  15571. this._skeletonsEnabled = true;
  15572. this.skeletons = new Array();
  15573. // Morph targets
  15574. this.morphTargetManagers = new Array();
  15575. // Lens flares
  15576. this.lensFlaresEnabled = true;
  15577. this.lensFlareSystems = new Array();
  15578. // Collisions
  15579. this.collisionsEnabled = true;
  15580. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15581. // Postprocesses
  15582. this.postProcessesEnabled = true;
  15583. // Customs render targets
  15584. this.renderTargetsEnabled = true;
  15585. this.dumpNextRenderTargets = false;
  15586. this.customRenderTargets = new Array();
  15587. // Imported meshes
  15588. this.importedMeshesFiles = new Array();
  15589. // Probes
  15590. this.probesEnabled = true;
  15591. this.reflectionProbes = new Array();
  15592. this._actionManagers = new Array();
  15593. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15594. // Procedural textures
  15595. this.proceduralTexturesEnabled = true;
  15596. this._proceduralTextures = new Array();
  15597. this.soundTracks = new Array();
  15598. this._audioEnabled = true;
  15599. this._headphone = false;
  15600. // Performance counters
  15601. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15602. this._totalLightsCounter = new BABYLON.PerfCounter();
  15603. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15604. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15605. this._totalVertices = new BABYLON.PerfCounter();
  15606. this._activeIndices = new BABYLON.PerfCounter();
  15607. this._activeParticles = new BABYLON.PerfCounter();
  15608. this._lastFrameDuration = new BABYLON.PerfCounter();
  15609. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15610. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15611. this._particlesDuration = new BABYLON.PerfCounter();
  15612. this._renderDuration = new BABYLON.PerfCounter();
  15613. this._spritesDuration = new BABYLON.PerfCounter();
  15614. this._activeBones = new BABYLON.PerfCounter();
  15615. this._animationTime = 0;
  15616. this.animationTimeScale = 1;
  15617. this._renderId = 0;
  15618. this._executeWhenReadyTimeoutId = -1;
  15619. this._intermediateRendering = false;
  15620. this._viewUpdateFlag = -1;
  15621. this._projectionUpdateFlag = -1;
  15622. this._toBeDisposed = new BABYLON.SmartArray(256);
  15623. this._pendingData = []; //ANY
  15624. this._activeMeshes = new BABYLON.SmartArray(256);
  15625. this._processedMaterials = new BABYLON.SmartArray(256);
  15626. this._renderTargets = new BABYLON.SmartArray(256);
  15627. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15628. this._activeSkeletons = new BABYLON.SmartArray(32);
  15629. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15630. this._activeAnimatables = new Array();
  15631. this._transformMatrix = BABYLON.Matrix.Zero();
  15632. this.requireLightSorting = false;
  15633. this._uniqueIdCounter = 0;
  15634. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15635. this._engine.scenes.push(this);
  15636. this._uid = null;
  15637. this._renderingManager = new BABYLON.RenderingManager(this);
  15638. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15639. if (BABYLON.OutlineRenderer) {
  15640. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15641. }
  15642. this.attachControl();
  15643. if (BABYLON.SoundTrack) {
  15644. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15645. }
  15646. //simplification queue
  15647. if (BABYLON.SimplificationQueue) {
  15648. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15649. }
  15650. //collision coordinator initialization. For now legacy per default.
  15651. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15652. // Uniform Buffer
  15653. this._createUbo();
  15654. // Default Image processing definition.
  15655. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  15656. }
  15657. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15658. get: function () {
  15659. return Scene._FOGMODE_NONE;
  15660. },
  15661. enumerable: true,
  15662. configurable: true
  15663. });
  15664. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15665. get: function () {
  15666. return Scene._FOGMODE_EXP;
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15672. get: function () {
  15673. return Scene._FOGMODE_EXP2;
  15674. },
  15675. enumerable: true,
  15676. configurable: true
  15677. });
  15678. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15679. get: function () {
  15680. return Scene._FOGMODE_LINEAR;
  15681. },
  15682. enumerable: true,
  15683. configurable: true
  15684. });
  15685. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15686. /**
  15687. * Texture used in all pbr material as the reflection texture.
  15688. * As in the majority of the scene they are the same (exception for multi room and so on),
  15689. * this is easier to reference from here than from all the materials.
  15690. */
  15691. get: function () {
  15692. return this._environmentTexture;
  15693. },
  15694. /**
  15695. * Texture used in all pbr material as the reflection texture.
  15696. * As in the majority of the scene they are the same (exception for multi room and so on),
  15697. * this is easier to set here than in all the materials.
  15698. */
  15699. set: function (value) {
  15700. this._environmentTexture = value;
  15701. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15702. },
  15703. enumerable: true,
  15704. configurable: true
  15705. });
  15706. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  15707. /**
  15708. * Default image processing configuration used either in the rendering
  15709. * Forward main pass or through the imageProcessingPostProcess if present.
  15710. * As in the majority of the scene they are the same (exception for multi camera),
  15711. * this is easier to reference from here than from all the materials and post process.
  15712. *
  15713. * No setter as we it is a shared configuration, you can set the values instead.
  15714. */
  15715. get: function () {
  15716. return this._imageProcessingConfiguration;
  15717. },
  15718. enumerable: true,
  15719. configurable: true
  15720. });
  15721. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15722. get: function () {
  15723. return this._forcePointsCloud;
  15724. },
  15725. set: function (value) {
  15726. if (this._forcePointsCloud === value) {
  15727. return;
  15728. }
  15729. this._forcePointsCloud = value;
  15730. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Object.defineProperty(Scene.prototype, "onDispose", {
  15736. set: function (callback) {
  15737. if (this._onDisposeObserver) {
  15738. this.onDisposeObservable.remove(this._onDisposeObserver);
  15739. }
  15740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(Scene.prototype, "beforeRender", {
  15746. set: function (callback) {
  15747. if (this._onBeforeRenderObserver) {
  15748. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15749. }
  15750. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15751. },
  15752. enumerable: true,
  15753. configurable: true
  15754. });
  15755. Object.defineProperty(Scene.prototype, "afterRender", {
  15756. set: function (callback) {
  15757. if (this._onAfterRenderObserver) {
  15758. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15759. }
  15760. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15766. set: function (callback) {
  15767. if (this._onBeforeCameraRenderObserver) {
  15768. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15769. }
  15770. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15776. set: function (callback) {
  15777. if (this._onAfterCameraRenderObserver) {
  15778. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15779. }
  15780. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15786. get: function () {
  15787. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15793. get: function () {
  15794. return this._useRightHandedSystem;
  15795. },
  15796. set: function (value) {
  15797. if (this._useRightHandedSystem === value) {
  15798. return;
  15799. }
  15800. this._useRightHandedSystem = value;
  15801. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15802. },
  15803. enumerable: true,
  15804. configurable: true
  15805. });
  15806. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15807. get: function () {
  15808. return this._fogEnabled;
  15809. },
  15810. set: function (value) {
  15811. if (this._fogEnabled === value) {
  15812. return;
  15813. }
  15814. this._fogEnabled = value;
  15815. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15816. },
  15817. enumerable: true,
  15818. configurable: true
  15819. });
  15820. Object.defineProperty(Scene.prototype, "fogMode", {
  15821. get: function () {
  15822. return this._fogMode;
  15823. },
  15824. set: function (value) {
  15825. if (this._fogMode === value) {
  15826. return;
  15827. }
  15828. this._fogMode = value;
  15829. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15830. },
  15831. enumerable: true,
  15832. configurable: true
  15833. });
  15834. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15835. get: function () {
  15836. return this._shadowsEnabled;
  15837. },
  15838. set: function (value) {
  15839. if (this._shadowsEnabled === value) {
  15840. return;
  15841. }
  15842. this._shadowsEnabled = value;
  15843. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15844. },
  15845. enumerable: true,
  15846. configurable: true
  15847. });
  15848. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15849. get: function () {
  15850. return this._lightsEnabled;
  15851. },
  15852. set: function (value) {
  15853. if (this._lightsEnabled === value) {
  15854. return;
  15855. }
  15856. this._lightsEnabled = value;
  15857. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15858. },
  15859. enumerable: true,
  15860. configurable: true
  15861. });
  15862. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15863. get: function () {
  15864. if (!this._defaultMaterial) {
  15865. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15866. }
  15867. return this._defaultMaterial;
  15868. },
  15869. set: function (value) {
  15870. this._defaultMaterial = value;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15876. get: function () {
  15877. return this._texturesEnabled;
  15878. },
  15879. set: function (value) {
  15880. if (this._texturesEnabled === value) {
  15881. return;
  15882. }
  15883. this._texturesEnabled = value;
  15884. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15885. },
  15886. enumerable: true,
  15887. configurable: true
  15888. });
  15889. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15890. get: function () {
  15891. return this._skeletonsEnabled;
  15892. },
  15893. set: function (value) {
  15894. if (this._skeletonsEnabled === value) {
  15895. return;
  15896. }
  15897. this._skeletonsEnabled = value;
  15898. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15899. },
  15900. enumerable: true,
  15901. configurable: true
  15902. });
  15903. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15904. get: function () {
  15905. if (!this._postProcessRenderPipelineManager) {
  15906. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15907. }
  15908. return this._postProcessRenderPipelineManager;
  15909. },
  15910. enumerable: true,
  15911. configurable: true
  15912. });
  15913. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15914. get: function () {
  15915. return this._frustumPlanes;
  15916. },
  15917. enumerable: true,
  15918. configurable: true
  15919. });
  15920. Object.defineProperty(Scene.prototype, "debugLayer", {
  15921. // Properties
  15922. get: function () {
  15923. if (!this._debugLayer) {
  15924. this._debugLayer = new BABYLON.DebugLayer(this);
  15925. }
  15926. return this._debugLayer;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15932. get: function () {
  15933. return this._workerCollisions;
  15934. },
  15935. set: function (enabled) {
  15936. if (!BABYLON.CollisionCoordinatorLegacy) {
  15937. return;
  15938. }
  15939. enabled = (enabled && !!Worker);
  15940. this._workerCollisions = enabled;
  15941. if (this.collisionCoordinator) {
  15942. this.collisionCoordinator.destroy();
  15943. }
  15944. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15945. this.collisionCoordinator.init(this);
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15951. get: function () {
  15952. return this._selectionOctree;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15958. /**
  15959. * The mesh that is currently under the pointer.
  15960. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15961. */
  15962. get: function () {
  15963. return this._pointerOverMesh;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Object.defineProperty(Scene.prototype, "pointerX", {
  15969. /**
  15970. * Current on-screen X position of the pointer
  15971. * @return {number} X position of the pointer
  15972. */
  15973. get: function () {
  15974. return this._pointerX;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(Scene.prototype, "pointerY", {
  15980. /**
  15981. * Current on-screen Y position of the pointer
  15982. * @return {number} Y position of the pointer
  15983. */
  15984. get: function () {
  15985. return this._pointerY;
  15986. },
  15987. enumerable: true,
  15988. configurable: true
  15989. });
  15990. Scene.prototype.getCachedMaterial = function () {
  15991. return this._cachedMaterial;
  15992. };
  15993. Scene.prototype.getCachedEffect = function () {
  15994. return this._cachedEffect;
  15995. };
  15996. Scene.prototype.getCachedVisibility = function () {
  15997. return this._cachedVisibility;
  15998. };
  15999. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  16000. if (visibility === void 0) { visibility = 0; }
  16001. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16002. };
  16003. Scene.prototype.getBoundingBoxRenderer = function () {
  16004. if (!this._boundingBoxRenderer) {
  16005. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16006. }
  16007. return this._boundingBoxRenderer;
  16008. };
  16009. Scene.prototype.getOutlineRenderer = function () {
  16010. return this._outlineRenderer;
  16011. };
  16012. Scene.prototype.getEngine = function () {
  16013. return this._engine;
  16014. };
  16015. Scene.prototype.getTotalVertices = function () {
  16016. return this._totalVertices.current;
  16017. };
  16018. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16019. get: function () {
  16020. return this._totalVertices;
  16021. },
  16022. enumerable: true,
  16023. configurable: true
  16024. });
  16025. Scene.prototype.getActiveIndices = function () {
  16026. return this._activeIndices.current;
  16027. };
  16028. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16029. get: function () {
  16030. return this._activeIndices;
  16031. },
  16032. enumerable: true,
  16033. configurable: true
  16034. });
  16035. Scene.prototype.getActiveParticles = function () {
  16036. return this._activeParticles.current;
  16037. };
  16038. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16039. get: function () {
  16040. return this._activeParticles;
  16041. },
  16042. enumerable: true,
  16043. configurable: true
  16044. });
  16045. Scene.prototype.getActiveBones = function () {
  16046. return this._activeBones.current;
  16047. };
  16048. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16049. get: function () {
  16050. return this._activeBones;
  16051. },
  16052. enumerable: true,
  16053. configurable: true
  16054. });
  16055. // Stats
  16056. Scene.prototype.getLastFrameDuration = function () {
  16057. return this._lastFrameDuration.current;
  16058. };
  16059. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16060. get: function () {
  16061. return this._lastFrameDuration;
  16062. },
  16063. enumerable: true,
  16064. configurable: true
  16065. });
  16066. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16067. return this._evaluateActiveMeshesDuration.current;
  16068. };
  16069. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16070. get: function () {
  16071. return this._evaluateActiveMeshesDuration;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Scene.prototype.getActiveMeshes = function () {
  16077. return this._activeMeshes;
  16078. };
  16079. Scene.prototype.getRenderTargetsDuration = function () {
  16080. return this._renderTargetsDuration.current;
  16081. };
  16082. Scene.prototype.getRenderDuration = function () {
  16083. return this._renderDuration.current;
  16084. };
  16085. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16086. get: function () {
  16087. return this._renderDuration;
  16088. },
  16089. enumerable: true,
  16090. configurable: true
  16091. });
  16092. Scene.prototype.getParticlesDuration = function () {
  16093. return this._particlesDuration.current;
  16094. };
  16095. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16096. get: function () {
  16097. return this._particlesDuration;
  16098. },
  16099. enumerable: true,
  16100. configurable: true
  16101. });
  16102. Scene.prototype.getSpritesDuration = function () {
  16103. return this._spritesDuration.current;
  16104. };
  16105. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16106. get: function () {
  16107. return this._spritesDuration;
  16108. },
  16109. enumerable: true,
  16110. configurable: true
  16111. });
  16112. Scene.prototype.getAnimationRatio = function () {
  16113. return this._animationRatio;
  16114. };
  16115. Scene.prototype.getRenderId = function () {
  16116. return this._renderId;
  16117. };
  16118. Scene.prototype.incrementRenderId = function () {
  16119. this._renderId++;
  16120. };
  16121. Scene.prototype._updatePointerPosition = function (evt) {
  16122. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16123. this._pointerX = evt.clientX - canvasRect.left;
  16124. this._pointerY = evt.clientY - canvasRect.top;
  16125. this._unTranslatedPointerX = this._pointerX;
  16126. this._unTranslatedPointerY = this._pointerY;
  16127. if (this.cameraToUseForPointers) {
  16128. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16129. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16130. }
  16131. };
  16132. Scene.prototype._createUbo = function () {
  16133. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16134. this._sceneUbo.addUniform("viewProjection", 16);
  16135. this._sceneUbo.addUniform("view", 16);
  16136. };
  16137. // Pointers handling
  16138. /**
  16139. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16140. * @param attachUp defines if you want to attach events to pointerup
  16141. * @param attachDown defines if you want to attach events to pointerdown
  16142. * @param attachMove defines if you want to attach events to pointermove
  16143. */
  16144. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16145. var _this = this;
  16146. if (attachUp === void 0) { attachUp = true; }
  16147. if (attachDown === void 0) { attachDown = true; }
  16148. if (attachMove === void 0) { attachMove = true; }
  16149. this._initActionManager = function (act, clickInfo) {
  16150. if (!_this._meshPickProceed) {
  16151. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16152. _this._currentPickResult = pickResult;
  16153. if (pickResult) {
  16154. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16155. }
  16156. _this._meshPickProceed = true;
  16157. }
  16158. return act;
  16159. };
  16160. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16161. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16162. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16163. btn !== _this._previousButtonPressed) {
  16164. _this._doubleClickOccured = false;
  16165. clickInfo.singleClick = true;
  16166. clickInfo.ignore = false;
  16167. cb(clickInfo, _this._currentPickResult);
  16168. }
  16169. };
  16170. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16171. var clickInfo = new ClickInfo();
  16172. _this._currentPickResult = null;
  16173. var act;
  16174. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16175. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16176. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16177. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16178. act = _this._initActionManager(act, clickInfo);
  16179. if (act)
  16180. checkPicking = act.hasPickTriggers;
  16181. }
  16182. if (checkPicking) {
  16183. var btn = evt.button;
  16184. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16185. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16186. if (!clickInfo.hasSwiped) {
  16187. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16188. if (!checkSingleClickImmediately) {
  16189. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16190. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16191. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16192. act = _this._initActionManager(act, clickInfo);
  16193. if (act)
  16194. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16195. }
  16196. }
  16197. if (checkSingleClickImmediately) {
  16198. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16199. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16200. btn !== _this._previousButtonPressed) {
  16201. clickInfo.singleClick = true;
  16202. cb(clickInfo, _this._currentPickResult);
  16203. }
  16204. }
  16205. else {
  16206. // wait that no double click has been raised during the double click delay
  16207. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16208. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16209. }
  16210. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16211. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16212. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16213. act = _this._initActionManager(act, clickInfo);
  16214. if (act)
  16215. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16216. }
  16217. if (checkDoubleClick) {
  16218. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16219. if (btn === _this._previousButtonPressed &&
  16220. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16221. !_this._doubleClickOccured) {
  16222. // pointer has not moved for 2 clicks, it's a double click
  16223. if (!clickInfo.hasSwiped &&
  16224. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16225. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16226. _this._previousStartingPointerTime = 0;
  16227. _this._doubleClickOccured = true;
  16228. clickInfo.doubleClick = true;
  16229. clickInfo.ignore = false;
  16230. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16231. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16232. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16233. cb(clickInfo, _this._currentPickResult);
  16234. }
  16235. else {
  16236. _this._doubleClickOccured = false;
  16237. _this._previousStartingPointerTime = _this._startingPointerTime;
  16238. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16239. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16240. _this._previousButtonPressed = btn;
  16241. _this._previousHasSwiped = clickInfo.hasSwiped;
  16242. if (Scene.ExclusiveDoubleClickMode) {
  16243. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16244. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16245. }
  16246. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16247. cb(clickInfo, _this._previousPickResult);
  16248. }
  16249. else {
  16250. cb(clickInfo, _this._currentPickResult);
  16251. }
  16252. }
  16253. }
  16254. else {
  16255. _this._doubleClickOccured = false;
  16256. _this._previousStartingPointerTime = _this._startingPointerTime;
  16257. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16258. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16259. _this._previousButtonPressed = btn;
  16260. _this._previousHasSwiped = clickInfo.hasSwiped;
  16261. }
  16262. }
  16263. }
  16264. }
  16265. clickInfo.ignore = true;
  16266. cb(clickInfo, _this._currentPickResult);
  16267. };
  16268. var spritePredicate = function (sprite) {
  16269. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16270. };
  16271. this._onPointerMove = function (evt) {
  16272. _this._updatePointerPosition(evt);
  16273. // PreObservable support
  16274. if (_this.onPrePointerObservable.hasObservers()) {
  16275. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16276. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16277. _this.onPrePointerObservable.notifyObservers(pi, type);
  16278. if (pi.skipOnPointerObservable) {
  16279. return;
  16280. }
  16281. }
  16282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16283. return;
  16284. }
  16285. var canvas = _this._engine.getRenderingCanvas();
  16286. if (!_this.pointerMovePredicate) {
  16287. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16288. }
  16289. // Meshes
  16290. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16291. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16292. _this.setPointerOverSprite(null);
  16293. _this.setPointerOverMesh(pickResult.pickedMesh);
  16294. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16295. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16296. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16297. }
  16298. else {
  16299. canvas.style.cursor = _this.hoverCursor;
  16300. }
  16301. }
  16302. else {
  16303. canvas.style.cursor = "";
  16304. }
  16305. }
  16306. else {
  16307. _this.setPointerOverMesh(null);
  16308. // Sprites
  16309. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16310. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16311. _this.setPointerOverSprite(pickResult.pickedSprite);
  16312. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16313. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16314. }
  16315. else {
  16316. canvas.style.cursor = _this.hoverCursor;
  16317. }
  16318. }
  16319. else {
  16320. _this.setPointerOverSprite(null);
  16321. // Restore pointer
  16322. canvas.style.cursor = "";
  16323. }
  16324. }
  16325. if (_this.onPointerMove) {
  16326. _this.onPointerMove(evt, pickResult);
  16327. }
  16328. if (_this.onPointerObservable.hasObservers()) {
  16329. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16330. var pi = new PointerInfo(type, evt, pickResult);
  16331. _this.onPointerObservable.notifyObservers(pi, type);
  16332. }
  16333. };
  16334. this._onPointerDown = function (evt) {
  16335. _this._isButtonPressed = true;
  16336. _this._pickedDownMesh = null;
  16337. _this._meshPickProceed = false;
  16338. _this._updatePointerPosition(evt);
  16339. // PreObservable support
  16340. if (_this.onPrePointerObservable.hasObservers()) {
  16341. var type = PointerEventTypes.POINTERDOWN;
  16342. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16343. _this.onPrePointerObservable.notifyObservers(pi, type);
  16344. if (pi.skipOnPointerObservable) {
  16345. return;
  16346. }
  16347. }
  16348. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16349. return;
  16350. }
  16351. _this._startingPointerPosition.x = _this._pointerX;
  16352. _this._startingPointerPosition.y = _this._pointerY;
  16353. _this._startingPointerTime = new Date().getTime();
  16354. if (!_this.pointerDownPredicate) {
  16355. _this.pointerDownPredicate = function (mesh) {
  16356. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16357. };
  16358. }
  16359. // Meshes
  16360. _this._pickedDownMesh = null;
  16361. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16362. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16363. _this._pickedDownMesh = pickResult.pickedMesh;
  16364. var actionManager = pickResult.pickedMesh.actionManager;
  16365. if (actionManager) {
  16366. if (actionManager.hasPickTriggers) {
  16367. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16368. switch (evt.button) {
  16369. case 0:
  16370. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16371. break;
  16372. case 1:
  16373. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16374. break;
  16375. case 2:
  16376. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16377. break;
  16378. }
  16379. }
  16380. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16381. window.setTimeout((function () {
  16382. var _this = this;
  16383. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  16384. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16385. if (this._isButtonPressed &&
  16386. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16387. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16388. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16389. this._startingPointerTime = 0;
  16390. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16391. }
  16392. }
  16393. }).bind(_this), Scene.LongPressDelay);
  16394. }
  16395. }
  16396. }
  16397. if (_this.onPointerDown) {
  16398. _this.onPointerDown(evt, pickResult);
  16399. }
  16400. if (_this.onPointerObservable.hasObservers()) {
  16401. var type = PointerEventTypes.POINTERDOWN;
  16402. var pi = new PointerInfo(type, evt, pickResult);
  16403. _this.onPointerObservable.notifyObservers(pi, type);
  16404. }
  16405. // Sprites
  16406. _this._pickedDownSprite = null;
  16407. if (_this.spriteManagers.length > 0) {
  16408. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16409. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16410. if (pickResult.pickedSprite.actionManager) {
  16411. _this._pickedDownSprite = pickResult.pickedSprite;
  16412. switch (evt.button) {
  16413. case 0:
  16414. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16415. break;
  16416. case 1:
  16417. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16418. break;
  16419. case 2:
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16421. break;
  16422. }
  16423. if (pickResult.pickedSprite.actionManager) {
  16424. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16425. }
  16426. }
  16427. }
  16428. }
  16429. };
  16430. this._onPointerUp = function (evt) {
  16431. _this._isButtonPressed = false;
  16432. _this._pickedUpMesh = null;
  16433. _this._meshPickProceed = false;
  16434. _this._updatePointerPosition(evt);
  16435. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16436. // PreObservable support
  16437. if (this.onPrePointerObservable.hasObservers()) {
  16438. if (!clickInfo.ignore) {
  16439. if (!clickInfo.hasSwiped) {
  16440. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16441. var type = PointerEventTypes.POINTERTAP;
  16442. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16443. this.onPrePointerObservable.notifyObservers(pi, type);
  16444. if (pi.skipOnPointerObservable) {
  16445. return;
  16446. }
  16447. }
  16448. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16449. var type = PointerEventTypes.POINTERDOUBLETAP;
  16450. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16451. this.onPrePointerObservable.notifyObservers(pi, type);
  16452. if (pi.skipOnPointerObservable) {
  16453. return;
  16454. }
  16455. }
  16456. }
  16457. }
  16458. else {
  16459. var type = PointerEventTypes.POINTERUP;
  16460. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16461. this.onPrePointerObservable.notifyObservers(pi, type);
  16462. if (pi.skipOnPointerObservable) {
  16463. return;
  16464. }
  16465. }
  16466. }
  16467. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16468. return;
  16469. }
  16470. if (!this.pointerUpPredicate) {
  16471. this.pointerUpPredicate = function (mesh) {
  16472. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16473. };
  16474. }
  16475. // Meshes
  16476. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16477. this._initActionManager(null, clickInfo);
  16478. }
  16479. if (!pickResult) {
  16480. pickResult = this._currentPickResult;
  16481. }
  16482. if (pickResult && pickResult && pickResult.pickedMesh) {
  16483. this._pickedUpMesh = pickResult.pickedMesh;
  16484. if (this._pickedDownMesh === this._pickedUpMesh) {
  16485. if (this.onPointerPick) {
  16486. this.onPointerPick(evt, pickResult);
  16487. }
  16488. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16489. var type = PointerEventTypes.POINTERPICK;
  16490. var pi = new PointerInfo(type, evt, pickResult);
  16491. this.onPointerObservable.notifyObservers(pi, type);
  16492. }
  16493. }
  16494. if (pickResult.pickedMesh.actionManager) {
  16495. if (clickInfo.ignore) {
  16496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16497. }
  16498. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16500. }
  16501. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16502. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16503. }
  16504. }
  16505. }
  16506. if (this._pickedDownMesh &&
  16507. this._pickedDownMesh.actionManager &&
  16508. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16509. this._pickedDownMesh !== this._pickedUpMesh) {
  16510. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16511. }
  16512. if (this.onPointerUp) {
  16513. this.onPointerUp(evt, pickResult);
  16514. }
  16515. if (this.onPointerObservable.hasObservers()) {
  16516. if (!clickInfo.ignore) {
  16517. if (!clickInfo.hasSwiped) {
  16518. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16519. var type = PointerEventTypes.POINTERTAP;
  16520. var pi = new PointerInfo(type, evt, pickResult);
  16521. this.onPointerObservable.notifyObservers(pi, type);
  16522. }
  16523. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16524. var type = PointerEventTypes.POINTERDOUBLETAP;
  16525. var pi = new PointerInfo(type, evt, pickResult);
  16526. this.onPointerObservable.notifyObservers(pi, type);
  16527. }
  16528. }
  16529. }
  16530. else {
  16531. var type = PointerEventTypes.POINTERUP;
  16532. var pi = new PointerInfo(type, evt, pickResult);
  16533. this.onPointerObservable.notifyObservers(pi, type);
  16534. }
  16535. }
  16536. // Sprites
  16537. if (this.spriteManagers.length > 0) {
  16538. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16539. if (pickResult.hit && pickResult.pickedSprite) {
  16540. if (pickResult.pickedSprite.actionManager) {
  16541. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16542. if (pickResult.pickedSprite.actionManager) {
  16543. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16544. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16545. }
  16546. }
  16547. }
  16548. }
  16549. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16550. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16551. }
  16552. }
  16553. this._previousPickResult = this._currentPickResult;
  16554. }).bind(_this));
  16555. };
  16556. this._onKeyDown = function (evt) {
  16557. if (_this.actionManager) {
  16558. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16559. }
  16560. };
  16561. this._onKeyUp = function (evt) {
  16562. if (_this.actionManager) {
  16563. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16564. }
  16565. };
  16566. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16567. var canvas = this._engine.getRenderingCanvas();
  16568. if (attachMove) {
  16569. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16570. // Wheel
  16571. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16572. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16573. }
  16574. if (attachDown) {
  16575. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16576. }
  16577. if (attachUp) {
  16578. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16579. }
  16580. canvas.tabIndex = 1;
  16581. canvas.addEventListener("keydown", this._onKeyDown, false);
  16582. canvas.addEventListener("keyup", this._onKeyUp, false);
  16583. };
  16584. Scene.prototype.detachControl = function () {
  16585. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16586. var canvas = this._engine.getRenderingCanvas();
  16587. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16588. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16589. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16590. // Wheel
  16591. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16592. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16593. canvas.removeEventListener("keydown", this._onKeyDown);
  16594. canvas.removeEventListener("keyup", this._onKeyUp);
  16595. };
  16596. // Ready
  16597. Scene.prototype.isReady = function () {
  16598. if (this._pendingData.length > 0) {
  16599. return false;
  16600. }
  16601. var index;
  16602. // Geometries
  16603. for (index = 0; index < this._geometries.length; index++) {
  16604. var geometry = this._geometries[index];
  16605. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16606. return false;
  16607. }
  16608. }
  16609. // Meshes
  16610. for (index = 0; index < this.meshes.length; index++) {
  16611. var mesh = this.meshes[index];
  16612. if (!mesh.isEnabled()) {
  16613. continue;
  16614. }
  16615. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16616. continue;
  16617. }
  16618. if (!mesh.isReady()) {
  16619. return false;
  16620. }
  16621. var mat = mesh.material;
  16622. if (mat) {
  16623. if (!mat.isReady(mesh)) {
  16624. return false;
  16625. }
  16626. }
  16627. }
  16628. return true;
  16629. };
  16630. Scene.prototype.resetCachedMaterial = function () {
  16631. this._cachedMaterial = null;
  16632. this._cachedEffect = null;
  16633. this._cachedVisibility = null;
  16634. };
  16635. Scene.prototype.registerBeforeRender = function (func) {
  16636. this.onBeforeRenderObservable.add(func);
  16637. };
  16638. Scene.prototype.unregisterBeforeRender = function (func) {
  16639. this.onBeforeRenderObservable.removeCallback(func);
  16640. };
  16641. Scene.prototype.registerAfterRender = function (func) {
  16642. this.onAfterRenderObservable.add(func);
  16643. };
  16644. Scene.prototype.unregisterAfterRender = function (func) {
  16645. this.onAfterRenderObservable.removeCallback(func);
  16646. };
  16647. Scene.prototype._addPendingData = function (data) {
  16648. this._pendingData.push(data);
  16649. };
  16650. Scene.prototype._removePendingData = function (data) {
  16651. var index = this._pendingData.indexOf(data);
  16652. if (index !== -1) {
  16653. this._pendingData.splice(index, 1);
  16654. }
  16655. };
  16656. Scene.prototype.getWaitingItemsCount = function () {
  16657. return this._pendingData.length;
  16658. };
  16659. /**
  16660. * Registers a function to be executed when the scene is ready.
  16661. * @param {Function} func - the function to be executed.
  16662. */
  16663. Scene.prototype.executeWhenReady = function (func) {
  16664. var _this = this;
  16665. this.onReadyObservable.add(func);
  16666. if (this._executeWhenReadyTimeoutId !== -1) {
  16667. return;
  16668. }
  16669. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16670. _this._checkIsReady();
  16671. }, 150);
  16672. };
  16673. Scene.prototype._checkIsReady = function () {
  16674. var _this = this;
  16675. if (this.isReady()) {
  16676. this.onReadyObservable.notifyObservers(this);
  16677. this.onReadyObservable.clear();
  16678. this._executeWhenReadyTimeoutId = -1;
  16679. return;
  16680. }
  16681. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16682. _this._checkIsReady();
  16683. }, 150);
  16684. };
  16685. // Animations
  16686. /**
  16687. * Will start the animation sequence of a given target
  16688. * @param target - the target
  16689. * @param {number} from - from which frame should animation start
  16690. * @param {number} to - till which frame should animation run.
  16691. * @param {boolean} [loop] - should the animation loop
  16692. * @param {number} [speedRatio] - the speed in which to run the animation
  16693. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16694. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16695. * @return {BABYLON.Animatable} the animatable object created for this animation
  16696. * @see BABYLON.Animatable
  16697. * @see http://doc.babylonjs.com/page.php?p=22081
  16698. */
  16699. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16700. if (speedRatio === void 0) { speedRatio = 1.0; }
  16701. if (from > to && speedRatio > 0) {
  16702. speedRatio *= -1;
  16703. }
  16704. this.stopAnimation(target);
  16705. if (!animatable) {
  16706. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16707. }
  16708. // Local animations
  16709. if (target.animations) {
  16710. animatable.appendAnimations(target, target.animations);
  16711. }
  16712. // Children animations
  16713. if (target.getAnimatables) {
  16714. var animatables = target.getAnimatables();
  16715. for (var index = 0; index < animatables.length; index++) {
  16716. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16717. }
  16718. }
  16719. animatable.reset();
  16720. return animatable;
  16721. };
  16722. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16723. if (speedRatio === undefined) {
  16724. speedRatio = 1.0;
  16725. }
  16726. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16727. return animatable;
  16728. };
  16729. Scene.prototype.getAnimatableByTarget = function (target) {
  16730. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16731. if (this._activeAnimatables[index].target === target) {
  16732. return this._activeAnimatables[index];
  16733. }
  16734. }
  16735. return null;
  16736. };
  16737. Object.defineProperty(Scene.prototype, "Animatables", {
  16738. get: function () {
  16739. return this._activeAnimatables;
  16740. },
  16741. enumerable: true,
  16742. configurable: true
  16743. });
  16744. /**
  16745. * Will stop the animation of the given target
  16746. * @param target - the target
  16747. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16748. * @see beginAnimation
  16749. */
  16750. Scene.prototype.stopAnimation = function (target, animationName) {
  16751. var animatable = this.getAnimatableByTarget(target);
  16752. if (animatable) {
  16753. animatable.stop(animationName);
  16754. }
  16755. };
  16756. Scene.prototype._animate = function () {
  16757. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16758. return;
  16759. }
  16760. // Getting time
  16761. var now = BABYLON.Tools.Now;
  16762. if (!this._animationTimeLast) {
  16763. if (this._pendingData.length > 0) {
  16764. return;
  16765. }
  16766. this._animationTimeLast = now;
  16767. }
  16768. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16769. this._animationTime += deltaTime;
  16770. this._animationTimeLast = now;
  16771. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16772. this._activeAnimatables[index]._animate(this._animationTime);
  16773. }
  16774. };
  16775. // Matrix
  16776. Scene.prototype.getViewMatrix = function () {
  16777. return this._viewMatrix;
  16778. };
  16779. Scene.prototype.getProjectionMatrix = function () {
  16780. return this._projectionMatrix;
  16781. };
  16782. Scene.prototype.getTransformMatrix = function () {
  16783. return this._transformMatrix;
  16784. };
  16785. Scene.prototype.setTransformMatrix = function (view, projection) {
  16786. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16787. return;
  16788. }
  16789. this._viewUpdateFlag = view.updateFlag;
  16790. this._projectionUpdateFlag = projection.updateFlag;
  16791. this._viewMatrix = view;
  16792. this._projectionMatrix = projection;
  16793. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16794. // Update frustum
  16795. if (!this._frustumPlanes) {
  16796. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16797. }
  16798. else {
  16799. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16800. }
  16801. if (this._sceneUbo.useUbo) {
  16802. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16803. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16804. this._sceneUbo.update();
  16805. }
  16806. };
  16807. Scene.prototype.getSceneUniformBuffer = function () {
  16808. return this._sceneUbo;
  16809. };
  16810. // Methods
  16811. Scene.prototype.getUniqueId = function () {
  16812. var result = this._uniqueIdCounter;
  16813. this._uniqueIdCounter++;
  16814. return result;
  16815. };
  16816. Scene.prototype.addMesh = function (newMesh) {
  16817. newMesh.uniqueId = this.getUniqueId();
  16818. var position = this.meshes.push(newMesh);
  16819. //notify the collision coordinator
  16820. if (this.collisionCoordinator) {
  16821. this.collisionCoordinator.onMeshAdded(newMesh);
  16822. }
  16823. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16824. };
  16825. Scene.prototype.removeMesh = function (toRemove) {
  16826. var index = this.meshes.indexOf(toRemove);
  16827. if (index !== -1) {
  16828. // Remove from the scene if mesh found
  16829. this.meshes.splice(index, 1);
  16830. }
  16831. //notify the collision coordinator
  16832. if (this.collisionCoordinator) {
  16833. this.collisionCoordinator.onMeshRemoved(toRemove);
  16834. }
  16835. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16836. return index;
  16837. };
  16838. Scene.prototype.removeSkeleton = function (toRemove) {
  16839. var index = this.skeletons.indexOf(toRemove);
  16840. if (index !== -1) {
  16841. // Remove from the scene if found
  16842. this.skeletons.splice(index, 1);
  16843. }
  16844. return index;
  16845. };
  16846. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16847. var index = this.morphTargetManagers.indexOf(toRemove);
  16848. if (index !== -1) {
  16849. // Remove from the scene if found
  16850. this.morphTargetManagers.splice(index, 1);
  16851. }
  16852. return index;
  16853. };
  16854. Scene.prototype.removeLight = function (toRemove) {
  16855. var index = this.lights.indexOf(toRemove);
  16856. if (index !== -1) {
  16857. // Remove from the scene if mesh found
  16858. this.lights.splice(index, 1);
  16859. this.sortLightsByPriority();
  16860. }
  16861. this.onLightRemovedObservable.notifyObservers(toRemove);
  16862. return index;
  16863. };
  16864. Scene.prototype.removeCamera = function (toRemove) {
  16865. var index = this.cameras.indexOf(toRemove);
  16866. if (index !== -1) {
  16867. // Remove from the scene if mesh found
  16868. this.cameras.splice(index, 1);
  16869. }
  16870. // Remove from activeCameras
  16871. var index2 = this.activeCameras.indexOf(toRemove);
  16872. if (index2 !== -1) {
  16873. // Remove from the scene if mesh found
  16874. this.activeCameras.splice(index2, 1);
  16875. }
  16876. // Reset the activeCamera
  16877. if (this.activeCamera === toRemove) {
  16878. if (this.cameras.length > 0) {
  16879. this.activeCamera = this.cameras[0];
  16880. }
  16881. else {
  16882. this.activeCamera = null;
  16883. }
  16884. }
  16885. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16886. return index;
  16887. };
  16888. Scene.prototype.addLight = function (newLight) {
  16889. newLight.uniqueId = this.getUniqueId();
  16890. this.lights.push(newLight);
  16891. this.sortLightsByPriority();
  16892. this.onNewLightAddedObservable.notifyObservers(newLight);
  16893. };
  16894. Scene.prototype.sortLightsByPriority = function () {
  16895. if (this.requireLightSorting) {
  16896. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16897. }
  16898. };
  16899. Scene.prototype.addCamera = function (newCamera) {
  16900. newCamera.uniqueId = this.getUniqueId();
  16901. var position = this.cameras.push(newCamera);
  16902. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16903. };
  16904. /**
  16905. * Switch active camera
  16906. * @param {Camera} newCamera - new active camera
  16907. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16908. */
  16909. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16910. if (attachControl === void 0) { attachControl = true; }
  16911. var canvas = this._engine.getRenderingCanvas();
  16912. this.activeCamera.detachControl(canvas);
  16913. this.activeCamera = newCamera;
  16914. if (attachControl) {
  16915. newCamera.attachControl(canvas);
  16916. }
  16917. };
  16918. /**
  16919. * sets the active camera of the scene using its ID
  16920. * @param {string} id - the camera's ID
  16921. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16922. * @see activeCamera
  16923. */
  16924. Scene.prototype.setActiveCameraByID = function (id) {
  16925. var camera = this.getCameraByID(id);
  16926. if (camera) {
  16927. this.activeCamera = camera;
  16928. return camera;
  16929. }
  16930. return null;
  16931. };
  16932. /**
  16933. * sets the active camera of the scene using its name
  16934. * @param {string} name - the camera's name
  16935. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16936. * @see activeCamera
  16937. */
  16938. Scene.prototype.setActiveCameraByName = function (name) {
  16939. var camera = this.getCameraByName(name);
  16940. if (camera) {
  16941. this.activeCamera = camera;
  16942. return camera;
  16943. }
  16944. return null;
  16945. };
  16946. /**
  16947. * get a material using its id
  16948. * @param {string} the material's ID
  16949. * @return {BABYLON.Material|null} the material or null if none found.
  16950. */
  16951. Scene.prototype.getMaterialByID = function (id) {
  16952. for (var index = 0; index < this.materials.length; index++) {
  16953. if (this.materials[index].id === id) {
  16954. return this.materials[index];
  16955. }
  16956. }
  16957. return null;
  16958. };
  16959. /**
  16960. * get a material using its name
  16961. * @param {string} the material's name
  16962. * @return {BABYLON.Material|null} the material or null if none found.
  16963. */
  16964. Scene.prototype.getMaterialByName = function (name) {
  16965. for (var index = 0; index < this.materials.length; index++) {
  16966. if (this.materials[index].name === name) {
  16967. return this.materials[index];
  16968. }
  16969. }
  16970. return null;
  16971. };
  16972. Scene.prototype.getLensFlareSystemByName = function (name) {
  16973. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16974. if (this.lensFlareSystems[index].name === name) {
  16975. return this.lensFlareSystems[index];
  16976. }
  16977. }
  16978. return null;
  16979. };
  16980. Scene.prototype.getLensFlareSystemByID = function (id) {
  16981. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16982. if (this.lensFlareSystems[index].id === id) {
  16983. return this.lensFlareSystems[index];
  16984. }
  16985. }
  16986. return null;
  16987. };
  16988. Scene.prototype.getCameraByID = function (id) {
  16989. for (var index = 0; index < this.cameras.length; index++) {
  16990. if (this.cameras[index].id === id) {
  16991. return this.cameras[index];
  16992. }
  16993. }
  16994. return null;
  16995. };
  16996. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16997. for (var index = 0; index < this.cameras.length; index++) {
  16998. if (this.cameras[index].uniqueId === uniqueId) {
  16999. return this.cameras[index];
  17000. }
  17001. }
  17002. return null;
  17003. };
  17004. /**
  17005. * get a camera using its name
  17006. * @param {string} the camera's name
  17007. * @return {BABYLON.Camera|null} the camera or null if none found.
  17008. */
  17009. Scene.prototype.getCameraByName = function (name) {
  17010. for (var index = 0; index < this.cameras.length; index++) {
  17011. if (this.cameras[index].name === name) {
  17012. return this.cameras[index];
  17013. }
  17014. }
  17015. return null;
  17016. };
  17017. /**
  17018. * get a bone using its id
  17019. * @param {string} the bone's id
  17020. * @return {BABYLON.Bone|null} the bone or null if not found
  17021. */
  17022. Scene.prototype.getBoneByID = function (id) {
  17023. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17024. var skeleton = this.skeletons[skeletonIndex];
  17025. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17026. if (skeleton.bones[boneIndex].id === id) {
  17027. return skeleton.bones[boneIndex];
  17028. }
  17029. }
  17030. }
  17031. return null;
  17032. };
  17033. /**
  17034. * get a bone using its id
  17035. * @param {string} the bone's name
  17036. * @return {BABYLON.Bone|null} the bone or null if not found
  17037. */
  17038. Scene.prototype.getBoneByName = function (name) {
  17039. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17040. var skeleton = this.skeletons[skeletonIndex];
  17041. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17042. if (skeleton.bones[boneIndex].name === name) {
  17043. return skeleton.bones[boneIndex];
  17044. }
  17045. }
  17046. }
  17047. return null;
  17048. };
  17049. /**
  17050. * get a light node using its name
  17051. * @param {string} the light's name
  17052. * @return {BABYLON.Light|null} the light or null if none found.
  17053. */
  17054. Scene.prototype.getLightByName = function (name) {
  17055. for (var index = 0; index < this.lights.length; index++) {
  17056. if (this.lights[index].name === name) {
  17057. return this.lights[index];
  17058. }
  17059. }
  17060. return null;
  17061. };
  17062. /**
  17063. * get a light node using its ID
  17064. * @param {string} the light's id
  17065. * @return {BABYLON.Light|null} the light or null if none found.
  17066. */
  17067. Scene.prototype.getLightByID = function (id) {
  17068. for (var index = 0; index < this.lights.length; index++) {
  17069. if (this.lights[index].id === id) {
  17070. return this.lights[index];
  17071. }
  17072. }
  17073. return null;
  17074. };
  17075. /**
  17076. * get a light node using its scene-generated unique ID
  17077. * @param {number} the light's unique id
  17078. * @return {BABYLON.Light|null} the light or null if none found.
  17079. */
  17080. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17081. for (var index = 0; index < this.lights.length; index++) {
  17082. if (this.lights[index].uniqueId === uniqueId) {
  17083. return this.lights[index];
  17084. }
  17085. }
  17086. return null;
  17087. };
  17088. /**
  17089. * get a particle system by id
  17090. * @param id {number} the particle system id
  17091. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17092. */
  17093. Scene.prototype.getParticleSystemByID = function (id) {
  17094. for (var index = 0; index < this.particleSystems.length; index++) {
  17095. if (this.particleSystems[index].id === id) {
  17096. return this.particleSystems[index];
  17097. }
  17098. }
  17099. return null;
  17100. };
  17101. /**
  17102. * get a geometry using its ID
  17103. * @param {string} the geometry's id
  17104. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17105. */
  17106. Scene.prototype.getGeometryByID = function (id) {
  17107. for (var index = 0; index < this._geometries.length; index++) {
  17108. if (this._geometries[index].id === id) {
  17109. return this._geometries[index];
  17110. }
  17111. }
  17112. return null;
  17113. };
  17114. /**
  17115. * add a new geometry to this scene.
  17116. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17117. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17118. * @return {boolean} was the geometry added or not
  17119. */
  17120. Scene.prototype.pushGeometry = function (geometry, force) {
  17121. if (!force && this.getGeometryByID(geometry.id)) {
  17122. return false;
  17123. }
  17124. this._geometries.push(geometry);
  17125. //notify the collision coordinator
  17126. if (this.collisionCoordinator) {
  17127. this.collisionCoordinator.onGeometryAdded(geometry);
  17128. }
  17129. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17130. return true;
  17131. };
  17132. /**
  17133. * Removes an existing geometry
  17134. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17135. * @return {boolean} was the geometry removed or not
  17136. */
  17137. Scene.prototype.removeGeometry = function (geometry) {
  17138. var index = this._geometries.indexOf(geometry);
  17139. if (index > -1) {
  17140. this._geometries.splice(index, 1);
  17141. //notify the collision coordinator
  17142. if (this.collisionCoordinator) {
  17143. this.collisionCoordinator.onGeometryDeleted(geometry);
  17144. }
  17145. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17146. return true;
  17147. }
  17148. return false;
  17149. };
  17150. Scene.prototype.getGeometries = function () {
  17151. return this._geometries;
  17152. };
  17153. /**
  17154. * Get the first added mesh found of a given ID
  17155. * @param {string} id - the id to search for
  17156. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17157. */
  17158. Scene.prototype.getMeshByID = function (id) {
  17159. for (var index = 0; index < this.meshes.length; index++) {
  17160. if (this.meshes[index].id === id) {
  17161. return this.meshes[index];
  17162. }
  17163. }
  17164. return null;
  17165. };
  17166. Scene.prototype.getMeshesByID = function (id) {
  17167. return this.meshes.filter(function (m) {
  17168. return m.id === id;
  17169. });
  17170. };
  17171. /**
  17172. * Get a mesh with its auto-generated unique id
  17173. * @param {number} uniqueId - the unique id to search for
  17174. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17175. */
  17176. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17177. for (var index = 0; index < this.meshes.length; index++) {
  17178. if (this.meshes[index].uniqueId === uniqueId) {
  17179. return this.meshes[index];
  17180. }
  17181. }
  17182. return null;
  17183. };
  17184. /**
  17185. * Get a the last added mesh found of a given ID
  17186. * @param {string} id - the id to search for
  17187. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17188. */
  17189. Scene.prototype.getLastMeshByID = function (id) {
  17190. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17191. if (this.meshes[index].id === id) {
  17192. return this.meshes[index];
  17193. }
  17194. }
  17195. return null;
  17196. };
  17197. /**
  17198. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17199. * @param {string} id - the id to search for
  17200. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17201. */
  17202. Scene.prototype.getLastEntryByID = function (id) {
  17203. var index;
  17204. for (index = this.meshes.length - 1; index >= 0; index--) {
  17205. if (this.meshes[index].id === id) {
  17206. return this.meshes[index];
  17207. }
  17208. }
  17209. for (index = this.cameras.length - 1; index >= 0; index--) {
  17210. if (this.cameras[index].id === id) {
  17211. return this.cameras[index];
  17212. }
  17213. }
  17214. for (index = this.lights.length - 1; index >= 0; index--) {
  17215. if (this.lights[index].id === id) {
  17216. return this.lights[index];
  17217. }
  17218. }
  17219. return null;
  17220. };
  17221. Scene.prototype.getNodeByID = function (id) {
  17222. var mesh = this.getMeshByID(id);
  17223. if (mesh) {
  17224. return mesh;
  17225. }
  17226. var light = this.getLightByID(id);
  17227. if (light) {
  17228. return light;
  17229. }
  17230. var camera = this.getCameraByID(id);
  17231. if (camera) {
  17232. return camera;
  17233. }
  17234. var bone = this.getBoneByID(id);
  17235. return bone;
  17236. };
  17237. Scene.prototype.getNodeByName = function (name) {
  17238. var mesh = this.getMeshByName(name);
  17239. if (mesh) {
  17240. return mesh;
  17241. }
  17242. var light = this.getLightByName(name);
  17243. if (light) {
  17244. return light;
  17245. }
  17246. var camera = this.getCameraByName(name);
  17247. if (camera) {
  17248. return camera;
  17249. }
  17250. var bone = this.getBoneByName(name);
  17251. return bone;
  17252. };
  17253. Scene.prototype.getMeshByName = function (name) {
  17254. for (var index = 0; index < this.meshes.length; index++) {
  17255. if (this.meshes[index].name === name) {
  17256. return this.meshes[index];
  17257. }
  17258. }
  17259. return null;
  17260. };
  17261. Scene.prototype.getSoundByName = function (name) {
  17262. var index;
  17263. if (BABYLON.AudioEngine) {
  17264. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17265. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17266. return this.mainSoundTrack.soundCollection[index];
  17267. }
  17268. }
  17269. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17270. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17271. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17272. return this.soundTracks[sdIndex].soundCollection[index];
  17273. }
  17274. }
  17275. }
  17276. }
  17277. return null;
  17278. };
  17279. Scene.prototype.getLastSkeletonByID = function (id) {
  17280. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17281. if (this.skeletons[index].id === id) {
  17282. return this.skeletons[index];
  17283. }
  17284. }
  17285. return null;
  17286. };
  17287. Scene.prototype.getSkeletonById = function (id) {
  17288. for (var index = 0; index < this.skeletons.length; index++) {
  17289. if (this.skeletons[index].id === id) {
  17290. return this.skeletons[index];
  17291. }
  17292. }
  17293. return null;
  17294. };
  17295. Scene.prototype.getSkeletonByName = function (name) {
  17296. for (var index = 0; index < this.skeletons.length; index++) {
  17297. if (this.skeletons[index].name === name) {
  17298. return this.skeletons[index];
  17299. }
  17300. }
  17301. return null;
  17302. };
  17303. Scene.prototype.getMorphTargetManagerById = function (id) {
  17304. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17305. if (this.morphTargetManagers[index].uniqueId === id) {
  17306. return this.morphTargetManagers[index];
  17307. }
  17308. }
  17309. return null;
  17310. };
  17311. Scene.prototype.isActiveMesh = function (mesh) {
  17312. return (this._activeMeshes.indexOf(mesh) !== -1);
  17313. };
  17314. /**
  17315. * Return a the first highlight layer of the scene with a given name.
  17316. * @param name The name of the highlight layer to look for.
  17317. * @return The highlight layer if found otherwise null.
  17318. */
  17319. Scene.prototype.getHighlightLayerByName = function (name) {
  17320. for (var index = 0; index < this.highlightLayers.length; index++) {
  17321. if (this.highlightLayers[index].name === name) {
  17322. return this.highlightLayers[index];
  17323. }
  17324. }
  17325. return null;
  17326. };
  17327. Object.defineProperty(Scene.prototype, "uid", {
  17328. /**
  17329. * Return a unique id as a string which can serve as an identifier for the scene
  17330. */
  17331. get: function () {
  17332. if (!this._uid) {
  17333. this._uid = BABYLON.Tools.RandomId();
  17334. }
  17335. return this._uid;
  17336. },
  17337. enumerable: true,
  17338. configurable: true
  17339. });
  17340. /**
  17341. * Add an externaly attached data from its key.
  17342. * This method call will fail and return false, if such key already exists.
  17343. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17344. * @param key the unique key that identifies the data
  17345. * @param data the data object to associate to the key for this Engine instance
  17346. * @return true if no such key were already present and the data was added successfully, false otherwise
  17347. */
  17348. Scene.prototype.addExternalData = function (key, data) {
  17349. if (!this._externalData) {
  17350. this._externalData = new BABYLON.StringDictionary();
  17351. }
  17352. return this._externalData.add(key, data);
  17353. };
  17354. /**
  17355. * Get an externaly attached data from its key
  17356. * @param key the unique key that identifies the data
  17357. * @return the associated data, if present (can be null), or undefined if not present
  17358. */
  17359. Scene.prototype.getExternalData = function (key) {
  17360. if (!this._externalData) {
  17361. return null;
  17362. }
  17363. return this._externalData.get(key);
  17364. };
  17365. /**
  17366. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17367. * @param key the unique key that identifies the data
  17368. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17369. * @return the associated data, can be null if the factory returned null.
  17370. */
  17371. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17372. if (!this._externalData) {
  17373. this._externalData = new BABYLON.StringDictionary();
  17374. }
  17375. return this._externalData.getOrAddWithFactory(key, factory);
  17376. };
  17377. /**
  17378. * Remove an externaly attached data from the Engine instance
  17379. * @param key the unique key that identifies the data
  17380. * @return true if the data was successfully removed, false if it doesn't exist
  17381. */
  17382. Scene.prototype.removeExternalData = function (key) {
  17383. return this._externalData.remove(key);
  17384. };
  17385. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17386. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17387. var material = subMesh.getMaterial();
  17388. if (mesh.showSubMeshesBoundingBox) {
  17389. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17390. }
  17391. if (material) {
  17392. // Render targets
  17393. if (material.getRenderTargetTextures) {
  17394. if (this._processedMaterials.indexOf(material) === -1) {
  17395. this._processedMaterials.push(material);
  17396. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17397. }
  17398. }
  17399. // Dispatch
  17400. this._activeIndices.addCount(subMesh.indexCount, false);
  17401. this._renderingManager.dispatch(subMesh);
  17402. }
  17403. }
  17404. };
  17405. Scene.prototype._isInIntermediateRendering = function () {
  17406. return this._intermediateRendering;
  17407. };
  17408. Scene.prototype._evaluateActiveMeshes = function () {
  17409. this.activeCamera._activeMeshes.reset();
  17410. this._activeMeshes.reset();
  17411. this._renderingManager.reset();
  17412. this._processedMaterials.reset();
  17413. this._activeParticleSystems.reset();
  17414. this._activeSkeletons.reset();
  17415. this._softwareSkinnedMeshes.reset();
  17416. if (this._boundingBoxRenderer) {
  17417. this._boundingBoxRenderer.reset();
  17418. }
  17419. // Meshes
  17420. var meshes;
  17421. var len;
  17422. if (this._selectionOctree) {
  17423. var selection = this._selectionOctree.select(this._frustumPlanes);
  17424. meshes = selection.data;
  17425. len = selection.length;
  17426. }
  17427. else {
  17428. len = this.meshes.length;
  17429. meshes = this.meshes;
  17430. }
  17431. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17432. var mesh = meshes[meshIndex];
  17433. if (mesh.isBlocked) {
  17434. continue;
  17435. }
  17436. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17437. if (!mesh.isReady() || !mesh.isEnabled()) {
  17438. continue;
  17439. }
  17440. mesh.computeWorldMatrix();
  17441. // Intersections
  17442. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17443. this._meshesForIntersections.pushNoDuplicate(mesh);
  17444. }
  17445. // Switch to current LOD
  17446. var meshLOD = mesh.getLOD(this.activeCamera);
  17447. if (!meshLOD) {
  17448. continue;
  17449. }
  17450. mesh._preActivate();
  17451. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17452. this._activeMeshes.push(mesh);
  17453. this.activeCamera._activeMeshes.push(mesh);
  17454. mesh._activate(this._renderId);
  17455. this._activeMesh(mesh, meshLOD);
  17456. }
  17457. }
  17458. // Particle systems
  17459. this._particlesDuration.beginMonitoring();
  17460. var beforeParticlesDate = BABYLON.Tools.Now;
  17461. if (this.particlesEnabled) {
  17462. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17463. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17464. var particleSystem = this.particleSystems[particleIndex];
  17465. if (!particleSystem.isStarted()) {
  17466. continue;
  17467. }
  17468. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17469. this._activeParticleSystems.push(particleSystem);
  17470. particleSystem.animate();
  17471. this._renderingManager.dispatchParticles(particleSystem);
  17472. }
  17473. }
  17474. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17475. }
  17476. this._particlesDuration.endMonitoring(false);
  17477. };
  17478. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17479. if (mesh.skeleton && this.skeletonsEnabled) {
  17480. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17481. mesh.skeleton.prepare();
  17482. }
  17483. if (!mesh.computeBonesUsingShaders) {
  17484. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17485. }
  17486. }
  17487. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17488. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17489. }
  17490. if (mesh && mesh.subMeshes) {
  17491. // Submeshes Octrees
  17492. var len;
  17493. var subMeshes;
  17494. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17495. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17496. len = intersections.length;
  17497. subMeshes = intersections.data;
  17498. }
  17499. else {
  17500. subMeshes = mesh.subMeshes;
  17501. len = subMeshes.length;
  17502. }
  17503. for (var subIndex = 0; subIndex < len; subIndex++) {
  17504. var subMesh = subMeshes[subIndex];
  17505. this._evaluateSubMesh(subMesh, mesh);
  17506. }
  17507. }
  17508. };
  17509. Scene.prototype.updateTransformMatrix = function (force) {
  17510. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17511. };
  17512. Scene.prototype._renderForCamera = function (camera) {
  17513. var engine = this._engine;
  17514. var startTime = BABYLON.Tools.Now;
  17515. this.activeCamera = camera;
  17516. if (!this.activeCamera)
  17517. throw new Error("Active camera not set");
  17518. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17519. // Viewport
  17520. engine.setViewport(this.activeCamera.viewport);
  17521. // Camera
  17522. this.resetCachedMaterial();
  17523. this._renderId++;
  17524. this.updateTransformMatrix();
  17525. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17526. // Meshes
  17527. this._evaluateActiveMeshesDuration.beginMonitoring();
  17528. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17529. this._evaluateActiveMeshes();
  17530. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17531. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17532. // Software skinning
  17533. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17534. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17535. mesh.applySkeleton(mesh.skeleton);
  17536. }
  17537. // Render targets
  17538. this._renderTargetsDuration.beginMonitoring();
  17539. var needsRestoreFrameBuffer = false;
  17540. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17541. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  17542. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  17543. }
  17544. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17545. this._intermediateRendering = true;
  17546. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17547. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17548. var renderTarget = this._renderTargets.data[renderIndex];
  17549. if (renderTarget._shouldRender()) {
  17550. this._renderId++;
  17551. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17552. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17553. }
  17554. }
  17555. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17556. this._intermediateRendering = false;
  17557. this._renderId++;
  17558. needsRestoreFrameBuffer = true; // Restore back buffer
  17559. }
  17560. // Render HighlightLayer Texture
  17561. var stencilState = this._engine.getStencilBuffer();
  17562. var renderhighlights = false;
  17563. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17564. this._intermediateRendering = true;
  17565. for (var i = 0; i < this.highlightLayers.length; i++) {
  17566. var highlightLayer = this.highlightLayers[i];
  17567. if (highlightLayer.shouldRender() &&
  17568. (!highlightLayer.camera ||
  17569. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17570. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17571. renderhighlights = true;
  17572. var renderTarget = highlightLayer._mainTexture;
  17573. if (renderTarget._shouldRender()) {
  17574. this._renderId++;
  17575. renderTarget.render(false, false);
  17576. needsRestoreFrameBuffer = true;
  17577. }
  17578. }
  17579. }
  17580. this._intermediateRendering = false;
  17581. this._renderId++;
  17582. }
  17583. if (needsRestoreFrameBuffer) {
  17584. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17585. }
  17586. this._renderTargetsDuration.endMonitoring(false);
  17587. // Prepare Frame
  17588. this.postProcessManager._prepareFrame();
  17589. this._renderDuration.beginMonitoring();
  17590. // Backgrounds
  17591. var layerIndex;
  17592. var layer;
  17593. if (this.layers.length) {
  17594. engine.setDepthBuffer(false);
  17595. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17596. layer = this.layers[layerIndex];
  17597. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17598. layer.render();
  17599. }
  17600. }
  17601. engine.setDepthBuffer(true);
  17602. }
  17603. // Render
  17604. BABYLON.Tools.StartPerformanceCounter("Main render");
  17605. // Activate HighlightLayer stencil
  17606. if (renderhighlights) {
  17607. this._engine.setStencilBuffer(true);
  17608. }
  17609. this._renderingManager.render(null, null, true, true);
  17610. // Restore HighlightLayer stencil
  17611. if (renderhighlights) {
  17612. this._engine.setStencilBuffer(stencilState);
  17613. }
  17614. BABYLON.Tools.EndPerformanceCounter("Main render");
  17615. // Bounding boxes
  17616. if (this._boundingBoxRenderer) {
  17617. this._boundingBoxRenderer.render();
  17618. }
  17619. // Lens flares
  17620. if (this.lensFlaresEnabled) {
  17621. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17622. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17623. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17624. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17625. lensFlareSystem.render();
  17626. }
  17627. }
  17628. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17629. }
  17630. // Foregrounds
  17631. if (this.layers.length) {
  17632. engine.setDepthBuffer(false);
  17633. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17634. layer = this.layers[layerIndex];
  17635. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17636. layer.render();
  17637. }
  17638. }
  17639. engine.setDepthBuffer(true);
  17640. }
  17641. // Highlight Layer
  17642. if (renderhighlights) {
  17643. engine.setDepthBuffer(false);
  17644. for (var i = 0; i < this.highlightLayers.length; i++) {
  17645. if (this.highlightLayers[i].shouldRender()) {
  17646. this.highlightLayers[i].render();
  17647. }
  17648. }
  17649. engine.setDepthBuffer(true);
  17650. }
  17651. this._renderDuration.endMonitoring(false);
  17652. // Finalize frame
  17653. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17654. // Update camera
  17655. this.activeCamera._updateFromScene();
  17656. // Reset some special arrays
  17657. this._renderTargets.reset();
  17658. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17659. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17660. };
  17661. Scene.prototype._processSubCameras = function (camera) {
  17662. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17663. this._renderForCamera(camera);
  17664. return;
  17665. }
  17666. // rig cameras
  17667. for (var index = 0; index < camera._rigCameras.length; index++) {
  17668. this._renderForCamera(camera._rigCameras[index]);
  17669. }
  17670. this.activeCamera = camera;
  17671. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17672. // Update camera
  17673. this.activeCamera._updateFromScene();
  17674. };
  17675. Scene.prototype._checkIntersections = function () {
  17676. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17677. var sourceMesh = this._meshesForIntersections.data[index];
  17678. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17679. var action = sourceMesh.actionManager.actions[actionIndex];
  17680. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17681. var parameters = action.getTriggerParameter();
  17682. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17683. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17684. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17685. if (areIntersecting && currentIntersectionInProgress === -1) {
  17686. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17687. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17688. sourceMesh._intersectionsInProgress.push(otherMesh);
  17689. }
  17690. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17691. sourceMesh._intersectionsInProgress.push(otherMesh);
  17692. }
  17693. }
  17694. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17695. //They intersected, and now they don't.
  17696. //is this trigger an exit trigger? execute an event.
  17697. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17698. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17699. }
  17700. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17701. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17702. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17703. }
  17704. }
  17705. }
  17706. }
  17707. }
  17708. };
  17709. Scene.prototype.render = function () {
  17710. if (this.isDisposed) {
  17711. return;
  17712. }
  17713. this._lastFrameDuration.beginMonitoring();
  17714. this._particlesDuration.fetchNewFrame();
  17715. this._spritesDuration.fetchNewFrame();
  17716. this._activeParticles.fetchNewFrame();
  17717. this._renderDuration.fetchNewFrame();
  17718. this._renderTargetsDuration.fetchNewFrame();
  17719. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17720. this._totalVertices.fetchNewFrame();
  17721. this._activeIndices.fetchNewFrame();
  17722. this._activeBones.fetchNewFrame();
  17723. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17724. this._meshesForIntersections.reset();
  17725. this.resetCachedMaterial();
  17726. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17727. // Actions
  17728. if (this.actionManager) {
  17729. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17730. }
  17731. //Simplification Queue
  17732. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17733. this.simplificationQueue.executeNext();
  17734. }
  17735. // Animations
  17736. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17737. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17738. this._animate();
  17739. // Physics
  17740. if (this._physicsEngine) {
  17741. BABYLON.Tools.StartPerformanceCounter("Physics");
  17742. this._physicsEngine._step(deltaTime / 1000.0);
  17743. BABYLON.Tools.EndPerformanceCounter("Physics");
  17744. }
  17745. // Before render
  17746. this.onBeforeRenderObservable.notifyObservers(this);
  17747. // Customs render targets
  17748. this._renderTargetsDuration.beginMonitoring();
  17749. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17750. var engine = this.getEngine();
  17751. var currentActiveCamera = this.activeCamera;
  17752. if (this.renderTargetsEnabled) {
  17753. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17754. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17755. var renderTarget = this.customRenderTargets[customIndex];
  17756. if (renderTarget._shouldRender()) {
  17757. this._renderId++;
  17758. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17759. if (!this.activeCamera)
  17760. throw new Error("Active camera not set");
  17761. // Viewport
  17762. engine.setViewport(this.activeCamera.viewport);
  17763. // Camera
  17764. this.updateTransformMatrix();
  17765. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17766. }
  17767. }
  17768. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17769. this._renderId++;
  17770. }
  17771. // Restore back buffer
  17772. if (this.customRenderTargets.length > 0) {
  17773. engine.restoreDefaultFramebuffer();
  17774. }
  17775. this._renderTargetsDuration.endMonitoring();
  17776. this.activeCamera = currentActiveCamera;
  17777. // Procedural textures
  17778. if (this.proceduralTexturesEnabled) {
  17779. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17780. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17781. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17782. if (proceduralTexture._shouldRender()) {
  17783. proceduralTexture.render();
  17784. }
  17785. }
  17786. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17787. }
  17788. // Clear
  17789. if (this.autoClearDepthAndStencil || this.autoClear) {
  17790. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17791. }
  17792. // Shadows
  17793. if (this.shadowsEnabled) {
  17794. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17795. var light = this.lights[lightIndex];
  17796. var shadowGenerator = light.getShadowGenerator();
  17797. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17798. var shadowMap = shadowGenerator.getShadowMap();
  17799. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17800. this._renderTargets.push(shadowMap);
  17801. }
  17802. }
  17803. }
  17804. }
  17805. // Depth renderer
  17806. if (this._depthRenderer) {
  17807. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17808. }
  17809. // Geometry renderer
  17810. if (this._geometryBufferRenderer) {
  17811. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17812. }
  17813. // RenderPipeline
  17814. if (this._postProcessRenderPipelineManager) {
  17815. this._postProcessRenderPipelineManager.update();
  17816. }
  17817. // Multi-cameras?
  17818. if (this.activeCameras.length > 0) {
  17819. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17820. if (cameraIndex > 0) {
  17821. this._engine.clear(null, false, true, true);
  17822. }
  17823. this._processSubCameras(this.activeCameras[cameraIndex]);
  17824. }
  17825. }
  17826. else {
  17827. if (!this.activeCamera) {
  17828. throw new Error("No camera defined");
  17829. }
  17830. this._processSubCameras(this.activeCamera);
  17831. }
  17832. // Intersection checks
  17833. this._checkIntersections();
  17834. // Update the audio listener attached to the camera
  17835. if (BABYLON.AudioEngine) {
  17836. this._updateAudioParameters();
  17837. }
  17838. // After render
  17839. if (this.afterRender) {
  17840. this.afterRender();
  17841. }
  17842. this.onAfterRenderObservable.notifyObservers(this);
  17843. // Cleaning
  17844. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17845. this._toBeDisposed.data[index].dispose();
  17846. this._toBeDisposed[index] = null;
  17847. }
  17848. this._toBeDisposed.reset();
  17849. if (this.dumpNextRenderTargets) {
  17850. this.dumpNextRenderTargets = false;
  17851. }
  17852. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17853. this._lastFrameDuration.endMonitoring();
  17854. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17855. this._totalLightsCounter.addCount(this.lights.length, true);
  17856. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17857. this._totalTexturesCounter.addCount(this.textures.length, true);
  17858. this._activeBones.addCount(0, true);
  17859. this._activeIndices.addCount(0, true);
  17860. this._activeParticles.addCount(0, true);
  17861. };
  17862. Scene.prototype._updateAudioParameters = function () {
  17863. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17864. return;
  17865. }
  17866. var listeningCamera;
  17867. var audioEngine = BABYLON.Engine.audioEngine;
  17868. if (this.activeCameras.length > 0) {
  17869. listeningCamera = this.activeCameras[0];
  17870. }
  17871. else {
  17872. listeningCamera = this.activeCamera;
  17873. }
  17874. if (listeningCamera && audioEngine.canUseWebAudio) {
  17875. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17876. // for VR cameras
  17877. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  17878. listeningCamera = listeningCamera.rigCameras[0];
  17879. }
  17880. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17881. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17882. cameraDirection.normalize();
  17883. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17884. var i;
  17885. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17886. var sound = this.mainSoundTrack.soundCollection[i];
  17887. if (sound.useCustomAttenuation) {
  17888. sound.updateDistanceFromListener();
  17889. }
  17890. }
  17891. for (i = 0; i < this.soundTracks.length; i++) {
  17892. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17893. sound = this.soundTracks[i].soundCollection[j];
  17894. if (sound.useCustomAttenuation) {
  17895. sound.updateDistanceFromListener();
  17896. }
  17897. }
  17898. }
  17899. }
  17900. };
  17901. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17902. // Audio
  17903. get: function () {
  17904. return this._audioEnabled;
  17905. },
  17906. set: function (value) {
  17907. this._audioEnabled = value;
  17908. if (BABYLON.AudioEngine) {
  17909. if (this._audioEnabled) {
  17910. this._enableAudio();
  17911. }
  17912. else {
  17913. this._disableAudio();
  17914. }
  17915. }
  17916. },
  17917. enumerable: true,
  17918. configurable: true
  17919. });
  17920. Scene.prototype._disableAudio = function () {
  17921. var i;
  17922. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17923. this.mainSoundTrack.soundCollection[i].pause();
  17924. }
  17925. for (i = 0; i < this.soundTracks.length; i++) {
  17926. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17927. this.soundTracks[i].soundCollection[j].pause();
  17928. }
  17929. }
  17930. };
  17931. Scene.prototype._enableAudio = function () {
  17932. var i;
  17933. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17934. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17935. this.mainSoundTrack.soundCollection[i].play();
  17936. }
  17937. }
  17938. for (i = 0; i < this.soundTracks.length; i++) {
  17939. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17940. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17941. this.soundTracks[i].soundCollection[j].play();
  17942. }
  17943. }
  17944. }
  17945. };
  17946. Object.defineProperty(Scene.prototype, "headphone", {
  17947. get: function () {
  17948. return this._headphone;
  17949. },
  17950. set: function (value) {
  17951. this._headphone = value;
  17952. if (BABYLON.AudioEngine) {
  17953. if (this._headphone) {
  17954. this._switchAudioModeForHeadphones();
  17955. }
  17956. else {
  17957. this._switchAudioModeForNormalSpeakers();
  17958. }
  17959. }
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Scene.prototype._switchAudioModeForHeadphones = function () {
  17965. this.mainSoundTrack.switchPanningModelToHRTF();
  17966. for (var i = 0; i < this.soundTracks.length; i++) {
  17967. this.soundTracks[i].switchPanningModelToHRTF();
  17968. }
  17969. };
  17970. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17971. this.mainSoundTrack.switchPanningModelToEqualPower();
  17972. for (var i = 0; i < this.soundTracks.length; i++) {
  17973. this.soundTracks[i].switchPanningModelToEqualPower();
  17974. }
  17975. };
  17976. Scene.prototype.enableDepthRenderer = function () {
  17977. if (this._depthRenderer) {
  17978. return this._depthRenderer;
  17979. }
  17980. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17981. return this._depthRenderer;
  17982. };
  17983. Scene.prototype.disableDepthRenderer = function () {
  17984. if (!this._depthRenderer) {
  17985. return;
  17986. }
  17987. this._depthRenderer.dispose();
  17988. this._depthRenderer = null;
  17989. };
  17990. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17991. if (ratio === void 0) { ratio = 1; }
  17992. if (this._geometryBufferRenderer) {
  17993. return this._geometryBufferRenderer;
  17994. }
  17995. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17996. if (!this._geometryBufferRenderer.isSupported) {
  17997. this._geometryBufferRenderer = null;
  17998. }
  17999. return this._geometryBufferRenderer;
  18000. };
  18001. Scene.prototype.disableGeometryBufferRenderer = function () {
  18002. if (!this._geometryBufferRenderer) {
  18003. return;
  18004. }
  18005. this._geometryBufferRenderer.dispose();
  18006. this._geometryBufferRenderer = null;
  18007. };
  18008. Scene.prototype.freezeMaterials = function () {
  18009. for (var i = 0; i < this.materials.length; i++) {
  18010. this.materials[i].freeze();
  18011. }
  18012. };
  18013. Scene.prototype.unfreezeMaterials = function () {
  18014. for (var i = 0; i < this.materials.length; i++) {
  18015. this.materials[i].unfreeze();
  18016. }
  18017. };
  18018. Scene.prototype.dispose = function () {
  18019. this.beforeRender = null;
  18020. this.afterRender = null;
  18021. this.skeletons = [];
  18022. this.morphTargetManagers = [];
  18023. this.importedMeshesFiles = new Array();
  18024. if (this._depthRenderer) {
  18025. this._depthRenderer.dispose();
  18026. }
  18027. // Smart arrays
  18028. if (this.activeCamera) {
  18029. this.activeCamera._activeMeshes.dispose();
  18030. this.activeCamera = null;
  18031. }
  18032. this._activeMeshes.dispose();
  18033. this._renderingManager.dispose();
  18034. this._processedMaterials.dispose();
  18035. this._activeParticleSystems.dispose();
  18036. this._activeSkeletons.dispose();
  18037. this._softwareSkinnedMeshes.dispose();
  18038. if (this._boundingBoxRenderer) {
  18039. this._boundingBoxRenderer.dispose();
  18040. }
  18041. this._meshesForIntersections.dispose();
  18042. this._toBeDisposed.dispose();
  18043. // Debug layer
  18044. if (this._debugLayer) {
  18045. this._debugLayer.hide();
  18046. }
  18047. // Events
  18048. this.onDisposeObservable.notifyObservers(this);
  18049. this.onDisposeObservable.clear();
  18050. this.onBeforeRenderObservable.clear();
  18051. this.onAfterRenderObservable.clear();
  18052. this.detachControl();
  18053. // Release sounds & sounds tracks
  18054. if (BABYLON.AudioEngine) {
  18055. this.disposeSounds();
  18056. }
  18057. // Detach cameras
  18058. var canvas = this._engine.getRenderingCanvas();
  18059. var index;
  18060. for (index = 0; index < this.cameras.length; index++) {
  18061. this.cameras[index].detachControl(canvas);
  18062. }
  18063. // Release lights
  18064. while (this.lights.length) {
  18065. this.lights[0].dispose();
  18066. }
  18067. // Release meshes
  18068. while (this.meshes.length) {
  18069. this.meshes[0].dispose(true);
  18070. }
  18071. // Release cameras
  18072. while (this.cameras.length) {
  18073. this.cameras[0].dispose();
  18074. }
  18075. // Release materials
  18076. while (this.materials.length) {
  18077. this.materials[0].dispose();
  18078. }
  18079. // Release particles
  18080. while (this.particleSystems.length) {
  18081. this.particleSystems[0].dispose();
  18082. }
  18083. // Release sprites
  18084. while (this.spriteManagers.length) {
  18085. this.spriteManagers[0].dispose();
  18086. }
  18087. // Release layers
  18088. while (this.layers.length) {
  18089. this.layers[0].dispose();
  18090. }
  18091. while (this.highlightLayers.length) {
  18092. this.highlightLayers[0].dispose();
  18093. }
  18094. // Release textures
  18095. while (this.textures.length) {
  18096. this.textures[0].dispose();
  18097. }
  18098. // Release UBO
  18099. this._sceneUbo.dispose();
  18100. // Post-processes
  18101. this.postProcessManager.dispose();
  18102. // Physics
  18103. if (this._physicsEngine) {
  18104. this.disablePhysicsEngine();
  18105. }
  18106. // Remove from engine
  18107. index = this._engine.scenes.indexOf(this);
  18108. if (index > -1) {
  18109. this._engine.scenes.splice(index, 1);
  18110. }
  18111. this._engine.wipeCaches();
  18112. this._engine = null;
  18113. };
  18114. Object.defineProperty(Scene.prototype, "isDisposed", {
  18115. get: function () {
  18116. return !this._engine;
  18117. },
  18118. enumerable: true,
  18119. configurable: true
  18120. });
  18121. // Release sounds & sounds tracks
  18122. Scene.prototype.disposeSounds = function () {
  18123. this.mainSoundTrack.dispose();
  18124. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18125. this.soundTracks[scIndex].dispose();
  18126. }
  18127. };
  18128. // Octrees
  18129. Scene.prototype.getWorldExtends = function () {
  18130. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18131. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18132. for (var index = 0; index < this.meshes.length; index++) {
  18133. var mesh = this.meshes[index];
  18134. mesh.computeWorldMatrix(true);
  18135. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18136. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18137. BABYLON.Tools.CheckExtends(minBox, min, max);
  18138. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18139. }
  18140. return {
  18141. min: min,
  18142. max: max
  18143. };
  18144. };
  18145. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18146. if (maxCapacity === void 0) { maxCapacity = 64; }
  18147. if (maxDepth === void 0) { maxDepth = 2; }
  18148. if (!this._selectionOctree) {
  18149. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18150. }
  18151. var worldExtends = this.getWorldExtends();
  18152. // Update octree
  18153. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18154. return this._selectionOctree;
  18155. };
  18156. // Picking
  18157. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18158. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18159. var engine = this._engine;
  18160. if (!camera) {
  18161. if (!this.activeCamera)
  18162. throw new Error("Active camera not set");
  18163. camera = this.activeCamera;
  18164. }
  18165. var cameraViewport = camera.viewport;
  18166. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18167. // Moving coordinates to local viewport world
  18168. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18169. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18170. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18171. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18172. };
  18173. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18174. if (!BABYLON.PickingInfo) {
  18175. return null;
  18176. }
  18177. var engine = this._engine;
  18178. if (!camera) {
  18179. if (!this.activeCamera)
  18180. throw new Error("Active camera not set");
  18181. camera = this.activeCamera;
  18182. }
  18183. var cameraViewport = camera.viewport;
  18184. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18185. var identity = BABYLON.Matrix.Identity();
  18186. // Moving coordinates to local viewport world
  18187. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18188. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18189. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18190. };
  18191. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18192. if (!BABYLON.PickingInfo) {
  18193. return null;
  18194. }
  18195. var pickingInfo = null;
  18196. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18197. var mesh = this.meshes[meshIndex];
  18198. if (predicate) {
  18199. if (!predicate(mesh)) {
  18200. continue;
  18201. }
  18202. }
  18203. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18204. continue;
  18205. }
  18206. var world = mesh.getWorldMatrix();
  18207. var ray = rayFunction(world);
  18208. var result = mesh.intersects(ray, fastCheck);
  18209. if (!result || !result.hit)
  18210. continue;
  18211. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18212. continue;
  18213. pickingInfo = result;
  18214. if (fastCheck) {
  18215. break;
  18216. }
  18217. }
  18218. return pickingInfo || new BABYLON.PickingInfo();
  18219. };
  18220. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18221. if (!BABYLON.PickingInfo) {
  18222. return null;
  18223. }
  18224. var pickingInfos = new Array();
  18225. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18226. var mesh = this.meshes[meshIndex];
  18227. if (predicate) {
  18228. if (!predicate(mesh)) {
  18229. continue;
  18230. }
  18231. }
  18232. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18233. continue;
  18234. }
  18235. var world = mesh.getWorldMatrix();
  18236. var ray = rayFunction(world);
  18237. var result = mesh.intersects(ray, false);
  18238. if (!result || !result.hit)
  18239. continue;
  18240. pickingInfos.push(result);
  18241. }
  18242. return pickingInfos;
  18243. };
  18244. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18245. if (!BABYLON.PickingInfo) {
  18246. return null;
  18247. }
  18248. var pickingInfo = null;
  18249. camera = camera || this.activeCamera;
  18250. if (this.spriteManagers.length > 0) {
  18251. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18252. var spriteManager = this.spriteManagers[spriteIndex];
  18253. if (!spriteManager.isPickable) {
  18254. continue;
  18255. }
  18256. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18257. if (!result || !result.hit)
  18258. continue;
  18259. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18260. continue;
  18261. pickingInfo = result;
  18262. if (fastCheck) {
  18263. break;
  18264. }
  18265. }
  18266. }
  18267. return pickingInfo || new BABYLON.PickingInfo();
  18268. };
  18269. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18270. /// <param name="x">X position on screen</param>
  18271. /// <param name="y">Y position on screen</param>
  18272. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18273. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18274. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18275. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18276. var _this = this;
  18277. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18278. };
  18279. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18280. /// <param name="x">X position on screen</param>
  18281. /// <param name="y">Y position on screen</param>
  18282. /// <param name="predicate">Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true</param>
  18283. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18284. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18285. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18286. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18287. };
  18288. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18289. var _this = this;
  18290. return this._internalPick(function (world) {
  18291. if (!_this._pickWithRayInverseMatrix) {
  18292. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18293. }
  18294. world.invertToRef(_this._pickWithRayInverseMatrix);
  18295. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18296. }, predicate, fastCheck);
  18297. };
  18298. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18299. /// <param name="x">X position on screen</param>
  18300. /// <param name="y">Y position on screen</param>
  18301. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18302. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  18303. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18304. var _this = this;
  18305. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18306. };
  18307. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18308. /// <param name="ray">Ray to use</param>
  18309. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  18310. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18311. var _this = this;
  18312. return this._internalMultiPick(function (world) {
  18313. if (!_this._pickWithRayInverseMatrix) {
  18314. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18315. }
  18316. world.invertToRef(_this._pickWithRayInverseMatrix);
  18317. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18318. }, predicate);
  18319. };
  18320. Scene.prototype.setPointerOverMesh = function (mesh) {
  18321. if (this._pointerOverMesh === mesh) {
  18322. return;
  18323. }
  18324. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18325. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18326. }
  18327. this._pointerOverMesh = mesh;
  18328. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18329. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18330. }
  18331. };
  18332. Scene.prototype.getPointerOverMesh = function () {
  18333. return this._pointerOverMesh;
  18334. };
  18335. Scene.prototype.setPointerOverSprite = function (sprite) {
  18336. if (this._pointerOverSprite === sprite) {
  18337. return;
  18338. }
  18339. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18340. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18341. }
  18342. this._pointerOverSprite = sprite;
  18343. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18344. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18345. }
  18346. };
  18347. Scene.prototype.getPointerOverSprite = function () {
  18348. return this._pointerOverSprite;
  18349. };
  18350. // Physics
  18351. Scene.prototype.getPhysicsEngine = function () {
  18352. return this._physicsEngine;
  18353. };
  18354. /**
  18355. * Enables physics to the current scene
  18356. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18357. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18358. * @return {boolean} was the physics engine initialized
  18359. */
  18360. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18361. if (this._physicsEngine) {
  18362. return true;
  18363. }
  18364. try {
  18365. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18366. return true;
  18367. }
  18368. catch (e) {
  18369. BABYLON.Tools.Error(e.message);
  18370. return false;
  18371. }
  18372. };
  18373. Scene.prototype.disablePhysicsEngine = function () {
  18374. if (!this._physicsEngine) {
  18375. return;
  18376. }
  18377. this._physicsEngine.dispose();
  18378. this._physicsEngine = undefined;
  18379. };
  18380. Scene.prototype.isPhysicsEnabled = function () {
  18381. return this._physicsEngine !== undefined;
  18382. };
  18383. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18384. var mesh = compound.parts[0].mesh;
  18385. mesh.physicsImpostor.dispose();
  18386. mesh.physicsImpostor = null;
  18387. };
  18388. // Misc.
  18389. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18390. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18391. // Light
  18392. if (this.lights.length === 0) {
  18393. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18394. }
  18395. // Camera
  18396. if (!this.activeCamera) {
  18397. var worldExtends = this.getWorldExtends();
  18398. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18399. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18400. var camera;
  18401. var radius = worldSize.length() * 1.5;
  18402. if (createArcRotateCamera) {
  18403. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18404. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18405. arcRotateCamera.wheelPrecision = 100 / radius;
  18406. camera = arcRotateCamera;
  18407. }
  18408. else {
  18409. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18410. freeCamera.setTarget(worldCenter);
  18411. camera = freeCamera;
  18412. }
  18413. camera.minZ = radius * 0.01;
  18414. camera.maxZ = radius * 100;
  18415. camera.speed = radius * 0.2;
  18416. this.activeCamera = camera;
  18417. }
  18418. };
  18419. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18420. if (pbr === void 0) { pbr = false; }
  18421. if (environmentTexture) {
  18422. this.environmentTexture = environmentTexture;
  18423. }
  18424. if (!this.environmentTexture) {
  18425. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18426. return;
  18427. }
  18428. if (!this.environmentTexture) {
  18429. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18430. return;
  18431. }
  18432. // Skybox
  18433. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18434. if (pbr) {
  18435. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18436. hdrSkyboxMaterial.backFaceCulling = false;
  18437. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18438. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18439. hdrSkyboxMaterial.microSurface = 1.0;
  18440. hdrSkyboxMaterial.disableLighting = true;
  18441. hdrSkybox.infiniteDistance = true;
  18442. hdrSkybox.material = hdrSkyboxMaterial;
  18443. }
  18444. else {
  18445. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18446. skyboxMaterial.backFaceCulling = false;
  18447. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18448. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18449. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18450. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18451. skyboxMaterial.disableLighting = true;
  18452. hdrSkybox.infiniteDistance = true;
  18453. hdrSkybox.material = skyboxMaterial;
  18454. }
  18455. return hdrSkybox;
  18456. };
  18457. // Tags
  18458. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18459. if (tagsQuery === undefined) {
  18460. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18461. return list;
  18462. }
  18463. var listByTags = [];
  18464. forEach = forEach || (function (item) { return; });
  18465. for (var i in list) {
  18466. var item = list[i];
  18467. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18468. listByTags.push(item);
  18469. forEach(item);
  18470. }
  18471. }
  18472. return listByTags;
  18473. };
  18474. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18475. return this._getByTags(this.meshes, tagsQuery, forEach);
  18476. };
  18477. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18478. return this._getByTags(this.cameras, tagsQuery, forEach);
  18479. };
  18480. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18481. return this._getByTags(this.lights, tagsQuery, forEach);
  18482. };
  18483. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18484. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18485. };
  18486. /**
  18487. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18488. * This allowed control for front to back rendering or reversly depending of the special needs.
  18489. *
  18490. * @param renderingGroupId The rendering group id corresponding to its index
  18491. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18492. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18493. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18494. */
  18495. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18496. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18497. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18498. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18499. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18500. };
  18501. /**
  18502. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18503. *
  18504. * @param renderingGroupId The rendering group id corresponding to its index
  18505. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18506. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18507. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18508. */
  18509. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18510. if (depth === void 0) { depth = true; }
  18511. if (stencil === void 0) { stencil = true; }
  18512. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18513. };
  18514. /**
  18515. * Will flag all materials as dirty to trigger new shader compilation
  18516. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18517. */
  18518. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18519. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18520. var material = _a[_i];
  18521. if (predicate && !predicate(material)) {
  18522. continue;
  18523. }
  18524. material.markAsDirty(flag);
  18525. }
  18526. };
  18527. return Scene;
  18528. }());
  18529. // Statics
  18530. Scene._FOGMODE_NONE = 0;
  18531. Scene._FOGMODE_EXP = 1;
  18532. Scene._FOGMODE_EXP2 = 2;
  18533. Scene._FOGMODE_LINEAR = 3;
  18534. Scene.MinDeltaTime = 1.0;
  18535. Scene.MaxDeltaTime = 1000.0;
  18536. Scene.DragMovementThreshold = 10; // in pixels
  18537. Scene.LongPressDelay = 500; // in milliseconds
  18538. Scene.DoubleClickDelay = 300; // in milliseconds
  18539. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18540. BABYLON.Scene = Scene;
  18541. })(BABYLON || (BABYLON = {}));
  18542. //# sourceMappingURL=babylon.scene.js.map
  18543. var BABYLON;
  18544. (function (BABYLON) {
  18545. var Buffer = (function () {
  18546. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18547. if (engine instanceof BABYLON.Mesh) {
  18548. this._engine = engine.getScene().getEngine();
  18549. }
  18550. else {
  18551. this._engine = engine;
  18552. }
  18553. this._updatable = updatable;
  18554. this._data = data;
  18555. this._strideSize = stride;
  18556. if (!postponeInternalCreation) {
  18557. this.create();
  18558. }
  18559. this._instanced = instanced;
  18560. this._instanceDivisor = instanced ? 1 : 0;
  18561. }
  18562. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18563. // a lot of these parameters are ignored as they are overriden by the buffer
  18564. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18565. };
  18566. // Properties
  18567. Buffer.prototype.isUpdatable = function () {
  18568. return this._updatable;
  18569. };
  18570. Buffer.prototype.getData = function () {
  18571. return this._data;
  18572. };
  18573. Buffer.prototype.getBuffer = function () {
  18574. return this._buffer;
  18575. };
  18576. Buffer.prototype.getStrideSize = function () {
  18577. return this._strideSize;
  18578. };
  18579. Buffer.prototype.getIsInstanced = function () {
  18580. return this._instanced;
  18581. };
  18582. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  18583. get: function () {
  18584. return this._instanceDivisor;
  18585. },
  18586. set: function (value) {
  18587. this._instanceDivisor = value;
  18588. if (value == 0) {
  18589. this._instanced = false;
  18590. }
  18591. else {
  18592. this._instanced = true;
  18593. }
  18594. },
  18595. enumerable: true,
  18596. configurable: true
  18597. });
  18598. // Methods
  18599. Buffer.prototype.create = function (data) {
  18600. if (!data && this._buffer) {
  18601. return; // nothing to do
  18602. }
  18603. data = data || this._data;
  18604. if (!this._buffer) {
  18605. if (this._updatable) {
  18606. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18607. this._data = data;
  18608. }
  18609. else {
  18610. this._buffer = this._engine.createVertexBuffer(data);
  18611. }
  18612. }
  18613. else if (this._updatable) {
  18614. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18615. this._data = data;
  18616. }
  18617. };
  18618. Buffer.prototype.update = function (data) {
  18619. this.create(data);
  18620. };
  18621. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18622. if (!this._buffer) {
  18623. return;
  18624. }
  18625. if (this._updatable) {
  18626. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18627. this._data = null;
  18628. }
  18629. };
  18630. Buffer.prototype.dispose = function () {
  18631. if (!this._buffer) {
  18632. return;
  18633. }
  18634. if (this._engine._releaseBuffer(this._buffer)) {
  18635. this._buffer = null;
  18636. }
  18637. };
  18638. return Buffer;
  18639. }());
  18640. BABYLON.Buffer = Buffer;
  18641. })(BABYLON || (BABYLON = {}));
  18642. //# sourceMappingURL=babylon.buffer.js.map
  18643. var BABYLON;
  18644. (function (BABYLON) {
  18645. var VertexBuffer = (function () {
  18646. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18647. if (!stride) {
  18648. // Deduce stride from kind
  18649. switch (kind) {
  18650. case VertexBuffer.PositionKind:
  18651. stride = 3;
  18652. break;
  18653. case VertexBuffer.NormalKind:
  18654. stride = 3;
  18655. break;
  18656. case VertexBuffer.UVKind:
  18657. case VertexBuffer.UV2Kind:
  18658. case VertexBuffer.UV3Kind:
  18659. case VertexBuffer.UV4Kind:
  18660. case VertexBuffer.UV5Kind:
  18661. case VertexBuffer.UV6Kind:
  18662. stride = 2;
  18663. break;
  18664. case VertexBuffer.TangentKind:
  18665. case VertexBuffer.ColorKind:
  18666. stride = 4;
  18667. break;
  18668. case VertexBuffer.MatricesIndicesKind:
  18669. case VertexBuffer.MatricesIndicesExtraKind:
  18670. stride = 4;
  18671. break;
  18672. case VertexBuffer.MatricesWeightsKind:
  18673. case VertexBuffer.MatricesWeightsExtraKind:
  18674. stride = 4;
  18675. break;
  18676. }
  18677. }
  18678. if (data instanceof BABYLON.Buffer) {
  18679. if (!stride) {
  18680. stride = data.getStrideSize();
  18681. }
  18682. this._buffer = data;
  18683. this._ownsBuffer = false;
  18684. }
  18685. else {
  18686. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18687. this._ownsBuffer = true;
  18688. }
  18689. this._stride = stride;
  18690. this._offset = offset ? offset : 0;
  18691. this._size = size ? size : stride;
  18692. this._kind = kind;
  18693. }
  18694. /**
  18695. * Returns the kind of the VertexBuffer (string).
  18696. */
  18697. VertexBuffer.prototype.getKind = function () {
  18698. return this._kind;
  18699. };
  18700. // Properties
  18701. /**
  18702. * Boolean : is the VertexBuffer updatable ?
  18703. */
  18704. VertexBuffer.prototype.isUpdatable = function () {
  18705. return this._buffer.isUpdatable();
  18706. };
  18707. /**
  18708. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18709. */
  18710. VertexBuffer.prototype.getData = function () {
  18711. return this._buffer.getData();
  18712. };
  18713. /**
  18714. * Returns the WebGLBuffer associated to the VertexBuffer.
  18715. */
  18716. VertexBuffer.prototype.getBuffer = function () {
  18717. return this._buffer.getBuffer();
  18718. };
  18719. /**
  18720. * Returns the stride of the VertexBuffer (integer).
  18721. */
  18722. VertexBuffer.prototype.getStrideSize = function () {
  18723. return this._stride;
  18724. };
  18725. /**
  18726. * Returns the offset (integer).
  18727. */
  18728. VertexBuffer.prototype.getOffset = function () {
  18729. return this._offset;
  18730. };
  18731. /**
  18732. * Returns the VertexBuffer total size (integer).
  18733. */
  18734. VertexBuffer.prototype.getSize = function () {
  18735. return this._size;
  18736. };
  18737. /**
  18738. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18739. */
  18740. VertexBuffer.prototype.getIsInstanced = function () {
  18741. return this._buffer.getIsInstanced();
  18742. };
  18743. /**
  18744. * Returns the instancing divisor, zero for non-instanced (integer).
  18745. */
  18746. VertexBuffer.prototype.getInstanceDivisor = function () {
  18747. return this._buffer.instanceDivisor;
  18748. };
  18749. // Methods
  18750. /**
  18751. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18752. * Returns the created WebGLBuffer.
  18753. */
  18754. VertexBuffer.prototype.create = function (data) {
  18755. return this._buffer.create(data);
  18756. };
  18757. /**
  18758. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18759. * Returns the updated WebGLBuffer.
  18760. */
  18761. VertexBuffer.prototype.update = function (data) {
  18762. return this._buffer.update(data);
  18763. };
  18764. /**
  18765. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18766. * Returns the directly updated WebGLBuffer.
  18767. */
  18768. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18769. return this._buffer.updateDirectly(data, offset);
  18770. };
  18771. /**
  18772. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18773. */
  18774. VertexBuffer.prototype.dispose = function () {
  18775. if (this._ownsBuffer) {
  18776. this._buffer.dispose();
  18777. }
  18778. };
  18779. Object.defineProperty(VertexBuffer, "PositionKind", {
  18780. get: function () {
  18781. return VertexBuffer._PositionKind;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(VertexBuffer, "NormalKind", {
  18787. get: function () {
  18788. return VertexBuffer._NormalKind;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(VertexBuffer, "TangentKind", {
  18794. get: function () {
  18795. return VertexBuffer._TangentKind;
  18796. },
  18797. enumerable: true,
  18798. configurable: true
  18799. });
  18800. Object.defineProperty(VertexBuffer, "UVKind", {
  18801. get: function () {
  18802. return VertexBuffer._UVKind;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18808. get: function () {
  18809. return VertexBuffer._UV2Kind;
  18810. },
  18811. enumerable: true,
  18812. configurable: true
  18813. });
  18814. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18815. get: function () {
  18816. return VertexBuffer._UV3Kind;
  18817. },
  18818. enumerable: true,
  18819. configurable: true
  18820. });
  18821. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18822. get: function () {
  18823. return VertexBuffer._UV4Kind;
  18824. },
  18825. enumerable: true,
  18826. configurable: true
  18827. });
  18828. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18829. get: function () {
  18830. return VertexBuffer._UV5Kind;
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18836. get: function () {
  18837. return VertexBuffer._UV6Kind;
  18838. },
  18839. enumerable: true,
  18840. configurable: true
  18841. });
  18842. Object.defineProperty(VertexBuffer, "ColorKind", {
  18843. get: function () {
  18844. return VertexBuffer._ColorKind;
  18845. },
  18846. enumerable: true,
  18847. configurable: true
  18848. });
  18849. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18850. get: function () {
  18851. return VertexBuffer._MatricesIndicesKind;
  18852. },
  18853. enumerable: true,
  18854. configurable: true
  18855. });
  18856. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18857. get: function () {
  18858. return VertexBuffer._MatricesWeightsKind;
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18864. get: function () {
  18865. return VertexBuffer._MatricesIndicesExtraKind;
  18866. },
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18871. get: function () {
  18872. return VertexBuffer._MatricesWeightsExtraKind;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. return VertexBuffer;
  18878. }());
  18879. // Enums
  18880. VertexBuffer._PositionKind = "position";
  18881. VertexBuffer._NormalKind = "normal";
  18882. VertexBuffer._TangentKind = "tangent";
  18883. VertexBuffer._UVKind = "uv";
  18884. VertexBuffer._UV2Kind = "uv2";
  18885. VertexBuffer._UV3Kind = "uv3";
  18886. VertexBuffer._UV4Kind = "uv4";
  18887. VertexBuffer._UV5Kind = "uv5";
  18888. VertexBuffer._UV6Kind = "uv6";
  18889. VertexBuffer._ColorKind = "color";
  18890. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18891. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18892. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18893. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18894. BABYLON.VertexBuffer = VertexBuffer;
  18895. })(BABYLON || (BABYLON = {}));
  18896. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18897. var BABYLON;
  18898. (function (BABYLON) {
  18899. var BaseTexture = (function () {
  18900. function BaseTexture(scene) {
  18901. this._hasAlpha = false;
  18902. this.getAlphaFromRGB = false;
  18903. this.level = 1;
  18904. this.coordinatesIndex = 0;
  18905. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18906. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18907. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18908. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18909. this.isCube = false;
  18910. this.isRenderTarget = false;
  18911. this.animations = new Array();
  18912. /**
  18913. * An event triggered when the texture is disposed.
  18914. * @type {BABYLON.Observable}
  18915. */
  18916. this.onDisposeObservable = new BABYLON.Observable();
  18917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18918. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18919. this._scene.textures.push(this);
  18920. this._uid = null;
  18921. }
  18922. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18923. get: function () {
  18924. return this._hasAlpha;
  18925. },
  18926. set: function (value) {
  18927. if (this._hasAlpha === value) {
  18928. return;
  18929. }
  18930. this._hasAlpha = value;
  18931. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18932. },
  18933. enumerable: true,
  18934. configurable: true
  18935. });
  18936. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18937. get: function () {
  18938. return this._coordinatesMode;
  18939. },
  18940. set: function (value) {
  18941. if (this._coordinatesMode === value) {
  18942. return;
  18943. }
  18944. this._coordinatesMode = value;
  18945. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18946. },
  18947. enumerable: true,
  18948. configurable: true
  18949. });
  18950. Object.defineProperty(BaseTexture.prototype, "uid", {
  18951. get: function () {
  18952. if (!this._uid) {
  18953. this._uid = BABYLON.Tools.RandomId();
  18954. }
  18955. return this._uid;
  18956. },
  18957. enumerable: true,
  18958. configurable: true
  18959. });
  18960. BaseTexture.prototype.toString = function () {
  18961. return this.name;
  18962. };
  18963. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18964. set: function (callback) {
  18965. if (this._onDisposeObserver) {
  18966. this.onDisposeObservable.remove(this._onDisposeObserver);
  18967. }
  18968. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18969. },
  18970. enumerable: true,
  18971. configurable: true
  18972. });
  18973. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18974. get: function () {
  18975. return true;
  18976. },
  18977. enumerable: true,
  18978. configurable: true
  18979. });
  18980. BaseTexture.prototype.getScene = function () {
  18981. return this._scene;
  18982. };
  18983. BaseTexture.prototype.getTextureMatrix = function () {
  18984. return null;
  18985. };
  18986. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18987. return null;
  18988. };
  18989. BaseTexture.prototype.getInternalTexture = function () {
  18990. return this._texture;
  18991. };
  18992. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18993. return !this.isBlocking || this.isReady();
  18994. };
  18995. BaseTexture.prototype.isReady = function () {
  18996. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18997. this.delayLoad();
  18998. return false;
  18999. }
  19000. if (this._texture) {
  19001. return this._texture.isReady;
  19002. }
  19003. return false;
  19004. };
  19005. BaseTexture.prototype.getSize = function () {
  19006. if (this._texture._width) {
  19007. return new BABYLON.Size(this._texture._width, this._texture._height);
  19008. }
  19009. if (this._texture._size) {
  19010. return new BABYLON.Size(this._texture._size, this._texture._size);
  19011. }
  19012. return BABYLON.Size.Zero();
  19013. };
  19014. BaseTexture.prototype.getBaseSize = function () {
  19015. if (!this.isReady() || !this._texture)
  19016. return BABYLON.Size.Zero();
  19017. if (this._texture._size) {
  19018. return new BABYLON.Size(this._texture._size, this._texture._size);
  19019. }
  19020. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  19021. };
  19022. BaseTexture.prototype.scale = function (ratio) {
  19023. };
  19024. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  19025. get: function () {
  19026. return false;
  19027. },
  19028. enumerable: true,
  19029. configurable: true
  19030. });
  19031. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  19032. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19033. for (var index = 0; index < texturesCache.length; index++) {
  19034. var texturesCacheEntry = texturesCache[index];
  19035. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19036. texturesCache.splice(index, 1);
  19037. return;
  19038. }
  19039. }
  19040. };
  19041. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  19042. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  19043. for (var index = 0; index < texturesCache.length; index++) {
  19044. var texturesCacheEntry = texturesCache[index];
  19045. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  19046. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  19047. texturesCacheEntry.references++;
  19048. return texturesCacheEntry;
  19049. }
  19050. }
  19051. }
  19052. return null;
  19053. };
  19054. BaseTexture.prototype.delayLoad = function () {
  19055. };
  19056. BaseTexture.prototype.clone = function () {
  19057. return null;
  19058. };
  19059. BaseTexture.prototype.readPixels = function (faceIndex) {
  19060. if (faceIndex === void 0) { faceIndex = 0; }
  19061. if (!this._texture) {
  19062. return null;
  19063. }
  19064. var size = this.getSize();
  19065. var engine = this.getScene().getEngine();
  19066. if (this._texture.isCube) {
  19067. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  19068. }
  19069. return engine._readTexturePixels(this._texture, size.width, size.height);
  19070. };
  19071. BaseTexture.prototype.releaseInternalTexture = function () {
  19072. if (this._texture) {
  19073. this._scene.getEngine().releaseInternalTexture(this._texture);
  19074. delete this._texture;
  19075. }
  19076. };
  19077. BaseTexture.prototype.dispose = function () {
  19078. // Animations
  19079. this.getScene().stopAnimation(this);
  19080. // Remove from scene
  19081. this._scene._removePendingData(this);
  19082. var index = this._scene.textures.indexOf(this);
  19083. if (index >= 0) {
  19084. this._scene.textures.splice(index, 1);
  19085. }
  19086. if (this._texture === undefined) {
  19087. return;
  19088. }
  19089. // Release
  19090. this.releaseInternalTexture();
  19091. // Callback
  19092. this.onDisposeObservable.notifyObservers(this);
  19093. this.onDisposeObservable.clear();
  19094. };
  19095. BaseTexture.prototype.serialize = function () {
  19096. if (!this.name) {
  19097. return null;
  19098. }
  19099. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19100. // Animations
  19101. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19102. return serializationObject;
  19103. };
  19104. BaseTexture.WhenAllReady = function (textures, onLoad) {
  19105. var numReady = 0;
  19106. var _loop_1 = function () {
  19107. texture = textures[i];
  19108. if (texture.isReady()) {
  19109. if (++numReady === textures.length) {
  19110. onLoad();
  19111. }
  19112. }
  19113. else {
  19114. observable = texture.onLoadObservable;
  19115. var callback_1 = function () {
  19116. observable.removeCallback(callback_1);
  19117. if (++numReady === textures.length) {
  19118. onLoad();
  19119. }
  19120. };
  19121. observable.add(callback_1);
  19122. }
  19123. };
  19124. var texture, observable;
  19125. for (var i = 0; i < textures.length; i++) {
  19126. _loop_1();
  19127. }
  19128. };
  19129. return BaseTexture;
  19130. }());
  19131. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  19132. __decorate([
  19133. BABYLON.serialize()
  19134. ], BaseTexture.prototype, "name", void 0);
  19135. __decorate([
  19136. BABYLON.serialize("hasAlpha")
  19137. ], BaseTexture.prototype, "_hasAlpha", void 0);
  19138. __decorate([
  19139. BABYLON.serialize()
  19140. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  19141. __decorate([
  19142. BABYLON.serialize()
  19143. ], BaseTexture.prototype, "level", void 0);
  19144. __decorate([
  19145. BABYLON.serialize()
  19146. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  19147. __decorate([
  19148. BABYLON.serialize("coordinatesMode")
  19149. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  19150. __decorate([
  19151. BABYLON.serialize()
  19152. ], BaseTexture.prototype, "wrapU", void 0);
  19153. __decorate([
  19154. BABYLON.serialize()
  19155. ], BaseTexture.prototype, "wrapV", void 0);
  19156. __decorate([
  19157. BABYLON.serialize()
  19158. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  19159. __decorate([
  19160. BABYLON.serialize()
  19161. ], BaseTexture.prototype, "isCube", void 0);
  19162. __decorate([
  19163. BABYLON.serialize()
  19164. ], BaseTexture.prototype, "isRenderTarget", void 0);
  19165. BABYLON.BaseTexture = BaseTexture;
  19166. })(BABYLON || (BABYLON = {}));
  19167. //# sourceMappingURL=babylon.baseTexture.js.map
  19168. var BABYLON;
  19169. (function (BABYLON) {
  19170. var Texture = (function (_super) {
  19171. __extends(Texture, _super);
  19172. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19173. if (noMipmap === void 0) { noMipmap = false; }
  19174. if (invertY === void 0) { invertY = true; }
  19175. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19176. if (onLoad === void 0) { onLoad = null; }
  19177. if (onError === void 0) { onError = null; }
  19178. if (buffer === void 0) { buffer = null; }
  19179. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19180. var _this = _super.call(this, scene) || this;
  19181. _this.uOffset = 0;
  19182. _this.vOffset = 0;
  19183. _this.uScale = 1.0;
  19184. _this.vScale = 1.0;
  19185. _this.uAng = 0;
  19186. _this.vAng = 0;
  19187. _this.wAng = 0;
  19188. _this._isBlocking = true;
  19189. _this.name = url;
  19190. _this.url = url;
  19191. _this._noMipmap = noMipmap;
  19192. _this._invertY = invertY;
  19193. _this._samplingMode = samplingMode;
  19194. _this._buffer = buffer;
  19195. _this._deleteBuffer = deleteBuffer;
  19196. _this._format = format;
  19197. scene = _this.getScene();
  19198. var load = function () {
  19199. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  19200. _this.onLoadObservable.notifyObservers(_this);
  19201. }
  19202. if (onLoad) {
  19203. onLoad();
  19204. }
  19205. if (!_this.isBlocking) {
  19206. scene.resetCachedMaterial();
  19207. }
  19208. };
  19209. if (!url) {
  19210. _this._delayedOnLoad = load;
  19211. _this._delayedOnError = onError;
  19212. return _this;
  19213. }
  19214. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19215. if (!_this._texture) {
  19216. if (!scene.useDelayedTextureLoading) {
  19217. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19218. if (deleteBuffer) {
  19219. delete _this._buffer;
  19220. }
  19221. }
  19222. else {
  19223. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19224. _this._delayedOnLoad = load;
  19225. _this._delayedOnError = onError;
  19226. }
  19227. }
  19228. else {
  19229. if (_this._texture.isReady) {
  19230. BABYLON.Tools.SetImmediate(function () { return load(); });
  19231. }
  19232. else {
  19233. _this._texture.onLoadedCallbacks.push(load);
  19234. }
  19235. }
  19236. return _this;
  19237. }
  19238. Object.defineProperty(Texture.prototype, "noMipmap", {
  19239. get: function () {
  19240. return this._noMipmap;
  19241. },
  19242. enumerable: true,
  19243. configurable: true
  19244. });
  19245. Object.defineProperty(Texture.prototype, "isBlocking", {
  19246. get: function () {
  19247. return this._isBlocking;
  19248. },
  19249. set: function (value) {
  19250. this._isBlocking = value;
  19251. },
  19252. enumerable: true,
  19253. configurable: true
  19254. });
  19255. Texture.prototype.updateURL = function (url) {
  19256. this.url = url;
  19257. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19258. this.delayLoad();
  19259. };
  19260. Texture.prototype.delayLoad = function () {
  19261. var _this = this;
  19262. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19263. return;
  19264. }
  19265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19266. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19267. if (!this._texture) {
  19268. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  19269. if (this._deleteBuffer) {
  19270. delete this._buffer;
  19271. }
  19272. }
  19273. else {
  19274. if (this._texture.isReady) {
  19275. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19276. }
  19277. else {
  19278. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19279. }
  19280. }
  19281. };
  19282. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19283. if (!this._texture) {
  19284. return;
  19285. }
  19286. this._samplingMode = samplingMode;
  19287. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19288. };
  19289. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19290. x *= this.uScale;
  19291. y *= this.vScale;
  19292. x -= 0.5 * this.uScale;
  19293. y -= 0.5 * this.vScale;
  19294. z -= 0.5;
  19295. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19296. t.x += 0.5 * this.uScale + this.uOffset;
  19297. t.y += 0.5 * this.vScale + this.vOffset;
  19298. t.z += 0.5;
  19299. };
  19300. Texture.prototype.getTextureMatrix = function () {
  19301. if (this.uOffset === this._cachedUOffset &&
  19302. this.vOffset === this._cachedVOffset &&
  19303. this.uScale === this._cachedUScale &&
  19304. this.vScale === this._cachedVScale &&
  19305. this.uAng === this._cachedUAng &&
  19306. this.vAng === this._cachedVAng &&
  19307. this.wAng === this._cachedWAng) {
  19308. return this._cachedTextureMatrix;
  19309. }
  19310. this._cachedUOffset = this.uOffset;
  19311. this._cachedVOffset = this.vOffset;
  19312. this._cachedUScale = this.uScale;
  19313. this._cachedVScale = this.vScale;
  19314. this._cachedUAng = this.uAng;
  19315. this._cachedVAng = this.vAng;
  19316. this._cachedWAng = this.wAng;
  19317. if (!this._cachedTextureMatrix) {
  19318. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19319. this._rowGenerationMatrix = new BABYLON.Matrix();
  19320. this._t0 = BABYLON.Vector3.Zero();
  19321. this._t1 = BABYLON.Vector3.Zero();
  19322. this._t2 = BABYLON.Vector3.Zero();
  19323. }
  19324. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19325. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19326. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19327. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19328. this._t1.subtractInPlace(this._t0);
  19329. this._t2.subtractInPlace(this._t0);
  19330. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19331. this._cachedTextureMatrix.m[0] = this._t1.x;
  19332. this._cachedTextureMatrix.m[1] = this._t1.y;
  19333. this._cachedTextureMatrix.m[2] = this._t1.z;
  19334. this._cachedTextureMatrix.m[4] = this._t2.x;
  19335. this._cachedTextureMatrix.m[5] = this._t2.y;
  19336. this._cachedTextureMatrix.m[6] = this._t2.z;
  19337. this._cachedTextureMatrix.m[8] = this._t0.x;
  19338. this._cachedTextureMatrix.m[9] = this._t0.y;
  19339. this._cachedTextureMatrix.m[10] = this._t0.z;
  19340. return this._cachedTextureMatrix;
  19341. };
  19342. Texture.prototype.getReflectionTextureMatrix = function () {
  19343. if (this.uOffset === this._cachedUOffset &&
  19344. this.vOffset === this._cachedVOffset &&
  19345. this.uScale === this._cachedUScale &&
  19346. this.vScale === this._cachedVScale &&
  19347. this.coordinatesMode === this._cachedCoordinatesMode) {
  19348. return this._cachedTextureMatrix;
  19349. }
  19350. if (!this._cachedTextureMatrix) {
  19351. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19352. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19353. }
  19354. this._cachedCoordinatesMode = this.coordinatesMode;
  19355. switch (this.coordinatesMode) {
  19356. case Texture.PLANAR_MODE:
  19357. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19358. this._cachedTextureMatrix[0] = this.uScale;
  19359. this._cachedTextureMatrix[5] = this.vScale;
  19360. this._cachedTextureMatrix[12] = this.uOffset;
  19361. this._cachedTextureMatrix[13] = this.vOffset;
  19362. break;
  19363. case Texture.PROJECTION_MODE:
  19364. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19365. this._projectionModeMatrix.m[0] = 0.5;
  19366. this._projectionModeMatrix.m[5] = -0.5;
  19367. this._projectionModeMatrix.m[10] = 0.0;
  19368. this._projectionModeMatrix.m[12] = 0.5;
  19369. this._projectionModeMatrix.m[13] = 0.5;
  19370. this._projectionModeMatrix.m[14] = 1.0;
  19371. this._projectionModeMatrix.m[15] = 1.0;
  19372. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19373. break;
  19374. default:
  19375. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19376. break;
  19377. }
  19378. return this._cachedTextureMatrix;
  19379. };
  19380. Texture.prototype.clone = function () {
  19381. var _this = this;
  19382. return BABYLON.SerializationHelper.Clone(function () {
  19383. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19384. }, this);
  19385. };
  19386. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19387. get: function () {
  19388. if (!this._onLoadObservable) {
  19389. this._onLoadObservable = new BABYLON.Observable();
  19390. }
  19391. return this._onLoadObservable;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. // Statics
  19397. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19398. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19399. if (onLoad === void 0) { onLoad = null; }
  19400. if (onError === void 0) { onError = null; }
  19401. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19402. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19403. };
  19404. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19405. if (parsedTexture.customType) {
  19406. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19407. // Update Sampling Mode
  19408. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19409. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19410. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19411. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19412. }
  19413. }
  19414. return parsedCustomTexture;
  19415. }
  19416. if (parsedTexture.isCube) {
  19417. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19418. }
  19419. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19420. return null;
  19421. }
  19422. var texture = BABYLON.SerializationHelper.Parse(function () {
  19423. if (parsedTexture.mirrorPlane) {
  19424. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19425. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19426. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19427. return mirrorTexture;
  19428. }
  19429. else if (parsedTexture.isRenderTarget) {
  19430. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19431. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19432. return renderTargetTexture;
  19433. }
  19434. else {
  19435. var texture;
  19436. if (parsedTexture.base64String) {
  19437. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19438. }
  19439. else {
  19440. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19441. }
  19442. return texture;
  19443. }
  19444. }, parsedTexture, scene);
  19445. // Update Sampling Mode
  19446. if (parsedTexture.samplingMode) {
  19447. var sampling = parsedTexture.samplingMode;
  19448. if (texture._samplingMode !== sampling) {
  19449. texture.updateSamplingMode(sampling);
  19450. }
  19451. }
  19452. // Animations
  19453. if (parsedTexture.animations) {
  19454. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19455. var parsedAnimation = parsedTexture.animations[animationIndex];
  19456. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19457. }
  19458. }
  19459. return texture;
  19460. };
  19461. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19462. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19463. if (noMipmap === void 0) { noMipmap = false; }
  19464. if (invertY === void 0) { invertY = true; }
  19465. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19466. if (onLoad === void 0) { onLoad = null; }
  19467. if (onError === void 0) { onError = null; }
  19468. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19469. if (name.substr(0, 5) !== "data:") {
  19470. name = "data:" + name;
  19471. }
  19472. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19473. };
  19474. return Texture;
  19475. }(BABYLON.BaseTexture));
  19476. // Constants
  19477. Texture.NEAREST_SAMPLINGMODE = 1;
  19478. Texture.BILINEAR_SAMPLINGMODE = 2;
  19479. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19480. Texture.EXPLICIT_MODE = 0;
  19481. Texture.SPHERICAL_MODE = 1;
  19482. Texture.PLANAR_MODE = 2;
  19483. Texture.CUBIC_MODE = 3;
  19484. Texture.PROJECTION_MODE = 4;
  19485. Texture.SKYBOX_MODE = 5;
  19486. Texture.INVCUBIC_MODE = 6;
  19487. Texture.EQUIRECTANGULAR_MODE = 7;
  19488. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19489. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19490. Texture.CLAMP_ADDRESSMODE = 0;
  19491. Texture.WRAP_ADDRESSMODE = 1;
  19492. Texture.MIRROR_ADDRESSMODE = 2;
  19493. __decorate([
  19494. BABYLON.serialize()
  19495. ], Texture.prototype, "url", void 0);
  19496. __decorate([
  19497. BABYLON.serialize()
  19498. ], Texture.prototype, "uOffset", void 0);
  19499. __decorate([
  19500. BABYLON.serialize()
  19501. ], Texture.prototype, "vOffset", void 0);
  19502. __decorate([
  19503. BABYLON.serialize()
  19504. ], Texture.prototype, "uScale", void 0);
  19505. __decorate([
  19506. BABYLON.serialize()
  19507. ], Texture.prototype, "vScale", void 0);
  19508. __decorate([
  19509. BABYLON.serialize()
  19510. ], Texture.prototype, "uAng", void 0);
  19511. __decorate([
  19512. BABYLON.serialize()
  19513. ], Texture.prototype, "vAng", void 0);
  19514. __decorate([
  19515. BABYLON.serialize()
  19516. ], Texture.prototype, "wAng", void 0);
  19517. __decorate([
  19518. BABYLON.serialize()
  19519. ], Texture.prototype, "isBlocking", null);
  19520. BABYLON.Texture = Texture;
  19521. })(BABYLON || (BABYLON = {}));
  19522. //# sourceMappingURL=babylon.texture.js.map
  19523. var BABYLON;
  19524. (function (BABYLON) {
  19525. var _InstancesBatch = (function () {
  19526. function _InstancesBatch() {
  19527. this.mustReturn = false;
  19528. this.visibleInstances = new Array();
  19529. this.renderSelf = new Array();
  19530. }
  19531. return _InstancesBatch;
  19532. }());
  19533. BABYLON._InstancesBatch = _InstancesBatch;
  19534. var Mesh = (function (_super) {
  19535. __extends(Mesh, _super);
  19536. /**
  19537. * @constructor
  19538. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19539. * @param {Scene} scene The scene to add this mesh to.
  19540. * @param {Node} parent The parent of this mesh, if it has one
  19541. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19542. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19543. * When false, achieved by calling a clone(), also passing False.
  19544. * This will make creation of children, recursive.
  19545. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19546. */
  19547. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19548. if (parent === void 0) { parent = null; }
  19549. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19550. var _this = _super.call(this, name, scene) || this;
  19551. // Events
  19552. /**
  19553. * An event triggered before rendering the mesh
  19554. * @type {BABYLON.Observable}
  19555. */
  19556. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19557. /**
  19558. * An event triggered after rendering the mesh
  19559. * @type {BABYLON.Observable}
  19560. */
  19561. _this.onAfterRenderObservable = new BABYLON.Observable();
  19562. /**
  19563. * An event triggered before drawing the mesh
  19564. * @type {BABYLON.Observable}
  19565. */
  19566. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19567. // Members
  19568. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19569. _this.instances = new Array();
  19570. _this._LODLevels = new Array();
  19571. _this._visibleInstances = {};
  19572. _this._renderIdForInstances = new Array();
  19573. _this._batchCache = new _InstancesBatch();
  19574. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19575. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19576. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19577. // Will be used to save a source mesh reference, If any
  19578. _this._source = null;
  19579. if (source) {
  19580. // Source mesh
  19581. _this._source = source;
  19582. // Geometry
  19583. if (source._geometry) {
  19584. source._geometry.applyToMesh(_this);
  19585. }
  19586. // Deep copy
  19587. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19588. // Parent
  19589. _this.parent = source.parent;
  19590. // Pivot
  19591. _this.setPivotMatrix(source.getPivotMatrix());
  19592. _this.id = name + "." + source.id;
  19593. // Material
  19594. _this.material = source.material;
  19595. var index;
  19596. if (!doNotCloneChildren) {
  19597. // Children
  19598. for (index = 0; index < scene.meshes.length; index++) {
  19599. var mesh = scene.meshes[index];
  19600. if (mesh.parent === source) {
  19601. // doNotCloneChildren is always going to be False
  19602. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19603. }
  19604. }
  19605. }
  19606. // Physics clone
  19607. var physicsEngine = _this.getScene().getPhysicsEngine();
  19608. if (clonePhysicsImpostor && physicsEngine) {
  19609. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19610. if (impostor) {
  19611. _this.physicsImpostor = impostor.clone(_this);
  19612. }
  19613. }
  19614. // Particles
  19615. for (index = 0; index < scene.particleSystems.length; index++) {
  19616. var system = scene.particleSystems[index];
  19617. if (system.emitter === source) {
  19618. system.clone(system.name, _this);
  19619. }
  19620. }
  19621. _this.computeWorldMatrix(true);
  19622. }
  19623. // Parent
  19624. if (parent !== null) {
  19625. _this.parent = parent;
  19626. }
  19627. return _this;
  19628. }
  19629. Object.defineProperty(Mesh, "FRONTSIDE", {
  19630. /**
  19631. * Mesh side orientation : usually the external or front surface
  19632. */
  19633. get: function () {
  19634. return Mesh._FRONTSIDE;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Mesh, "BACKSIDE", {
  19640. /**
  19641. * Mesh side orientation : usually the internal or back surface
  19642. */
  19643. get: function () {
  19644. return Mesh._BACKSIDE;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19650. /**
  19651. * Mesh side orientation : both internal and external or front and back surfaces
  19652. */
  19653. get: function () {
  19654. return Mesh._DOUBLESIDE;
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19660. /**
  19661. * Mesh side orientation : by default, `FRONTSIDE`
  19662. */
  19663. get: function () {
  19664. return Mesh._DEFAULTSIDE;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. Object.defineProperty(Mesh, "NO_CAP", {
  19670. /**
  19671. * Mesh cap setting : no cap
  19672. */
  19673. get: function () {
  19674. return Mesh._NO_CAP;
  19675. },
  19676. enumerable: true,
  19677. configurable: true
  19678. });
  19679. Object.defineProperty(Mesh, "CAP_START", {
  19680. /**
  19681. * Mesh cap setting : one cap at the beginning of the mesh
  19682. */
  19683. get: function () {
  19684. return Mesh._CAP_START;
  19685. },
  19686. enumerable: true,
  19687. configurable: true
  19688. });
  19689. Object.defineProperty(Mesh, "CAP_END", {
  19690. /**
  19691. * Mesh cap setting : one cap at the end of the mesh
  19692. */
  19693. get: function () {
  19694. return Mesh._CAP_END;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Mesh, "CAP_ALL", {
  19700. /**
  19701. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19702. */
  19703. get: function () {
  19704. return Mesh._CAP_ALL;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19710. set: function (callback) {
  19711. if (this._onBeforeDrawObserver) {
  19712. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19713. }
  19714. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19715. },
  19716. enumerable: true,
  19717. configurable: true
  19718. });
  19719. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19720. get: function () {
  19721. return this._morphTargetManager;
  19722. },
  19723. set: function (value) {
  19724. if (this._morphTargetManager === value) {
  19725. return;
  19726. }
  19727. this._morphTargetManager = value;
  19728. this._syncGeometryWithMorphTargetManager();
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(Mesh.prototype, "source", {
  19734. get: function () {
  19735. return this._source;
  19736. },
  19737. enumerable: true,
  19738. configurable: true
  19739. });
  19740. // Methods
  19741. /**
  19742. * Returns the string "Mesh".
  19743. */
  19744. Mesh.prototype.getClassName = function () {
  19745. return "Mesh";
  19746. };
  19747. /**
  19748. * Returns a string.
  19749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19750. */
  19751. Mesh.prototype.toString = function (fullDetails) {
  19752. var ret = _super.prototype.toString.call(this, fullDetails);
  19753. ret += ", n vertices: " + this.getTotalVertices();
  19754. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19755. if (this.animations) {
  19756. for (var i = 0; i < this.animations.length; i++) {
  19757. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19758. }
  19759. }
  19760. if (fullDetails) {
  19761. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19762. }
  19763. return ret;
  19764. };
  19765. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19766. /**
  19767. * True if the mesh has some Levels Of Details (LOD).
  19768. * Returns a boolean.
  19769. */
  19770. get: function () {
  19771. return this._LODLevels.length > 0;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Mesh.prototype._sortLODLevels = function () {
  19777. this._LODLevels.sort(function (a, b) {
  19778. if (a.distance < b.distance) {
  19779. return 1;
  19780. }
  19781. if (a.distance > b.distance) {
  19782. return -1;
  19783. }
  19784. return 0;
  19785. });
  19786. };
  19787. /**
  19788. * Add a mesh as LOD level triggered at the given distance.
  19789. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19790. * @param {number} distance The distance from the center of the object to show this level
  19791. * @param {Mesh} mesh The mesh to be added as LOD level
  19792. * @return {Mesh} This mesh (for chaining)
  19793. */
  19794. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19795. if (mesh && mesh._masterMesh) {
  19796. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19797. return this;
  19798. }
  19799. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19800. this._LODLevels.push(level);
  19801. if (mesh) {
  19802. mesh._masterMesh = this;
  19803. }
  19804. this._sortLODLevels();
  19805. return this;
  19806. };
  19807. /**
  19808. * Returns the LOD level mesh at the passed distance or null if not found.
  19809. * It is related to the method `addLODLevel(distance, mesh)`.
  19810. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19811. * Returns an object Mesh or `null`.
  19812. */
  19813. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19814. for (var index = 0; index < this._LODLevels.length; index++) {
  19815. var level = this._LODLevels[index];
  19816. if (level.distance === distance) {
  19817. return level.mesh;
  19818. }
  19819. }
  19820. return null;
  19821. };
  19822. /**
  19823. * Remove a mesh from the LOD array
  19824. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19825. * @param {Mesh} mesh The mesh to be removed.
  19826. * @return {Mesh} This mesh (for chaining)
  19827. */
  19828. Mesh.prototype.removeLODLevel = function (mesh) {
  19829. for (var index = 0; index < this._LODLevels.length; index++) {
  19830. if (this._LODLevels[index].mesh === mesh) {
  19831. this._LODLevels.splice(index, 1);
  19832. if (mesh) {
  19833. mesh._masterMesh = null;
  19834. }
  19835. }
  19836. }
  19837. this._sortLODLevels();
  19838. return this;
  19839. };
  19840. /**
  19841. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19842. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19843. */
  19844. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19845. if (!this._LODLevels || this._LODLevels.length === 0) {
  19846. return this;
  19847. }
  19848. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19849. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19850. if (this.onLODLevelSelection) {
  19851. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19852. }
  19853. return this;
  19854. }
  19855. for (var index = 0; index < this._LODLevels.length; index++) {
  19856. var level = this._LODLevels[index];
  19857. if (level.distance < distanceToCamera) {
  19858. if (level.mesh) {
  19859. level.mesh._preActivate();
  19860. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19861. }
  19862. if (this.onLODLevelSelection) {
  19863. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19864. }
  19865. return level.mesh;
  19866. }
  19867. }
  19868. if (this.onLODLevelSelection) {
  19869. this.onLODLevelSelection(distanceToCamera, this, this);
  19870. }
  19871. return this;
  19872. };
  19873. Object.defineProperty(Mesh.prototype, "geometry", {
  19874. /**
  19875. * Returns the mesh internal Geometry object.
  19876. */
  19877. get: function () {
  19878. return this._geometry;
  19879. },
  19880. enumerable: true,
  19881. configurable: true
  19882. });
  19883. /**
  19884. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19885. */
  19886. Mesh.prototype.getTotalVertices = function () {
  19887. if (!this._geometry) {
  19888. return 0;
  19889. }
  19890. return this._geometry.getTotalVertices();
  19891. };
  19892. /**
  19893. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19894. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  19895. * You can force the copy with forceCopy === true
  19896. * Returns null if the mesh has no geometry or no vertex buffer.
  19897. * Possible `kind` values :
  19898. * - BABYLON.VertexBuffer.PositionKind
  19899. * - BABYLON.VertexBuffer.UVKind
  19900. * - BABYLON.VertexBuffer.UV2Kind
  19901. * - BABYLON.VertexBuffer.UV3Kind
  19902. * - BABYLON.VertexBuffer.UV4Kind
  19903. * - BABYLON.VertexBuffer.UV5Kind
  19904. * - BABYLON.VertexBuffer.UV6Kind
  19905. * - BABYLON.VertexBuffer.ColorKind
  19906. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19907. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19908. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19909. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19910. */
  19911. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19912. if (!this._geometry) {
  19913. return null;
  19914. }
  19915. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19916. };
  19917. /**
  19918. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19919. * Returns `undefined` if the mesh has no geometry.
  19920. * Possible `kind` values :
  19921. * - BABYLON.VertexBuffer.PositionKind
  19922. * - BABYLON.VertexBuffer.UVKind
  19923. * - BABYLON.VertexBuffer.UV2Kind
  19924. * - BABYLON.VertexBuffer.UV3Kind
  19925. * - BABYLON.VertexBuffer.UV4Kind
  19926. * - BABYLON.VertexBuffer.UV5Kind
  19927. * - BABYLON.VertexBuffer.UV6Kind
  19928. * - BABYLON.VertexBuffer.ColorKind
  19929. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19930. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19931. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19932. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19933. */
  19934. Mesh.prototype.getVertexBuffer = function (kind) {
  19935. if (!this._geometry) {
  19936. return undefined;
  19937. }
  19938. return this._geometry.getVertexBuffer(kind);
  19939. };
  19940. /**
  19941. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19942. * Possible `kind` values :
  19943. * - BABYLON.VertexBuffer.PositionKind
  19944. * - BABYLON.VertexBuffer.UVKind
  19945. * - BABYLON.VertexBuffer.UV2Kind
  19946. * - BABYLON.VertexBuffer.UV3Kind
  19947. * - BABYLON.VertexBuffer.UV4Kind
  19948. * - BABYLON.VertexBuffer.UV5Kind
  19949. * - BABYLON.VertexBuffer.UV6Kind
  19950. * - BABYLON.VertexBuffer.ColorKind
  19951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19955. */
  19956. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19957. if (!this._geometry) {
  19958. if (this._delayInfo) {
  19959. return this._delayInfo.indexOf(kind) !== -1;
  19960. }
  19961. return false;
  19962. }
  19963. return this._geometry.isVerticesDataPresent(kind);
  19964. };
  19965. /**
  19966. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19967. * Possible `kind` values :
  19968. * - BABYLON.VertexBuffer.PositionKind
  19969. * - BABYLON.VertexBuffer.UVKind
  19970. * - BABYLON.VertexBuffer.UV2Kind
  19971. * - BABYLON.VertexBuffer.UV3Kind
  19972. * - BABYLON.VertexBuffer.UV4Kind
  19973. * - BABYLON.VertexBuffer.UV5Kind
  19974. * - BABYLON.VertexBuffer.UV6Kind
  19975. * - BABYLON.VertexBuffer.ColorKind
  19976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19980. */
  19981. Mesh.prototype.getVerticesDataKinds = function () {
  19982. if (!this._geometry) {
  19983. var result = [];
  19984. if (this._delayInfo) {
  19985. this._delayInfo.forEach(function (kind, index, array) {
  19986. result.push(kind);
  19987. });
  19988. }
  19989. return result;
  19990. }
  19991. return this._geometry.getVerticesDataKinds();
  19992. };
  19993. /**
  19994. * Returns a positive integer : the total number of indices in this mesh geometry.
  19995. * Returns zero if the mesh has no geometry.
  19996. */
  19997. Mesh.prototype.getTotalIndices = function () {
  19998. if (!this._geometry) {
  19999. return 0;
  20000. }
  20001. return this._geometry.getTotalIndices();
  20002. };
  20003. /**
  20004. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20005. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  20006. * Returns an empty array if the mesh has no geometry.
  20007. */
  20008. Mesh.prototype.getIndices = function (copyWhenShared) {
  20009. if (!this._geometry) {
  20010. return [];
  20011. }
  20012. return this._geometry.getIndices(copyWhenShared);
  20013. };
  20014. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20015. get: function () {
  20016. return this._masterMesh !== null && this._masterMesh !== undefined;
  20017. },
  20018. enumerable: true,
  20019. configurable: true
  20020. });
  20021. /**
  20022. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20023. */
  20024. Mesh.prototype.isReady = function () {
  20025. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20026. return false;
  20027. }
  20028. return _super.prototype.isReady.call(this);
  20029. };
  20030. /**
  20031. * Boolean : true if the mesh has been disposed.
  20032. */
  20033. Mesh.prototype.isDisposed = function () {
  20034. return this._isDisposed;
  20035. };
  20036. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20037. get: function () {
  20038. return this._sideOrientation;
  20039. },
  20040. /**
  20041. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20042. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20043. */
  20044. set: function (sideO) {
  20045. this._sideOrientation = sideO;
  20046. },
  20047. enumerable: true,
  20048. configurable: true
  20049. });
  20050. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20051. /**
  20052. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20053. * This property is pertinent only for updatable parametric shapes.
  20054. */
  20055. get: function () {
  20056. return this._areNormalsFrozen;
  20057. },
  20058. enumerable: true,
  20059. configurable: true
  20060. });
  20061. /**
  20062. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20063. * It has no effect at all on other shapes.
  20064. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20065. * Returns the Mesh.
  20066. */
  20067. Mesh.prototype.freezeNormals = function () {
  20068. this._areNormalsFrozen = true;
  20069. return this;
  20070. };
  20071. /**
  20072. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20073. * It has no effect at all on other shapes.
  20074. * It reactivates the mesh normals computation if it was previously frozen.
  20075. * Returns the Mesh.
  20076. */
  20077. Mesh.prototype.unfreezeNormals = function () {
  20078. this._areNormalsFrozen = false;
  20079. return this;
  20080. };
  20081. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20082. /**
  20083. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20084. */
  20085. set: function (count) {
  20086. this._overridenInstanceCount = count;
  20087. },
  20088. enumerable: true,
  20089. configurable: true
  20090. });
  20091. // Methods
  20092. Mesh.prototype._preActivate = function () {
  20093. var sceneRenderId = this.getScene().getRenderId();
  20094. if (this._preActivateId === sceneRenderId) {
  20095. return this;
  20096. }
  20097. this._preActivateId = sceneRenderId;
  20098. this._visibleInstances = null;
  20099. return this;
  20100. };
  20101. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20102. if (this._visibleInstances) {
  20103. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20104. }
  20105. return this;
  20106. };
  20107. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20108. if (!this._visibleInstances) {
  20109. this._visibleInstances = {};
  20110. this._visibleInstances.defaultRenderId = renderId;
  20111. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20112. }
  20113. if (!this._visibleInstances[renderId]) {
  20114. this._visibleInstances[renderId] = new Array();
  20115. }
  20116. this._visibleInstances[renderId].push(instance);
  20117. return this;
  20118. };
  20119. /**
  20120. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20121. * This means the mesh underlying bounding box and sphere are recomputed.
  20122. * Returns the Mesh.
  20123. */
  20124. Mesh.prototype.refreshBoundingInfo = function () {
  20125. if (this._boundingInfo.isLocked) {
  20126. return;
  20127. }
  20128. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20129. if (data) {
  20130. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20131. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20132. }
  20133. if (this.subMeshes) {
  20134. for (var index = 0; index < this.subMeshes.length; index++) {
  20135. this.subMeshes[index].refreshBoundingInfo();
  20136. }
  20137. }
  20138. this._updateBoundingInfo();
  20139. return this;
  20140. };
  20141. Mesh.prototype._createGlobalSubMesh = function () {
  20142. var totalVertices = this.getTotalVertices();
  20143. if (!totalVertices || !this.getIndices()) {
  20144. return null;
  20145. }
  20146. this.releaseSubMeshes();
  20147. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20148. };
  20149. Mesh.prototype.subdivide = function (count) {
  20150. if (count < 1) {
  20151. return;
  20152. }
  20153. var totalIndices = this.getTotalIndices();
  20154. var subdivisionSize = (totalIndices / count) | 0;
  20155. var offset = 0;
  20156. // Ensure that subdivisionSize is a multiple of 3
  20157. while (subdivisionSize % 3 !== 0) {
  20158. subdivisionSize++;
  20159. }
  20160. this.releaseSubMeshes();
  20161. for (var index = 0; index < count; index++) {
  20162. if (offset >= totalIndices) {
  20163. break;
  20164. }
  20165. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20166. offset += subdivisionSize;
  20167. }
  20168. this.synchronizeInstances();
  20169. };
  20170. /**
  20171. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20172. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20173. * The `data` are either a numeric array either a Float32Array.
  20174. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20175. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  20176. * Note that a new underlying VertexBuffer object is created each call.
  20177. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20178. *
  20179. * Possible `kind` values :
  20180. * - BABYLON.VertexBuffer.PositionKind
  20181. * - BABYLON.VertexBuffer.UVKind
  20182. * - BABYLON.VertexBuffer.UV2Kind
  20183. * - BABYLON.VertexBuffer.UV3Kind
  20184. * - BABYLON.VertexBuffer.UV4Kind
  20185. * - BABYLON.VertexBuffer.UV5Kind
  20186. * - BABYLON.VertexBuffer.UV6Kind
  20187. * - BABYLON.VertexBuffer.ColorKind
  20188. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20189. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20190. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20191. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20192. *
  20193. * Returns the Mesh.
  20194. */
  20195. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20196. if (!this._geometry) {
  20197. var vertexData = new BABYLON.VertexData();
  20198. vertexData.set(data, kind);
  20199. var scene = this.getScene();
  20200. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20201. }
  20202. else {
  20203. this._geometry.setVerticesData(kind, data, updatable, stride);
  20204. }
  20205. return this;
  20206. };
  20207. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20208. if (updatable === void 0) { updatable = true; }
  20209. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20210. return;
  20211. }
  20212. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20213. };
  20214. /**
  20215. * Sets the mesh VertexBuffer.
  20216. * Returns the Mesh.
  20217. */
  20218. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20219. if (!this._geometry) {
  20220. var scene = this.getScene();
  20221. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20222. }
  20223. this._geometry.setVerticesBuffer(buffer);
  20224. return this;
  20225. };
  20226. /**
  20227. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20228. * If the mesh has no geometry, it is simply returned as it is.
  20229. * The `data` are either a numeric array either a Float32Array.
  20230. * No new underlying VertexBuffer object is created.
  20231. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20232. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20233. *
  20234. * Possible `kind` values :
  20235. * - BABYLON.VertexBuffer.PositionKind
  20236. * - BABYLON.VertexBuffer.UVKind
  20237. * - BABYLON.VertexBuffer.UV2Kind
  20238. * - BABYLON.VertexBuffer.UV3Kind
  20239. * - BABYLON.VertexBuffer.UV4Kind
  20240. * - BABYLON.VertexBuffer.UV5Kind
  20241. * - BABYLON.VertexBuffer.UV6Kind
  20242. * - BABYLON.VertexBuffer.ColorKind
  20243. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20244. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20245. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20246. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20247. *
  20248. * Returns the Mesh.
  20249. */
  20250. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20251. if (!this._geometry) {
  20252. return;
  20253. }
  20254. if (!makeItUnique) {
  20255. this._geometry.updateVerticesData(kind, data, updateExtends);
  20256. }
  20257. else {
  20258. this.makeGeometryUnique();
  20259. this.updateVerticesData(kind, data, updateExtends, false);
  20260. }
  20261. return this;
  20262. };
  20263. /**
  20264. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20265. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20266. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20267. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20268. * Returns the Mesh.
  20269. */
  20270. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20271. if (computeNormals === void 0) { computeNormals = true; }
  20272. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20273. positionFunction(positions);
  20274. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20275. if (computeNormals) {
  20276. var indices = this.getIndices();
  20277. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20278. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20279. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20280. }
  20281. return this;
  20282. };
  20283. /**
  20284. * Creates a un-shared specific occurence of the geometry for the mesh.
  20285. * Returns the Mesh.
  20286. */
  20287. Mesh.prototype.makeGeometryUnique = function () {
  20288. if (!this._geometry) {
  20289. return;
  20290. }
  20291. var oldGeometry = this._geometry;
  20292. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20293. oldGeometry.releaseForMesh(this, true);
  20294. geometry.applyToMesh(this);
  20295. return this;
  20296. };
  20297. /**
  20298. * Sets the mesh indices.
  20299. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20300. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20301. * This method creates a new index buffer each call.
  20302. * Returns the Mesh.
  20303. */
  20304. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20305. if (!this._geometry) {
  20306. var vertexData = new BABYLON.VertexData();
  20307. vertexData.indices = indices;
  20308. var scene = this.getScene();
  20309. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20310. }
  20311. else {
  20312. this._geometry.setIndices(indices, totalVertices);
  20313. }
  20314. return this;
  20315. };
  20316. /**
  20317. * Invert the geometry to move from a right handed system to a left handed one.
  20318. * Returns the Mesh.
  20319. */
  20320. Mesh.prototype.toLeftHanded = function () {
  20321. if (!this._geometry) {
  20322. return;
  20323. }
  20324. this._geometry.toLeftHanded();
  20325. return this;
  20326. };
  20327. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20328. var engine = this.getScene().getEngine();
  20329. // Wireframe
  20330. var indexToBind;
  20331. if (this._unIndexed) {
  20332. indexToBind = null;
  20333. }
  20334. else {
  20335. switch (fillMode) {
  20336. case BABYLON.Material.PointFillMode:
  20337. indexToBind = null;
  20338. break;
  20339. case BABYLON.Material.WireFrameFillMode:
  20340. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20341. break;
  20342. default:
  20343. case BABYLON.Material.TriangleFillMode:
  20344. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20345. break;
  20346. }
  20347. }
  20348. // VBOs
  20349. this._geometry._bind(effect, indexToBind);
  20350. return this;
  20351. };
  20352. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20353. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20354. return this;
  20355. }
  20356. this.onBeforeDrawObservable.notifyObservers(this);
  20357. var engine = this.getScene().getEngine();
  20358. // Draw order
  20359. switch (fillMode) {
  20360. case BABYLON.Material.PointFillMode:
  20361. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20362. break;
  20363. case BABYLON.Material.WireFrameFillMode:
  20364. if (this._unIndexed) {
  20365. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20366. }
  20367. else {
  20368. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20369. }
  20370. break;
  20371. default:
  20372. if (this._unIndexed) {
  20373. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20374. }
  20375. else {
  20376. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20377. }
  20378. }
  20379. return this;
  20380. };
  20381. /**
  20382. * Registers for this mesh a javascript function called just before the rendering process.
  20383. * This function is passed the current mesh.
  20384. * Return the Mesh.
  20385. */
  20386. Mesh.prototype.registerBeforeRender = function (func) {
  20387. this.onBeforeRenderObservable.add(func);
  20388. return this;
  20389. };
  20390. /**
  20391. * Disposes a previously registered javascript function called before the rendering.
  20392. * This function is passed the current mesh.
  20393. * Returns the Mesh.
  20394. */
  20395. Mesh.prototype.unregisterBeforeRender = function (func) {
  20396. this.onBeforeRenderObservable.removeCallback(func);
  20397. return this;
  20398. };
  20399. /**
  20400. * Registers for this mesh a javascript function called just after the rendering is complete.
  20401. * This function is passed the current mesh.
  20402. * Returns the Mesh.
  20403. */
  20404. Mesh.prototype.registerAfterRender = function (func) {
  20405. this.onAfterRenderObservable.add(func);
  20406. return this;
  20407. };
  20408. /**
  20409. * Disposes a previously registered javascript function called after the rendering.
  20410. * This function is passed the current mesh.
  20411. * Return the Mesh.
  20412. */
  20413. Mesh.prototype.unregisterAfterRender = function (func) {
  20414. this.onAfterRenderObservable.removeCallback(func);
  20415. return this;
  20416. };
  20417. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20418. var scene = this.getScene();
  20419. this._batchCache.mustReturn = false;
  20420. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20421. this._batchCache.visibleInstances[subMeshId] = null;
  20422. if (this._visibleInstances) {
  20423. var currentRenderId = scene.getRenderId();
  20424. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20425. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20426. var selfRenderId = this._renderId;
  20427. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20428. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20429. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20430. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20431. }
  20432. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20433. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20434. this._batchCache.mustReturn = true;
  20435. return this._batchCache;
  20436. }
  20437. if (currentRenderId !== selfRenderId) {
  20438. this._batchCache.renderSelf[subMeshId] = false;
  20439. }
  20440. }
  20441. this._renderIdForInstances[subMeshId] = currentRenderId;
  20442. }
  20443. return this._batchCache;
  20444. };
  20445. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20446. var visibleInstances = batch.visibleInstances[subMesh._id];
  20447. var matricesCount = visibleInstances.length + 1;
  20448. var bufferSize = matricesCount * 16 * 4;
  20449. var currentInstancesBufferSize = this._instancesBufferSize;
  20450. var instancesBuffer = this._instancesBuffer;
  20451. while (this._instancesBufferSize < bufferSize) {
  20452. this._instancesBufferSize *= 2;
  20453. }
  20454. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20455. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20456. }
  20457. var offset = 0;
  20458. var instancesCount = 0;
  20459. var world = this.getWorldMatrix();
  20460. if (batch.renderSelf[subMesh._id]) {
  20461. world.copyToArray(this._instancesData, offset);
  20462. offset += 16;
  20463. instancesCount++;
  20464. }
  20465. if (visibleInstances) {
  20466. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20467. var instance = visibleInstances[instanceIndex];
  20468. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20469. offset += 16;
  20470. instancesCount++;
  20471. }
  20472. }
  20473. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20474. if (instancesBuffer) {
  20475. instancesBuffer.dispose();
  20476. }
  20477. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20478. this._instancesBuffer = instancesBuffer;
  20479. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20480. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20481. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20482. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20483. }
  20484. else {
  20485. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20486. }
  20487. this.geometry._bind(effect);
  20488. this._draw(subMesh, fillMode, instancesCount);
  20489. engine.unbindInstanceAttributes();
  20490. return this;
  20491. };
  20492. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20493. var scene = this.getScene();
  20494. var engine = scene.getEngine();
  20495. if (hardwareInstancedRendering) {
  20496. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20497. }
  20498. else {
  20499. if (batch.renderSelf[subMesh._id]) {
  20500. // Draw
  20501. if (onBeforeDraw) {
  20502. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20503. }
  20504. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20505. }
  20506. if (batch.visibleInstances[subMesh._id]) {
  20507. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20508. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20509. // World
  20510. var world = instance.getWorldMatrix();
  20511. if (onBeforeDraw) {
  20512. onBeforeDraw(true, world, effectiveMaterial);
  20513. }
  20514. // Draw
  20515. this._draw(subMesh, fillMode);
  20516. }
  20517. }
  20518. }
  20519. return this;
  20520. };
  20521. /**
  20522. * Triggers the draw call for the mesh.
  20523. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20524. * Returns the Mesh.
  20525. */
  20526. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20527. var scene = this.getScene();
  20528. // Managing instances
  20529. var batch = this._getInstancesRenderList(subMesh._id);
  20530. if (batch.mustReturn) {
  20531. return this;
  20532. }
  20533. // Checking geometry state
  20534. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20535. return this;
  20536. }
  20537. var callbackIndex;
  20538. this.onBeforeRenderObservable.notifyObservers(this);
  20539. var engine = scene.getEngine();
  20540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20541. // Material
  20542. var effectiveMaterial = subMesh.getMaterial();
  20543. if (!effectiveMaterial) {
  20544. return this;
  20545. }
  20546. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20547. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20548. return this;
  20549. }
  20550. }
  20551. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20552. return this;
  20553. }
  20554. // Alpha mode
  20555. if (enableAlphaMode) {
  20556. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20557. }
  20558. // Outline - step 1
  20559. var savedDepthWrite = engine.getDepthWrite();
  20560. if (this.renderOutline) {
  20561. engine.setDepthWrite(false);
  20562. scene.getOutlineRenderer().render(subMesh, batch);
  20563. engine.setDepthWrite(savedDepthWrite);
  20564. }
  20565. var effect;
  20566. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20567. effect = subMesh.effect;
  20568. }
  20569. else {
  20570. effect = effectiveMaterial.getEffect();
  20571. }
  20572. effectiveMaterial._preBind(effect);
  20573. // Bind
  20574. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20575. this._bind(subMesh, effect, fillMode);
  20576. var world = this.getWorldMatrix();
  20577. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20578. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20579. }
  20580. else {
  20581. effectiveMaterial.bind(world, this);
  20582. }
  20583. // Draw
  20584. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20585. // Unbind
  20586. effectiveMaterial.unbind();
  20587. // Outline - step 2
  20588. if (this.renderOutline && savedDepthWrite) {
  20589. engine.setDepthWrite(true);
  20590. engine.setColorWrite(false);
  20591. scene.getOutlineRenderer().render(subMesh, batch);
  20592. engine.setColorWrite(true);
  20593. }
  20594. // Overlay
  20595. if (this.renderOverlay) {
  20596. var currentMode = engine.getAlphaMode();
  20597. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20598. scene.getOutlineRenderer().render(subMesh, batch, true);
  20599. engine.setAlphaMode(currentMode);
  20600. }
  20601. this.onAfterRenderObservable.notifyObservers(this);
  20602. return this;
  20603. };
  20604. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20605. if (isInstance) {
  20606. effectiveMaterial.bindOnlyWorldMatrix(world);
  20607. }
  20608. return this;
  20609. };
  20610. /**
  20611. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20612. */
  20613. Mesh.prototype.getEmittedParticleSystems = function () {
  20614. var results = new Array();
  20615. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20616. var particleSystem = this.getScene().particleSystems[index];
  20617. if (particleSystem.emitter === this) {
  20618. results.push(particleSystem);
  20619. }
  20620. }
  20621. return results;
  20622. };
  20623. /**
  20624. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20625. */
  20626. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20627. var results = new Array();
  20628. var descendants = this.getDescendants();
  20629. descendants.push(this);
  20630. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20631. var particleSystem = this.getScene().particleSystems[index];
  20632. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20633. results.push(particleSystem);
  20634. }
  20635. }
  20636. return results;
  20637. };
  20638. Mesh.prototype._checkDelayState = function () {
  20639. var scene = this.getScene();
  20640. if (this._geometry) {
  20641. this._geometry.load(scene);
  20642. }
  20643. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20644. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20645. this._queueLoad(this, scene);
  20646. }
  20647. return this;
  20648. };
  20649. Mesh.prototype._queueLoad = function (mesh, scene) {
  20650. var _this = this;
  20651. scene._addPendingData(mesh);
  20652. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20653. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20654. if (data instanceof ArrayBuffer) {
  20655. _this._delayLoadingFunction(data, _this);
  20656. }
  20657. else {
  20658. _this._delayLoadingFunction(JSON.parse(data), _this);
  20659. }
  20660. _this.instances.forEach(function (instance) {
  20661. instance._syncSubMeshes();
  20662. });
  20663. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20664. scene._removePendingData(_this);
  20665. }, function () { }, scene.database, getBinaryData);
  20666. return this;
  20667. };
  20668. /**
  20669. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20670. */
  20671. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20672. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20673. return false;
  20674. }
  20675. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20676. return false;
  20677. }
  20678. this._checkDelayState();
  20679. return true;
  20680. };
  20681. /**
  20682. * Sets the mesh material by the material or multiMaterial `id` property.
  20683. * The material `id` is a string identifying the material or the multiMaterial.
  20684. * This method returns the Mesh.
  20685. */
  20686. Mesh.prototype.setMaterialByID = function (id) {
  20687. var materials = this.getScene().materials;
  20688. var index;
  20689. for (index = materials.length - 1; index > -1; index--) {
  20690. if (materials[index].id === id) {
  20691. this.material = materials[index];
  20692. return this;
  20693. }
  20694. }
  20695. // Multi
  20696. var multiMaterials = this.getScene().multiMaterials;
  20697. for (index = multiMaterials.length - 1; index > -1; index--) {
  20698. if (multiMaterials[index].id === id) {
  20699. this.material = multiMaterials[index];
  20700. return this;
  20701. }
  20702. }
  20703. return this;
  20704. };
  20705. /**
  20706. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20707. */
  20708. Mesh.prototype.getAnimatables = function () {
  20709. var results = [];
  20710. if (this.material) {
  20711. results.push(this.material);
  20712. }
  20713. if (this.skeleton) {
  20714. results.push(this.skeleton);
  20715. }
  20716. return results;
  20717. };
  20718. /**
  20719. * Modifies the mesh geometry according to the passed transformation matrix.
  20720. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20721. * The mesh normals are modified accordingly the same transformation.
  20722. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20723. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20724. * Returns the Mesh.
  20725. */
  20726. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20727. // Position
  20728. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20729. return this;
  20730. }
  20731. var submeshes = this.subMeshes.splice(0);
  20732. this._resetPointsArrayCache();
  20733. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20734. var temp = [];
  20735. var index;
  20736. for (index = 0; index < data.length; index += 3) {
  20737. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20738. }
  20739. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20740. // Normals
  20741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20742. return this;
  20743. }
  20744. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20745. temp = [];
  20746. for (index = 0; index < data.length; index += 3) {
  20747. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20748. }
  20749. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20750. // flip faces?
  20751. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20752. this.flipFaces();
  20753. }
  20754. // Restore submeshes
  20755. this.releaseSubMeshes();
  20756. this.subMeshes = submeshes;
  20757. return this;
  20758. };
  20759. /**
  20760. * Modifies the mesh geometry according to its own current World Matrix.
  20761. * The mesh World Matrix is then reset.
  20762. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20763. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20765. * Returns the Mesh.
  20766. */
  20767. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20768. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20769. this.scaling.copyFromFloats(1, 1, 1);
  20770. this.position.copyFromFloats(0, 0, 0);
  20771. this.rotation.copyFromFloats(0, 0, 0);
  20772. //only if quaternion is already set
  20773. if (this.rotationQuaternion) {
  20774. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20775. }
  20776. this._worldMatrix = BABYLON.Matrix.Identity();
  20777. return this;
  20778. };
  20779. Object.defineProperty(Mesh.prototype, "_positions", {
  20780. // Cache
  20781. get: function () {
  20782. if (this._geometry) {
  20783. return this._geometry._positions;
  20784. }
  20785. return null;
  20786. },
  20787. enumerable: true,
  20788. configurable: true
  20789. });
  20790. Mesh.prototype._resetPointsArrayCache = function () {
  20791. if (this._geometry) {
  20792. this._geometry._resetPointsArrayCache();
  20793. }
  20794. return this;
  20795. };
  20796. Mesh.prototype._generatePointsArray = function () {
  20797. if (this._geometry) {
  20798. return this._geometry._generatePointsArray();
  20799. }
  20800. return false;
  20801. };
  20802. /**
  20803. * Returns a new Mesh object generated from the current mesh properties.
  20804. * This method must not get confused with createInstance().
  20805. * The parameter `name` is a string, the name given to the new mesh.
  20806. * The optional parameter `newParent` can be any Node object (default `null`).
  20807. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20808. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  20809. */
  20810. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20811. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20812. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20813. };
  20814. /**
  20815. * Disposes the mesh.
  20816. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20817. */
  20818. Mesh.prototype.dispose = function (doNotRecurse) {
  20819. var _this = this;
  20820. this.morphTargetManager = undefined;
  20821. if (this._geometry) {
  20822. this._geometry.releaseForMesh(this, true);
  20823. }
  20824. // Sources
  20825. var meshes = this.getScene().meshes;
  20826. meshes.forEach(function (mesh) {
  20827. if (mesh._source && mesh._source === _this) {
  20828. mesh._source = null;
  20829. }
  20830. });
  20831. this._source = null;
  20832. // Instances
  20833. if (this._instancesBuffer) {
  20834. this._instancesBuffer.dispose();
  20835. this._instancesBuffer = null;
  20836. }
  20837. while (this.instances.length) {
  20838. this.instances[0].dispose();
  20839. }
  20840. // Highlight layers.
  20841. var highlightLayers = this.getScene().highlightLayers;
  20842. for (var i = 0; i < highlightLayers.length; i++) {
  20843. var highlightLayer = highlightLayers[i];
  20844. if (highlightLayer) {
  20845. highlightLayer.removeMesh(this);
  20846. highlightLayer.removeExcludedMesh(this);
  20847. }
  20848. }
  20849. _super.prototype.dispose.call(this, doNotRecurse);
  20850. };
  20851. /**
  20852. * Modifies the mesh geometry according to a displacement map.
  20853. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  20854. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20855. * This method returns nothing.
  20856. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20857. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20858. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  20859. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20860. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20861. *
  20862. * Returns the Mesh.
  20863. */
  20864. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20865. var _this = this;
  20866. var scene = this.getScene();
  20867. var onload = function (img) {
  20868. // Getting height map data
  20869. var canvas = document.createElement("canvas");
  20870. var context = canvas.getContext("2d");
  20871. var heightMapWidth = img.width;
  20872. var heightMapHeight = img.height;
  20873. canvas.width = heightMapWidth;
  20874. canvas.height = heightMapHeight;
  20875. context.drawImage(img, 0, 0);
  20876. // Create VertexData from map data
  20877. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20878. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20879. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20880. //execute success callback, if set
  20881. if (onSuccess) {
  20882. onSuccess(_this);
  20883. }
  20884. };
  20885. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20886. return this;
  20887. };
  20888. /**
  20889. * Modifies the mesh geometry according to a displacementMap buffer.
  20890. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  20891. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20892. * This method returns nothing.
  20893. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  20894. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20895. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20896. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20897. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20898. *
  20899. * Returns the Mesh.
  20900. */
  20901. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20902. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20903. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20904. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20905. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20906. return this;
  20907. }
  20908. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20909. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20910. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20911. var position = BABYLON.Vector3.Zero();
  20912. var normal = BABYLON.Vector3.Zero();
  20913. var uv = BABYLON.Vector2.Zero();
  20914. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20915. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20916. for (var index = 0; index < positions.length; index += 3) {
  20917. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20918. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20919. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20920. // Compute height
  20921. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20922. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20923. var pos = (u + v * heightMapWidth) * 4;
  20924. var r = buffer[pos] / 255.0;
  20925. var g = buffer[pos + 1] / 255.0;
  20926. var b = buffer[pos + 2] / 255.0;
  20927. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20928. normal.normalize();
  20929. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20930. position = position.add(normal);
  20931. position.toArray(positions, index);
  20932. }
  20933. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20934. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20935. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20936. return this;
  20937. };
  20938. /**
  20939. * Modify the mesh to get a flat shading rendering.
  20940. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20941. * This method returns the Mesh.
  20942. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20943. */
  20944. Mesh.prototype.convertToFlatShadedMesh = function () {
  20945. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20946. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20947. var kinds = this.getVerticesDataKinds();
  20948. var vbs = [];
  20949. var data = [];
  20950. var newdata = [];
  20951. var updatableNormals = false;
  20952. var kindIndex;
  20953. var kind;
  20954. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20955. kind = kinds[kindIndex];
  20956. var vertexBuffer = this.getVertexBuffer(kind);
  20957. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20958. updatableNormals = vertexBuffer.isUpdatable();
  20959. kinds.splice(kindIndex, 1);
  20960. kindIndex--;
  20961. continue;
  20962. }
  20963. vbs[kind] = vertexBuffer;
  20964. data[kind] = vbs[kind].getData();
  20965. newdata[kind] = [];
  20966. }
  20967. // Save previous submeshes
  20968. var previousSubmeshes = this.subMeshes.slice(0);
  20969. var indices = this.getIndices();
  20970. var totalIndices = this.getTotalIndices();
  20971. // Generating unique vertices per face
  20972. var index;
  20973. for (index = 0; index < totalIndices; index++) {
  20974. var vertexIndex = indices[index];
  20975. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20976. kind = kinds[kindIndex];
  20977. var stride = vbs[kind].getStrideSize();
  20978. for (var offset = 0; offset < stride; offset++) {
  20979. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20980. }
  20981. }
  20982. }
  20983. // Updating faces & normal
  20984. var normals = [];
  20985. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20986. for (index = 0; index < totalIndices; index += 3) {
  20987. indices[index] = index;
  20988. indices[index + 1] = index + 1;
  20989. indices[index + 2] = index + 2;
  20990. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20991. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20992. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20993. var p1p2 = p1.subtract(p2);
  20994. var p3p2 = p3.subtract(p2);
  20995. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20996. // Store same normals for every vertex
  20997. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20998. normals.push(normal.x);
  20999. normals.push(normal.y);
  21000. normals.push(normal.z);
  21001. }
  21002. }
  21003. this.setIndices(indices);
  21004. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21005. // Updating vertex buffers
  21006. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21007. kind = kinds[kindIndex];
  21008. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21009. }
  21010. // Updating submeshes
  21011. this.releaseSubMeshes();
  21012. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21013. var previousOne = previousSubmeshes[submeshIndex];
  21014. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21015. }
  21016. this.synchronizeInstances();
  21017. return this;
  21018. };
  21019. /**
  21020. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21021. * In other words, more vertices, no more indices and a single bigger VBO.
  21022. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21023. * Returns the Mesh.
  21024. */
  21025. Mesh.prototype.convertToUnIndexedMesh = function () {
  21026. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21027. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21028. var kinds = this.getVerticesDataKinds();
  21029. var vbs = [];
  21030. var data = [];
  21031. var newdata = [];
  21032. var updatableNormals = false;
  21033. var kindIndex;
  21034. var kind;
  21035. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21036. kind = kinds[kindIndex];
  21037. var vertexBuffer = this.getVertexBuffer(kind);
  21038. vbs[kind] = vertexBuffer;
  21039. data[kind] = vbs[kind].getData();
  21040. newdata[kind] = [];
  21041. }
  21042. // Save previous submeshes
  21043. var previousSubmeshes = this.subMeshes.slice(0);
  21044. var indices = this.getIndices();
  21045. var totalIndices = this.getTotalIndices();
  21046. // Generating unique vertices per face
  21047. var index;
  21048. for (index = 0; index < totalIndices; index++) {
  21049. var vertexIndex = indices[index];
  21050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21051. kind = kinds[kindIndex];
  21052. var stride = vbs[kind].getStrideSize();
  21053. for (var offset = 0; offset < stride; offset++) {
  21054. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21055. }
  21056. }
  21057. }
  21058. // Updating indices
  21059. for (index = 0; index < totalIndices; index += 3) {
  21060. indices[index] = index;
  21061. indices[index + 1] = index + 1;
  21062. indices[index + 2] = index + 2;
  21063. }
  21064. this.setIndices(indices);
  21065. // Updating vertex buffers
  21066. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21067. kind = kinds[kindIndex];
  21068. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21069. }
  21070. // Updating submeshes
  21071. this.releaseSubMeshes();
  21072. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21073. var previousOne = previousSubmeshes[submeshIndex];
  21074. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21075. }
  21076. this._unIndexed = true;
  21077. this.synchronizeInstances();
  21078. return this;
  21079. };
  21080. /**
  21081. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21082. * This method returns the Mesh.
  21083. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21084. */
  21085. Mesh.prototype.flipFaces = function (flipNormals) {
  21086. if (flipNormals === void 0) { flipNormals = false; }
  21087. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21088. var i;
  21089. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21090. for (i = 0; i < vertex_data.normals.length; i++) {
  21091. vertex_data.normals[i] *= -1;
  21092. }
  21093. }
  21094. var temp;
  21095. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21096. // reassign indices
  21097. temp = vertex_data.indices[i + 1];
  21098. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21099. vertex_data.indices[i + 2] = temp;
  21100. }
  21101. vertex_data.applyToMesh(this);
  21102. return this;
  21103. };
  21104. // Instances
  21105. /**
  21106. * Creates a new InstancedMesh object from the mesh model.
  21107. * An instance shares the same properties and the same material than its model.
  21108. * Only these properties of each instance can then be set individually :
  21109. * - position
  21110. * - rotation
  21111. * - rotationQuaternion
  21112. * - setPivotMatrix
  21113. * - scaling
  21114. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21115. * Warning : this method is not supported for Line mesh and LineSystem
  21116. */
  21117. Mesh.prototype.createInstance = function (name) {
  21118. return new BABYLON.InstancedMesh(name, this);
  21119. };
  21120. /**
  21121. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21122. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21123. * This method returns the Mesh.
  21124. */
  21125. Mesh.prototype.synchronizeInstances = function () {
  21126. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21127. var instance = this.instances[instanceIndex];
  21128. instance._syncSubMeshes();
  21129. }
  21130. return this;
  21131. };
  21132. /**
  21133. * Simplify the mesh according to the given array of settings.
  21134. * Function will return immediately and will simplify async. It returns the Mesh.
  21135. * @param settings a collection of simplification settings.
  21136. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21137. * @param type the type of simplification to run.
  21138. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21139. */
  21140. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21141. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21142. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21143. this.getScene().simplificationQueue.addTask({
  21144. settings: settings,
  21145. parallelProcessing: parallelProcessing,
  21146. mesh: this,
  21147. simplificationType: simplificationType,
  21148. successCallback: successCallback
  21149. });
  21150. return this;
  21151. };
  21152. /**
  21153. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21154. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21155. * This should be used together with the simplification to avoid disappearing triangles.
  21156. * Returns the Mesh.
  21157. * @param successCallback an optional success callback to be called after the optimization finished.
  21158. */
  21159. Mesh.prototype.optimizeIndices = function (successCallback) {
  21160. var _this = this;
  21161. var indices = this.getIndices();
  21162. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21163. var vectorPositions = [];
  21164. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21165. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21166. }
  21167. var dupes = [];
  21168. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21169. var realPos = vectorPositions.length - 1 - iteration;
  21170. var testedPosition = vectorPositions[realPos];
  21171. for (var j = 0; j < realPos; ++j) {
  21172. var againstPosition = vectorPositions[j];
  21173. if (testedPosition.equals(againstPosition)) {
  21174. dupes[realPos] = j;
  21175. break;
  21176. }
  21177. }
  21178. }, function () {
  21179. for (var i = 0; i < indices.length; ++i) {
  21180. indices[i] = dupes[indices[i]] || indices[i];
  21181. }
  21182. //indices are now reordered
  21183. var originalSubMeshes = _this.subMeshes.slice(0);
  21184. _this.setIndices(indices);
  21185. _this.subMeshes = originalSubMeshes;
  21186. if (successCallback) {
  21187. successCallback(_this);
  21188. }
  21189. });
  21190. return this;
  21191. };
  21192. Mesh.prototype.serialize = function (serializationObject) {
  21193. serializationObject.name = this.name;
  21194. serializationObject.id = this.id;
  21195. serializationObject.type = this.getClassName();
  21196. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21197. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21198. }
  21199. serializationObject.position = this.position.asArray();
  21200. if (this.rotationQuaternion) {
  21201. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21202. }
  21203. else if (this.rotation) {
  21204. serializationObject.rotation = this.rotation.asArray();
  21205. }
  21206. serializationObject.scaling = this.scaling.asArray();
  21207. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21208. serializationObject.isEnabled = this.isEnabled();
  21209. serializationObject.isVisible = this.isVisible;
  21210. serializationObject.infiniteDistance = this.infiniteDistance;
  21211. serializationObject.pickable = this.isPickable;
  21212. serializationObject.receiveShadows = this.receiveShadows;
  21213. serializationObject.billboardMode = this.billboardMode;
  21214. serializationObject.visibility = this.visibility;
  21215. serializationObject.checkCollisions = this.checkCollisions;
  21216. serializationObject.isBlocker = this.isBlocker;
  21217. // Parent
  21218. if (this.parent) {
  21219. serializationObject.parentId = this.parent.id;
  21220. }
  21221. // Geometry
  21222. var geometry = this._geometry;
  21223. if (geometry) {
  21224. var geometryId = geometry.id;
  21225. serializationObject.geometryId = geometryId;
  21226. // SubMeshes
  21227. serializationObject.subMeshes = [];
  21228. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21229. var subMesh = this.subMeshes[subIndex];
  21230. serializationObject.subMeshes.push({
  21231. materialIndex: subMesh.materialIndex,
  21232. verticesStart: subMesh.verticesStart,
  21233. verticesCount: subMesh.verticesCount,
  21234. indexStart: subMesh.indexStart,
  21235. indexCount: subMesh.indexCount
  21236. });
  21237. }
  21238. }
  21239. // Material
  21240. if (this.material) {
  21241. serializationObject.materialId = this.material.id;
  21242. }
  21243. else {
  21244. this.material = null;
  21245. }
  21246. // Morph targets
  21247. if (this.morphTargetManager) {
  21248. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21249. }
  21250. // Skeleton
  21251. if (this.skeleton) {
  21252. serializationObject.skeletonId = this.skeleton.id;
  21253. }
  21254. // Physics
  21255. //TODO implement correct serialization for physics impostors.
  21256. if (this.getPhysicsImpostor()) {
  21257. var impostor = this.getPhysicsImpostor();
  21258. serializationObject.physicsMass = impostor.getParam("mass");
  21259. serializationObject.physicsFriction = impostor.getParam("friction");
  21260. serializationObject.physicsRestitution = impostor.getParam("mass");
  21261. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21262. }
  21263. // Metadata
  21264. if (this.metadata) {
  21265. serializationObject.metadata = this.metadata;
  21266. }
  21267. // Instances
  21268. serializationObject.instances = [];
  21269. for (var index = 0; index < this.instances.length; index++) {
  21270. var instance = this.instances[index];
  21271. var serializationInstance = {
  21272. name: instance.name,
  21273. position: instance.position.asArray(),
  21274. scaling: instance.scaling.asArray()
  21275. };
  21276. if (instance.rotationQuaternion) {
  21277. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21278. }
  21279. else if (instance.rotation) {
  21280. serializationInstance.rotation = instance.rotation.asArray();
  21281. }
  21282. serializationObject.instances.push(serializationInstance);
  21283. // Animations
  21284. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21285. serializationInstance.ranges = instance.serializeAnimationRanges();
  21286. }
  21287. //
  21288. // Animations
  21289. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21290. serializationObject.ranges = this.serializeAnimationRanges();
  21291. // Layer mask
  21292. serializationObject.layerMask = this.layerMask;
  21293. // Alpha
  21294. serializationObject.alphaIndex = this.alphaIndex;
  21295. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21296. // Overlay
  21297. serializationObject.overlayAlpha = this.overlayAlpha;
  21298. serializationObject.overlayColor = this.overlayColor.asArray();
  21299. serializationObject.renderOverlay = this.renderOverlay;
  21300. // Fog
  21301. serializationObject.applyFog = this.applyFog;
  21302. // Action Manager
  21303. if (this.actionManager) {
  21304. serializationObject.actions = this.actionManager.serialize(this.name);
  21305. }
  21306. };
  21307. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21308. if (!this.geometry) {
  21309. return;
  21310. }
  21311. this._markSubMeshesAsAttributesDirty();
  21312. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21313. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21314. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21315. this.morphTargetManager = undefined;
  21316. return;
  21317. }
  21318. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21319. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21320. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21321. if (morphTarget.hasNormals) {
  21322. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21323. }
  21324. if (morphTarget.hasTangents) {
  21325. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21326. }
  21327. }
  21328. }
  21329. else {
  21330. var index = 0;
  21331. // Positions
  21332. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21333. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21334. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21335. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21336. }
  21337. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21338. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21339. }
  21340. index++;
  21341. }
  21342. }
  21343. };
  21344. // Statics
  21345. /**
  21346. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21347. * The parameter `parsedMesh` is the mesh to be copied.
  21348. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21349. */
  21350. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21351. var mesh;
  21352. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21353. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21354. }
  21355. else {
  21356. mesh = new Mesh(parsedMesh.name, scene);
  21357. }
  21358. mesh.id = parsedMesh.id;
  21359. if (BABYLON.Tags) {
  21360. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21361. }
  21362. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21363. if (parsedMesh.metadata !== undefined) {
  21364. mesh.metadata = parsedMesh.metadata;
  21365. }
  21366. if (parsedMesh.rotationQuaternion) {
  21367. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21368. }
  21369. else if (parsedMesh.rotation) {
  21370. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21371. }
  21372. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21373. if (parsedMesh.localMatrix) {
  21374. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21375. }
  21376. else if (parsedMesh.pivotMatrix) {
  21377. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21378. }
  21379. mesh.setEnabled(parsedMesh.isEnabled);
  21380. mesh.isVisible = parsedMesh.isVisible;
  21381. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21382. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21383. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21384. if (parsedMesh.applyFog !== undefined) {
  21385. mesh.applyFog = parsedMesh.applyFog;
  21386. }
  21387. if (parsedMesh.pickable !== undefined) {
  21388. mesh.isPickable = parsedMesh.pickable;
  21389. }
  21390. if (parsedMesh.alphaIndex !== undefined) {
  21391. mesh.alphaIndex = parsedMesh.alphaIndex;
  21392. }
  21393. mesh.receiveShadows = parsedMesh.receiveShadows;
  21394. mesh.billboardMode = parsedMesh.billboardMode;
  21395. if (parsedMesh.visibility !== undefined) {
  21396. mesh.visibility = parsedMesh.visibility;
  21397. }
  21398. mesh.checkCollisions = parsedMesh.checkCollisions;
  21399. if (parsedMesh.isBlocker !== undefined) {
  21400. mesh.isBlocker = parsedMesh.isBlocker;
  21401. }
  21402. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21403. // freezeWorldMatrix
  21404. if (parsedMesh.freezeWorldMatrix) {
  21405. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21406. }
  21407. // Parent
  21408. if (parsedMesh.parentId) {
  21409. mesh._waitingParentId = parsedMesh.parentId;
  21410. }
  21411. // Actions
  21412. if (parsedMesh.actions !== undefined) {
  21413. mesh._waitingActions = parsedMesh.actions;
  21414. }
  21415. // Overlay
  21416. if (parsedMesh.overlayAlpha !== undefined) {
  21417. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21418. }
  21419. if (parsedMesh.overlayColor !== undefined) {
  21420. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21421. }
  21422. if (parsedMesh.renderOverlay !== undefined) {
  21423. mesh.renderOverlay = parsedMesh.renderOverlay;
  21424. }
  21425. // Geometry
  21426. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21427. if (parsedMesh.delayLoadingFile) {
  21428. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21429. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21430. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21431. if (parsedMesh._binaryInfo) {
  21432. mesh._binaryInfo = parsedMesh._binaryInfo;
  21433. }
  21434. mesh._delayInfo = [];
  21435. if (parsedMesh.hasUVs) {
  21436. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21437. }
  21438. if (parsedMesh.hasUVs2) {
  21439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21440. }
  21441. if (parsedMesh.hasUVs3) {
  21442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21443. }
  21444. if (parsedMesh.hasUVs4) {
  21445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21446. }
  21447. if (parsedMesh.hasUVs5) {
  21448. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21449. }
  21450. if (parsedMesh.hasUVs6) {
  21451. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21452. }
  21453. if (parsedMesh.hasColors) {
  21454. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21455. }
  21456. if (parsedMesh.hasMatricesIndices) {
  21457. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21458. }
  21459. if (parsedMesh.hasMatricesWeights) {
  21460. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21461. }
  21462. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21463. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21464. mesh._checkDelayState();
  21465. }
  21466. }
  21467. else {
  21468. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21469. }
  21470. // Material
  21471. if (parsedMesh.materialId) {
  21472. mesh.setMaterialByID(parsedMesh.materialId);
  21473. }
  21474. else {
  21475. mesh.material = null;
  21476. }
  21477. // Morph targets
  21478. if (parsedMesh.morphTargetManagerId > -1) {
  21479. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21480. }
  21481. // Skeleton
  21482. if (parsedMesh.skeletonId > -1) {
  21483. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21484. if (parsedMesh.numBoneInfluencers) {
  21485. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21486. }
  21487. }
  21488. // Animations
  21489. if (parsedMesh.animations) {
  21490. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21491. var parsedAnimation = parsedMesh.animations[animationIndex];
  21492. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21493. }
  21494. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21495. }
  21496. if (parsedMesh.autoAnimate) {
  21497. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21498. }
  21499. // Layer Mask
  21500. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21501. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21502. }
  21503. else {
  21504. mesh.layerMask = 0x0FFFFFFF;
  21505. }
  21506. // Physics
  21507. if (parsedMesh.physicsImpostor) {
  21508. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21509. mass: parsedMesh.physicsMass,
  21510. friction: parsedMesh.physicsFriction,
  21511. restitution: parsedMesh.physicsRestitution
  21512. }, scene);
  21513. }
  21514. // Instances
  21515. if (parsedMesh.instances) {
  21516. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21517. var parsedInstance = parsedMesh.instances[index];
  21518. var instance = mesh.createInstance(parsedInstance.name);
  21519. if (BABYLON.Tags) {
  21520. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21521. }
  21522. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21523. if (parsedInstance.parentId) {
  21524. instance._waitingParentId = parsedInstance.parentId;
  21525. }
  21526. if (parsedInstance.rotationQuaternion) {
  21527. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21528. }
  21529. else if (parsedInstance.rotation) {
  21530. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21531. }
  21532. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21533. instance.checkCollisions = mesh.checkCollisions;
  21534. if (parsedMesh.animations) {
  21535. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21536. parsedAnimation = parsedMesh.animations[animationIndex];
  21537. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21538. }
  21539. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21540. }
  21541. }
  21542. }
  21543. return mesh;
  21544. };
  21545. /**
  21546. * Creates a ribbon mesh.
  21547. * Please consider using the same method from the MeshBuilder class instead.
  21548. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21549. *
  21550. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21551. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21552. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21553. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21554. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  21555. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  21556. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  21557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21558. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21560. */
  21561. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21562. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21563. pathArray: pathArray,
  21564. closeArray: closeArray,
  21565. closePath: closePath,
  21566. offset: offset,
  21567. updatable: updatable,
  21568. sideOrientation: sideOrientation,
  21569. instance: instance
  21570. }, scene);
  21571. };
  21572. /**
  21573. * Creates a plane polygonal mesh. By default, this is a disc.
  21574. * Please consider using the same method from the MeshBuilder class instead.
  21575. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21576. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  21577. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21578. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21580. */
  21581. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21582. var options = {
  21583. radius: radius,
  21584. tessellation: tessellation,
  21585. sideOrientation: sideOrientation,
  21586. updatable: updatable
  21587. };
  21588. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21589. };
  21590. /**
  21591. * Creates a box mesh.
  21592. * Please consider using the same method from the MeshBuilder class instead.
  21593. * The parameter `size` sets the size (float) of each box side (default 1).
  21594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21597. */
  21598. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21599. var options = {
  21600. size: size,
  21601. sideOrientation: sideOrientation,
  21602. updatable: updatable
  21603. };
  21604. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21605. };
  21606. /**
  21607. * Creates a sphere mesh.
  21608. * Please consider using the same method from the MeshBuilder class instead.
  21609. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21610. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21613. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21614. */
  21615. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21616. var options = {
  21617. segments: segments,
  21618. diameterX: diameter,
  21619. diameterY: diameter,
  21620. diameterZ: diameter,
  21621. sideOrientation: sideOrientation,
  21622. updatable: updatable
  21623. };
  21624. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21625. };
  21626. /**
  21627. * Creates a cylinder or a cone mesh.
  21628. * Please consider using the same method from the MeshBuilder class instead.
  21629. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21630. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21631. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  21632. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21633. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21637. */
  21638. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21639. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21640. if (scene !== undefined) {
  21641. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21642. updatable = scene;
  21643. }
  21644. scene = subdivisions;
  21645. subdivisions = 1;
  21646. }
  21647. var options = {
  21648. height: height,
  21649. diameterTop: diameterTop,
  21650. diameterBottom: diameterBottom,
  21651. tessellation: tessellation,
  21652. subdivisions: subdivisions,
  21653. sideOrientation: sideOrientation,
  21654. updatable: updatable
  21655. };
  21656. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21657. };
  21658. // Torus (Code from SharpDX.org)
  21659. /**
  21660. * Creates a torus mesh.
  21661. * Please consider using the same method from the MeshBuilder class instead.
  21662. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21663. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21664. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21668. */
  21669. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21670. var options = {
  21671. diameter: diameter,
  21672. thickness: thickness,
  21673. tessellation: tessellation,
  21674. sideOrientation: sideOrientation,
  21675. updatable: updatable
  21676. };
  21677. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21678. };
  21679. /**
  21680. * Creates a torus knot mesh.
  21681. * Please consider using the same method from the MeshBuilder class instead.
  21682. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21683. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21684. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21685. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21689. */
  21690. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21691. var options = {
  21692. radius: radius,
  21693. tube: tube,
  21694. radialSegments: radialSegments,
  21695. tubularSegments: tubularSegments,
  21696. p: p,
  21697. q: q,
  21698. sideOrientation: sideOrientation,
  21699. updatable: updatable
  21700. };
  21701. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21702. };
  21703. /**
  21704. * Creates a line mesh.
  21705. * Please consider using the same method from the MeshBuilder class instead.
  21706. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  21707. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21708. * The parameter `points` is an array successive Vector3.
  21709. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  21710. * When updating an instance, remember that only point positions can change, not the number of points.
  21711. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21712. */
  21713. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21714. var options = {
  21715. points: points,
  21716. updatable: updatable,
  21717. instance: instance
  21718. };
  21719. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21720. };
  21721. /**
  21722. * Creates a dashed line mesh.
  21723. * Please consider using the same method from the MeshBuilder class instead.
  21724. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  21725. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21726. * The parameter `points` is an array successive Vector3.
  21727. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21728. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21729. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21730. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  21731. * When updating an instance, remember that only point positions can change, not the number of points.
  21732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21733. */
  21734. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21735. var options = {
  21736. points: points,
  21737. dashSize: dashSize,
  21738. gapSize: gapSize,
  21739. dashNb: dashNb,
  21740. updatable: updatable,
  21741. instance: instance
  21742. };
  21743. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21744. };
  21745. /**
  21746. * Creates a polygon mesh.
  21747. * Please consider using the same method from the MeshBuilder class instead.
  21748. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21749. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  21750. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21751. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21752. * Remember you can only change the shape positions, not their number when updating a polygon.
  21753. */
  21754. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21755. var options = {
  21756. shape: shape,
  21757. holes: holes,
  21758. updatable: updatable,
  21759. sideOrientation: sideOrientation
  21760. };
  21761. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21762. };
  21763. /**
  21764. * Creates an extruded polygon mesh, with depth in the Y direction.
  21765. * Please consider using the same method from the MeshBuilder class instead.
  21766. */
  21767. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21768. var options = {
  21769. shape: shape,
  21770. holes: holes,
  21771. depth: depth,
  21772. updatable: updatable,
  21773. sideOrientation: sideOrientation
  21774. };
  21775. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21776. };
  21777. /**
  21778. * Creates an extruded shape mesh.
  21779. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21780. * Please consider using the same method from the MeshBuilder class instead.
  21781. *
  21782. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21783. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  21784. * extruded along the Z axis.
  21785. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21786. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  21787. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21788. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21789. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  21790. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21791. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21792. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21793. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21794. */
  21795. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21796. var options = {
  21797. shape: shape,
  21798. path: path,
  21799. scale: scale,
  21800. rotation: rotation,
  21801. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21802. sideOrientation: sideOrientation,
  21803. instance: instance,
  21804. updatable: updatable
  21805. };
  21806. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21807. };
  21808. /**
  21809. * Creates an custom extruded shape mesh.
  21810. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21811. * Please consider using the same method from the MeshBuilder class instead.
  21812. *
  21813. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21814. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  21815. * extruded along the Z axis.
  21816. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21817. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  21818. * and the distance of this point from the begining of the path :
  21819. * ```javascript
  21820. * var rotationFunction = function(i, distance) {
  21821. * // do things
  21822. * return rotationValue; }
  21823. * ```
  21824. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21825. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  21826. * and the distance of this point from the begining of the path :
  21827. * ```javascript
  21828. * var scaleFunction = function(i, distance) {
  21829. * // do things
  21830. * return scaleValue;}
  21831. * ```
  21832. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21833. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21834. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21835. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21836. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  21837. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21841. */
  21842. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21843. var options = {
  21844. shape: shape,
  21845. path: path,
  21846. scaleFunction: scaleFunction,
  21847. rotationFunction: rotationFunction,
  21848. ribbonCloseArray: ribbonCloseArray,
  21849. ribbonClosePath: ribbonClosePath,
  21850. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21851. sideOrientation: sideOrientation,
  21852. instance: instance,
  21853. updatable: updatable
  21854. };
  21855. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21856. };
  21857. /**
  21858. * Creates lathe mesh.
  21859. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21860. * Please consider using the same method from the MeshBuilder class instead.
  21861. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  21862. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21863. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21864. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21865. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21866. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21867. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21868. */
  21869. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21870. var options = {
  21871. shape: shape,
  21872. radius: radius,
  21873. tessellation: tessellation,
  21874. sideOrientation: sideOrientation,
  21875. updatable: updatable
  21876. };
  21877. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21878. };
  21879. /**
  21880. * Creates a plane mesh.
  21881. * Please consider using the same method from the MeshBuilder class instead.
  21882. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21883. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21884. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21886. */
  21887. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21888. var options = {
  21889. size: size,
  21890. width: size,
  21891. height: size,
  21892. sideOrientation: sideOrientation,
  21893. updatable: updatable
  21894. };
  21895. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21896. };
  21897. /**
  21898. * Creates a ground mesh.
  21899. * Please consider using the same method from the MeshBuilder class instead.
  21900. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21901. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21903. */
  21904. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21905. var options = {
  21906. width: width,
  21907. height: height,
  21908. subdivisions: subdivisions,
  21909. updatable: updatable
  21910. };
  21911. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21912. };
  21913. /**
  21914. * Creates a tiled ground mesh.
  21915. * Please consider using the same method from the MeshBuilder class instead.
  21916. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21917. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21918. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21919. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21920. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21921. * numbers of subdivisions on the ground width and height of each tile.
  21922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21923. */
  21924. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21925. var options = {
  21926. xmin: xmin,
  21927. zmin: zmin,
  21928. xmax: xmax,
  21929. zmax: zmax,
  21930. subdivisions: subdivisions,
  21931. precision: precision,
  21932. updatable: updatable
  21933. };
  21934. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21935. };
  21936. /**
  21937. * Creates a ground mesh from a height map.
  21938. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21939. * Please consider using the same method from the MeshBuilder class instead.
  21940. * The parameter `url` sets the URL of the height map image resource.
  21941. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21942. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21943. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21944. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21945. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  21946. * This function is passed the newly built mesh :
  21947. * ```javascript
  21948. * function(mesh) { // do things
  21949. * return; }
  21950. * ```
  21951. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21952. */
  21953. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21954. var options = {
  21955. width: width,
  21956. height: height,
  21957. subdivisions: subdivisions,
  21958. minHeight: minHeight,
  21959. maxHeight: maxHeight,
  21960. updatable: updatable,
  21961. onReady: onReady
  21962. };
  21963. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21964. };
  21965. /**
  21966. * Creates a tube mesh.
  21967. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21968. * Please consider using the same method from the MeshBuilder class instead.
  21969. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21970. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21971. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21972. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21973. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  21974. * It must return a radius value (positive float) :
  21975. * ```javascript
  21976. * var radiusFunction = function(i, distance) {
  21977. * // do things
  21978. * return radius; }
  21979. * ```
  21980. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21981. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  21982. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21983. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21985. */
  21986. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21987. var options = {
  21988. path: path,
  21989. radius: radius,
  21990. tessellation: tessellation,
  21991. radiusFunction: radiusFunction,
  21992. arc: 1,
  21993. cap: cap,
  21994. updatable: updatable,
  21995. sideOrientation: sideOrientation,
  21996. instance: instance
  21997. };
  21998. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21999. };
  22000. /**
  22001. * Creates a polyhedron mesh.
  22002. * Please consider using the same method from the MeshBuilder class instead.
  22003. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  22004. * to choose the wanted type.
  22005. * The parameter `size` (positive float, default 1) sets the polygon size.
  22006. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22007. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  22008. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  22009. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  22010. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22011. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  22012. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22013. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22014. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22015. */
  22016. Mesh.CreatePolyhedron = function (name, options, scene) {
  22017. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22018. };
  22019. /**
  22020. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22021. * Please consider using the same method from the MeshBuilder class instead.
  22022. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22023. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  22024. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22025. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  22026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22029. */
  22030. Mesh.CreateIcoSphere = function (name, options, scene) {
  22031. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22032. };
  22033. /**
  22034. * Creates a decal mesh.
  22035. * Please consider using the same method from the MeshBuilder class instead.
  22036. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  22037. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22038. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22039. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22040. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22041. */
  22042. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22043. var options = {
  22044. position: position,
  22045. normal: normal,
  22046. size: size,
  22047. angle: angle
  22048. };
  22049. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22050. };
  22051. // Skeletons
  22052. /**
  22053. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22054. */
  22055. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22056. var source;
  22057. if (!this._sourcePositions) {
  22058. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22059. this._sourcePositions = new Float32Array(source);
  22060. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22061. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22062. }
  22063. }
  22064. return this._sourcePositions;
  22065. };
  22066. /**
  22067. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22068. */
  22069. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22070. var source;
  22071. if (!this._sourceNormals) {
  22072. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22073. this._sourceNormals = new Float32Array(source);
  22074. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22075. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22076. }
  22077. }
  22078. return this._sourceNormals;
  22079. };
  22080. /**
  22081. * Updates the vertex buffer by applying transformation from the bones.
  22082. * Returns the Mesh.
  22083. *
  22084. * @param {skeleton} skeleton to apply
  22085. */
  22086. Mesh.prototype.applySkeleton = function (skeleton) {
  22087. if (!this.geometry) {
  22088. return this;
  22089. }
  22090. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22091. return this;
  22092. }
  22093. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22095. return this;
  22096. }
  22097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22098. return this;
  22099. }
  22100. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22101. return this;
  22102. }
  22103. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22104. return this;
  22105. }
  22106. if (!this._sourcePositions) {
  22107. var submeshes = this.subMeshes.slice();
  22108. this.setPositionsForCPUSkinning();
  22109. this.subMeshes = submeshes;
  22110. }
  22111. if (!this._sourceNormals) {
  22112. this.setNormalsForCPUSkinning();
  22113. }
  22114. // positionsData checks for not being Float32Array will only pass at most once
  22115. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22116. if (!(positionsData instanceof Float32Array)) {
  22117. positionsData = new Float32Array(positionsData);
  22118. }
  22119. // normalsData checks for not being Float32Array will only pass at most once
  22120. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22121. if (!(normalsData instanceof Float32Array)) {
  22122. normalsData = new Float32Array(normalsData);
  22123. }
  22124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22126. var needExtras = this.numBoneInfluencers > 4;
  22127. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22128. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22129. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22130. var tempVector3 = BABYLON.Vector3.Zero();
  22131. var finalMatrix = new BABYLON.Matrix();
  22132. var tempMatrix = new BABYLON.Matrix();
  22133. var matWeightIdx = 0;
  22134. var inf;
  22135. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22136. var weight;
  22137. for (inf = 0; inf < 4; inf++) {
  22138. weight = matricesWeightsData[matWeightIdx + inf];
  22139. if (weight > 0) {
  22140. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22141. finalMatrix.addToSelf(tempMatrix);
  22142. }
  22143. else
  22144. break;
  22145. }
  22146. if (needExtras) {
  22147. for (inf = 0; inf < 4; inf++) {
  22148. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22149. if (weight > 0) {
  22150. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22151. finalMatrix.addToSelf(tempMatrix);
  22152. }
  22153. else
  22154. break;
  22155. }
  22156. }
  22157. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22158. tempVector3.toArray(positionsData, index);
  22159. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22160. tempVector3.toArray(normalsData, index);
  22161. finalMatrix.reset();
  22162. }
  22163. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22164. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22165. return this;
  22166. };
  22167. // Tools
  22168. /**
  22169. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22170. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22171. */
  22172. Mesh.MinMax = function (meshes) {
  22173. var minVector = null;
  22174. var maxVector = null;
  22175. meshes.forEach(function (mesh, index, array) {
  22176. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22177. if (!minVector) {
  22178. minVector = boundingBox.minimumWorld;
  22179. maxVector = boundingBox.maximumWorld;
  22180. }
  22181. else {
  22182. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22183. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22184. }
  22185. });
  22186. return {
  22187. min: minVector,
  22188. max: maxVector
  22189. };
  22190. };
  22191. /**
  22192. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22193. */
  22194. Mesh.Center = function (meshesOrMinMaxVector) {
  22195. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22196. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22197. };
  22198. /**
  22199. * Merge the array of meshes into a single mesh for performance reasons.
  22200. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22201. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22202. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22203. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22204. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22205. */
  22206. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22207. if (disposeSource === void 0) { disposeSource = true; }
  22208. var index;
  22209. if (!allow32BitsIndices) {
  22210. var totalVertices = 0;
  22211. // Counting vertices
  22212. for (index = 0; index < meshes.length; index++) {
  22213. if (meshes[index]) {
  22214. totalVertices += meshes[index].getTotalVertices();
  22215. if (totalVertices > 65536) {
  22216. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22217. return null;
  22218. }
  22219. }
  22220. }
  22221. }
  22222. // Merge
  22223. var vertexData;
  22224. var otherVertexData;
  22225. var indiceArray = new Array();
  22226. var source;
  22227. for (index = 0; index < meshes.length; index++) {
  22228. if (meshes[index]) {
  22229. meshes[index].computeWorldMatrix(true);
  22230. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22231. otherVertexData.transform(meshes[index].getWorldMatrix());
  22232. if (vertexData) {
  22233. vertexData.merge(otherVertexData);
  22234. }
  22235. else {
  22236. vertexData = otherVertexData;
  22237. source = meshes[index];
  22238. }
  22239. if (subdivideWithSubMeshes) {
  22240. indiceArray.push(meshes[index].getTotalIndices());
  22241. }
  22242. }
  22243. }
  22244. if (!meshSubclass) {
  22245. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22246. }
  22247. vertexData.applyToMesh(meshSubclass);
  22248. // Setting properties
  22249. meshSubclass.material = source.material;
  22250. meshSubclass.checkCollisions = source.checkCollisions;
  22251. // Cleaning
  22252. if (disposeSource) {
  22253. for (index = 0; index < meshes.length; index++) {
  22254. if (meshes[index]) {
  22255. meshes[index].dispose();
  22256. }
  22257. }
  22258. }
  22259. // Subdivide
  22260. if (subdivideWithSubMeshes) {
  22261. //-- Suppresions du submesh global
  22262. meshSubclass.releaseSubMeshes();
  22263. index = 0;
  22264. var offset = 0;
  22265. //-- aplique la subdivision en fonction du tableau d'indices
  22266. while (index < indiceArray.length) {
  22267. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22268. offset += indiceArray[index];
  22269. index++;
  22270. }
  22271. }
  22272. return meshSubclass;
  22273. };
  22274. return Mesh;
  22275. }(BABYLON.AbstractMesh));
  22276. // Consts
  22277. Mesh._FRONTSIDE = 0;
  22278. Mesh._BACKSIDE = 1;
  22279. Mesh._DOUBLESIDE = 2;
  22280. Mesh._DEFAULTSIDE = 0;
  22281. Mesh._NO_CAP = 0;
  22282. Mesh._CAP_START = 1;
  22283. Mesh._CAP_END = 2;
  22284. Mesh._CAP_ALL = 3;
  22285. BABYLON.Mesh = Mesh;
  22286. })(BABYLON || (BABYLON = {}));
  22287. //# sourceMappingURL=babylon.mesh.js.map
  22288. var BABYLON;
  22289. (function (BABYLON) {
  22290. var BaseSubMesh = (function () {
  22291. function BaseSubMesh() {
  22292. }
  22293. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  22294. get: function () {
  22295. return this._materialEffect;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  22301. if (this._materialEffect === effect) {
  22302. return;
  22303. }
  22304. this._materialDefines = defines;
  22305. this._materialEffect = effect;
  22306. };
  22307. return BaseSubMesh;
  22308. }());
  22309. BABYLON.BaseSubMesh = BaseSubMesh;
  22310. var SubMesh = (function (_super) {
  22311. __extends(SubMesh, _super);
  22312. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22313. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22314. var _this = _super.call(this) || this;
  22315. _this.materialIndex = materialIndex;
  22316. _this.verticesStart = verticesStart;
  22317. _this.verticesCount = verticesCount;
  22318. _this.indexStart = indexStart;
  22319. _this.indexCount = indexCount;
  22320. _this._renderId = 0;
  22321. _this._mesh = mesh;
  22322. _this._renderingMesh = renderingMesh || mesh;
  22323. mesh.subMeshes.push(_this);
  22324. _this._trianglePlanes = [];
  22325. _this._id = mesh.subMeshes.length - 1;
  22326. if (createBoundingBox) {
  22327. _this.refreshBoundingInfo();
  22328. mesh.computeWorldMatrix(true);
  22329. }
  22330. return _this;
  22331. }
  22332. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22333. get: function () {
  22334. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22335. },
  22336. enumerable: true,
  22337. configurable: true
  22338. });
  22339. /**
  22340. * Returns the submesh BoudingInfo object.
  22341. */
  22342. SubMesh.prototype.getBoundingInfo = function () {
  22343. if (this.IsGlobal) {
  22344. return this._mesh.getBoundingInfo();
  22345. }
  22346. return this._boundingInfo;
  22347. };
  22348. /**
  22349. * Sets the submesh BoundingInfo.
  22350. * Return the SubMesh.
  22351. */
  22352. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22353. this._boundingInfo = boundingInfo;
  22354. return this;
  22355. };
  22356. /**
  22357. * Returns the mesh of the current submesh.
  22358. */
  22359. SubMesh.prototype.getMesh = function () {
  22360. return this._mesh;
  22361. };
  22362. /**
  22363. * Returns the rendering mesh of the submesh.
  22364. */
  22365. SubMesh.prototype.getRenderingMesh = function () {
  22366. return this._renderingMesh;
  22367. };
  22368. /**
  22369. * Returns the submesh material.
  22370. */
  22371. SubMesh.prototype.getMaterial = function () {
  22372. var rootMaterial = this._renderingMesh.material;
  22373. if (rootMaterial && rootMaterial.getSubMaterial) {
  22374. var multiMaterial = rootMaterial;
  22375. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22376. if (this._currentMaterial !== effectiveMaterial) {
  22377. this._currentMaterial = effectiveMaterial;
  22378. if (this._materialDefines) {
  22379. this._materialDefines.markAllAsDirty();
  22380. }
  22381. }
  22382. return effectiveMaterial;
  22383. }
  22384. if (!rootMaterial) {
  22385. return this._mesh.getScene().defaultMaterial;
  22386. }
  22387. return rootMaterial;
  22388. };
  22389. // Methods
  22390. /**
  22391. * Sets a new updated BoundingInfo object to the submesh.
  22392. * Returns the SubMesh.
  22393. */
  22394. SubMesh.prototype.refreshBoundingInfo = function () {
  22395. this._lastColliderWorldVertices = null;
  22396. if (this.IsGlobal) {
  22397. return;
  22398. }
  22399. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22400. if (!data) {
  22401. this._boundingInfo = this._mesh._boundingInfo;
  22402. return;
  22403. }
  22404. var indices = this._renderingMesh.getIndices();
  22405. var extend;
  22406. //is this the only submesh?
  22407. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22408. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22409. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22410. }
  22411. else {
  22412. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22413. }
  22414. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22415. return this;
  22416. };
  22417. SubMesh.prototype._checkCollision = function (collider) {
  22418. return this.getBoundingInfo()._checkCollision(collider);
  22419. };
  22420. /**
  22421. * Updates the submesh BoundingInfo.
  22422. * Returns the Submesh.
  22423. */
  22424. SubMesh.prototype.updateBoundingInfo = function (world) {
  22425. if (!this.getBoundingInfo()) {
  22426. this.refreshBoundingInfo();
  22427. }
  22428. this.getBoundingInfo().update(world);
  22429. return this;
  22430. };
  22431. /**
  22432. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22433. * Boolean returned.
  22434. */
  22435. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22436. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22437. };
  22438. /**
  22439. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22440. * Boolean returned.
  22441. */
  22442. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22443. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22444. };
  22445. /**
  22446. * Renders the submesh.
  22447. * Returns it.
  22448. */
  22449. SubMesh.prototype.render = function (enableAlphaMode) {
  22450. this._renderingMesh.render(this, enableAlphaMode);
  22451. return this;
  22452. };
  22453. /**
  22454. * Returns a new Index Buffer.
  22455. * Type returned : WebGLBuffer.
  22456. */
  22457. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22458. if (!this._linesIndexBuffer) {
  22459. var linesIndices = [];
  22460. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22461. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22462. }
  22463. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22464. this.linesIndexCount = linesIndices.length;
  22465. }
  22466. return this._linesIndexBuffer;
  22467. };
  22468. /**
  22469. * True is the passed Ray intersects the submesh bounding box.
  22470. * Boolean returned.
  22471. */
  22472. SubMesh.prototype.canIntersects = function (ray) {
  22473. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22474. };
  22475. /**
  22476. * Returns an object IntersectionInfo.
  22477. */
  22478. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22479. var intersectInfo = null;
  22480. // LineMesh first as it's also a Mesh...
  22481. if (this._mesh instanceof BABYLON.LinesMesh) {
  22482. var lineMesh = this._mesh;
  22483. // Line test
  22484. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22485. var p0 = positions[indices[index]];
  22486. var p1 = positions[indices[index + 1]];
  22487. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22488. if (length < 0) {
  22489. continue;
  22490. }
  22491. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22492. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22493. if (fastCheck) {
  22494. break;
  22495. }
  22496. }
  22497. }
  22498. }
  22499. else {
  22500. // Triangles test
  22501. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22502. var p0 = positions[indices[index]];
  22503. var p1 = positions[indices[index + 1]];
  22504. var p2 = positions[indices[index + 2]];
  22505. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22506. if (currentIntersectInfo) {
  22507. if (currentIntersectInfo.distance < 0) {
  22508. continue;
  22509. }
  22510. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22511. intersectInfo = currentIntersectInfo;
  22512. intersectInfo.faceId = index / 3;
  22513. if (fastCheck) {
  22514. break;
  22515. }
  22516. }
  22517. }
  22518. }
  22519. }
  22520. return intersectInfo;
  22521. };
  22522. // Clone
  22523. /**
  22524. * Creates a new Submesh from the passed Mesh.
  22525. */
  22526. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22527. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22528. if (!this.IsGlobal) {
  22529. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22530. }
  22531. return result;
  22532. };
  22533. // Dispose
  22534. /**
  22535. * Disposes the Submesh.
  22536. * Returns nothing.
  22537. */
  22538. SubMesh.prototype.dispose = function () {
  22539. if (this._linesIndexBuffer) {
  22540. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22541. this._linesIndexBuffer = null;
  22542. }
  22543. // Remove from mesh
  22544. var index = this._mesh.subMeshes.indexOf(this);
  22545. this._mesh.subMeshes.splice(index, 1);
  22546. };
  22547. // Statics
  22548. /**
  22549. * Creates a new Submesh from the passed parameters :
  22550. * - materialIndex (integer) : the index of the main mesh material.
  22551. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22552. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22553. * - mesh (Mesh) : the main mesh to create the submesh from.
  22554. * - renderingMesh (optional Mesh) : rendering mesh.
  22555. */
  22556. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22557. var minVertexIndex = Number.MAX_VALUE;
  22558. var maxVertexIndex = -Number.MAX_VALUE;
  22559. renderingMesh = renderingMesh || mesh;
  22560. var indices = renderingMesh.getIndices();
  22561. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22562. var vertexIndex = indices[index];
  22563. if (vertexIndex < minVertexIndex)
  22564. minVertexIndex = vertexIndex;
  22565. if (vertexIndex > maxVertexIndex)
  22566. maxVertexIndex = vertexIndex;
  22567. }
  22568. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22569. };
  22570. return SubMesh;
  22571. }(BaseSubMesh));
  22572. BABYLON.SubMesh = SubMesh;
  22573. })(BABYLON || (BABYLON = {}));
  22574. //# sourceMappingURL=babylon.subMesh.js.map
  22575. var BABYLON;
  22576. (function (BABYLON) {
  22577. var EffectFallbacks = (function () {
  22578. function EffectFallbacks() {
  22579. this._defines = {};
  22580. this._currentRank = 32;
  22581. this._maxRank = -1;
  22582. }
  22583. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22584. if (!this._defines[rank]) {
  22585. if (rank < this._currentRank) {
  22586. this._currentRank = rank;
  22587. }
  22588. if (rank > this._maxRank) {
  22589. this._maxRank = rank;
  22590. }
  22591. this._defines[rank] = new Array();
  22592. }
  22593. this._defines[rank].push(define);
  22594. };
  22595. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22596. this._meshRank = rank;
  22597. this._mesh = mesh;
  22598. if (rank < this._currentRank) {
  22599. this._currentRank = rank;
  22600. }
  22601. if (rank > this._maxRank) {
  22602. this._maxRank = rank;
  22603. }
  22604. };
  22605. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22606. get: function () {
  22607. return this._currentRank <= this._maxRank;
  22608. },
  22609. enumerable: true,
  22610. configurable: true
  22611. });
  22612. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22613. // First we try to switch to CPU skinning
  22614. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22615. this._mesh.computeBonesUsingShaders = false;
  22616. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22617. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22618. var scene = this._mesh.getScene();
  22619. for (var index = 0; index < scene.meshes.length; index++) {
  22620. var otherMesh = scene.meshes[index];
  22621. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22622. otherMesh.computeBonesUsingShaders = false;
  22623. }
  22624. }
  22625. }
  22626. else {
  22627. var currentFallbacks = this._defines[this._currentRank];
  22628. if (currentFallbacks) {
  22629. for (var index = 0; index < currentFallbacks.length; index++) {
  22630. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22631. }
  22632. }
  22633. this._currentRank++;
  22634. }
  22635. return currentDefines;
  22636. };
  22637. return EffectFallbacks;
  22638. }());
  22639. BABYLON.EffectFallbacks = EffectFallbacks;
  22640. var EffectCreationOptions = (function () {
  22641. function EffectCreationOptions() {
  22642. }
  22643. return EffectCreationOptions;
  22644. }());
  22645. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22646. var Effect = (function () {
  22647. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22648. var _this = this;
  22649. this.uniqueId = 0;
  22650. this.onCompileObservable = new BABYLON.Observable();
  22651. this.onErrorObservable = new BABYLON.Observable();
  22652. this.onBindObservable = new BABYLON.Observable();
  22653. this._uniformBuffersNames = {};
  22654. this._isReady = false;
  22655. this._compilationError = "";
  22656. this._valueCache = {};
  22657. this.name = baseName;
  22658. if (attributesNamesOrOptions.attributes) {
  22659. var options = attributesNamesOrOptions;
  22660. this._engine = uniformsNamesOrEngine;
  22661. this._attributesNames = options.attributes;
  22662. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22663. this._samplers = options.samplers;
  22664. this.defines = options.defines;
  22665. this.onError = options.onError;
  22666. this.onCompiled = options.onCompiled;
  22667. this._fallbacks = options.fallbacks;
  22668. this._indexParameters = options.indexParameters;
  22669. if (options.uniformBuffersNames) {
  22670. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22671. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22672. }
  22673. }
  22674. }
  22675. else {
  22676. this._engine = engine;
  22677. this.defines = defines;
  22678. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22679. this._samplers = samplers;
  22680. this._attributesNames = attributesNamesOrOptions;
  22681. this.onError = onError;
  22682. this.onCompiled = onCompiled;
  22683. this._indexParameters = indexParameters;
  22684. this._fallbacks = fallbacks;
  22685. }
  22686. this.uniqueId = Effect._uniqueIdSeed++;
  22687. var vertexSource;
  22688. var fragmentSource;
  22689. if (baseName.vertexElement) {
  22690. vertexSource = document.getElementById(baseName.vertexElement);
  22691. if (!vertexSource) {
  22692. vertexSource = baseName.vertexElement;
  22693. }
  22694. }
  22695. else {
  22696. vertexSource = baseName.vertex || baseName;
  22697. }
  22698. if (baseName.fragmentElement) {
  22699. fragmentSource = document.getElementById(baseName.fragmentElement);
  22700. if (!fragmentSource) {
  22701. fragmentSource = baseName.fragmentElement;
  22702. }
  22703. }
  22704. else {
  22705. fragmentSource = baseName.fragment || baseName;
  22706. }
  22707. this._loadVertexShader(vertexSource, function (vertexCode) {
  22708. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22709. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22710. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22711. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22712. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22713. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22714. });
  22715. });
  22716. });
  22717. });
  22718. });
  22719. });
  22720. }
  22721. Object.defineProperty(Effect.prototype, "key", {
  22722. get: function () {
  22723. return this._key;
  22724. },
  22725. enumerable: true,
  22726. configurable: true
  22727. });
  22728. // Properties
  22729. Effect.prototype.isReady = function () {
  22730. return this._isReady;
  22731. };
  22732. Effect.prototype.getEngine = function () {
  22733. return this._engine;
  22734. };
  22735. Effect.prototype.getProgram = function () {
  22736. return this._program;
  22737. };
  22738. Effect.prototype.getAttributesNames = function () {
  22739. return this._attributesNames;
  22740. };
  22741. Effect.prototype.getAttributeLocation = function (index) {
  22742. return this._attributes[index];
  22743. };
  22744. Effect.prototype.getAttributeLocationByName = function (name) {
  22745. var index = this._attributesNames.indexOf(name);
  22746. return this._attributes[index];
  22747. };
  22748. Effect.prototype.getAttributesCount = function () {
  22749. return this._attributes.length;
  22750. };
  22751. Effect.prototype.getUniformIndex = function (uniformName) {
  22752. return this._uniformsNames.indexOf(uniformName);
  22753. };
  22754. Effect.prototype.getUniform = function (uniformName) {
  22755. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22756. };
  22757. Effect.prototype.getSamplers = function () {
  22758. return this._samplers;
  22759. };
  22760. Effect.prototype.getCompilationError = function () {
  22761. return this._compilationError;
  22762. };
  22763. Effect.prototype.getVertexShaderSource = function () {
  22764. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22765. };
  22766. Effect.prototype.getFragmentShaderSource = function () {
  22767. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22768. };
  22769. // Methods
  22770. Effect.prototype.executeWhenCompiled = function (func) {
  22771. var _this = this;
  22772. if (this.isReady()) {
  22773. func(this);
  22774. return;
  22775. }
  22776. var observer = this.onCompileObservable.add(function (effect) {
  22777. _this.onCompileObservable.remove(observer);
  22778. func(effect);
  22779. });
  22780. };
  22781. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22782. // DOM element ?
  22783. if (vertex instanceof HTMLElement) {
  22784. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22785. callback(vertexCode);
  22786. return;
  22787. }
  22788. // Base64 encoded ?
  22789. if (vertex.substr(0, 7) === "base64:") {
  22790. var vertexBinary = window.atob(vertex.substr(7));
  22791. callback(vertexBinary);
  22792. return;
  22793. }
  22794. // Is in local store ?
  22795. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22796. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22797. return;
  22798. }
  22799. var vertexShaderUrl;
  22800. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22801. vertexShaderUrl = vertex;
  22802. }
  22803. else {
  22804. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22805. }
  22806. // Vertex shader
  22807. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22808. };
  22809. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22810. // DOM element ?
  22811. if (fragment instanceof HTMLElement) {
  22812. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22813. callback(fragmentCode);
  22814. return;
  22815. }
  22816. // Base64 encoded ?
  22817. if (fragment.substr(0, 7) === "base64:") {
  22818. var fragmentBinary = window.atob(fragment.substr(7));
  22819. callback(fragmentBinary);
  22820. return;
  22821. }
  22822. // Is in local store ?
  22823. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22824. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22825. return;
  22826. }
  22827. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22828. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22829. return;
  22830. }
  22831. var fragmentShaderUrl;
  22832. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22833. fragmentShaderUrl = fragment;
  22834. }
  22835. else {
  22836. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22837. }
  22838. // Fragment shader
  22839. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22840. };
  22841. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22842. // Rebuild shaders source code
  22843. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22844. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22845. vertexCode = prefix + vertexCode;
  22846. fragmentCode = prefix + fragmentCode;
  22847. // Number lines of shaders source code
  22848. var i = 2;
  22849. var regex = /\n/gm;
  22850. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22851. i = 2;
  22852. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22853. // Dump shaders name and formatted source code
  22854. if (this.name.vertexElement) {
  22855. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22856. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22857. }
  22858. else if (this.name.vertex) {
  22859. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22860. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22861. }
  22862. else {
  22863. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22864. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22865. }
  22866. };
  22867. ;
  22868. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22869. var preparedSourceCode = this._processPrecision(sourceCode);
  22870. if (this._engine.webGLVersion == 1) {
  22871. callback(preparedSourceCode);
  22872. return;
  22873. }
  22874. // Already converted
  22875. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22876. callback(preparedSourceCode.replace("#version 300 es", ""));
  22877. return;
  22878. }
  22879. // Remove extensions
  22880. // #extension GL_OES_standard_derivatives : enable
  22881. // #extension GL_EXT_shader_texture_lod : enable
  22882. // #extension GL_EXT_frag_depth : enable
  22883. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22884. var result = preparedSourceCode.replace(regex, "");
  22885. // Migrate to GLSL v300
  22886. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22887. result = result.replace(/attribute[ \t]/g, "in ");
  22888. result = result.replace(/[ \t]attribute/g, " in");
  22889. if (isFragment) {
  22890. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22891. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22892. result = result.replace(/texture2D\(/g, "texture(");
  22893. result = result.replace(/textureCube\(/g, "texture(");
  22894. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22895. result = result.replace(/gl_FragColor/g, "glFragColor");
  22896. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22897. }
  22898. callback(result);
  22899. };
  22900. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22901. var _this = this;
  22902. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22903. var match = regex.exec(sourceCode);
  22904. var returnValue = new String(sourceCode);
  22905. while (match != null) {
  22906. var includeFile = match[1];
  22907. // Uniform declaration
  22908. if (includeFile.indexOf("__decl__") !== -1) {
  22909. includeFile = includeFile.replace(/__decl__/, "");
  22910. if (this._engine.webGLVersion != 1) {
  22911. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22912. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22913. }
  22914. includeFile = includeFile + "Declaration";
  22915. }
  22916. if (Effect.IncludesShadersStore[includeFile]) {
  22917. // Substitution
  22918. var includeContent = Effect.IncludesShadersStore[includeFile];
  22919. if (match[2]) {
  22920. var splits = match[3].split(",");
  22921. for (var index = 0; index < splits.length; index += 2) {
  22922. var source = new RegExp(splits[index], "g");
  22923. var dest = splits[index + 1];
  22924. includeContent = includeContent.replace(source, dest);
  22925. }
  22926. }
  22927. if (match[4]) {
  22928. var indexString = match[5];
  22929. if (indexString.indexOf("..") !== -1) {
  22930. var indexSplits = indexString.split("..");
  22931. var minIndex = parseInt(indexSplits[0]);
  22932. var maxIndex = parseInt(indexSplits[1]);
  22933. var sourceIncludeContent = includeContent.slice(0);
  22934. includeContent = "";
  22935. if (isNaN(maxIndex)) {
  22936. maxIndex = this._indexParameters[indexSplits[1]];
  22937. }
  22938. for (var i = minIndex; i < maxIndex; i++) {
  22939. if (this._engine.webGLVersion === 1) {
  22940. // Ubo replacement
  22941. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22942. return p1 + "{X}";
  22943. });
  22944. }
  22945. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22946. }
  22947. }
  22948. else {
  22949. if (this._engine.webGLVersion === 1) {
  22950. // Ubo replacement
  22951. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22952. return p1 + "{X}";
  22953. });
  22954. }
  22955. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22956. }
  22957. }
  22958. // Replace
  22959. returnValue = returnValue.replace(match[0], includeContent);
  22960. }
  22961. else {
  22962. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22963. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22964. Effect.IncludesShadersStore[includeFile] = fileContent;
  22965. _this._processIncludes(returnValue, callback);
  22966. });
  22967. return;
  22968. }
  22969. match = regex.exec(sourceCode);
  22970. }
  22971. callback(returnValue);
  22972. };
  22973. Effect.prototype._processPrecision = function (source) {
  22974. if (source.indexOf("precision highp float") === -1) {
  22975. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22976. source = "precision mediump float;\n" + source;
  22977. }
  22978. else {
  22979. source = "precision highp float;\n" + source;
  22980. }
  22981. }
  22982. else {
  22983. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22984. source = source.replace("precision highp float", "precision mediump float");
  22985. }
  22986. }
  22987. return source;
  22988. };
  22989. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22990. try {
  22991. var engine = this._engine;
  22992. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22993. if (engine.webGLVersion > 1) {
  22994. for (var name in this._uniformBuffersNames) {
  22995. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22996. }
  22997. }
  22998. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22999. this._attributes = engine.getAttributes(this._program, attributesNames);
  23000. var index;
  23001. for (index = 0; index < this._samplers.length; index++) {
  23002. var sampler = this.getUniform(this._samplers[index]);
  23003. if (sampler == null) {
  23004. this._samplers.splice(index, 1);
  23005. index--;
  23006. }
  23007. }
  23008. engine.bindSamplers(this);
  23009. this._compilationError = "";
  23010. this._isReady = true;
  23011. if (this.onCompiled) {
  23012. this.onCompiled(this);
  23013. }
  23014. this.onCompileObservable.notifyObservers(this);
  23015. }
  23016. catch (e) {
  23017. this._compilationError = e.message;
  23018. // Let's go through fallbacks then
  23019. BABYLON.Tools.Error("Unable to compile effect:");
  23020. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  23021. return " " + uniform;
  23022. }));
  23023. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  23024. return " " + attribute;
  23025. }));
  23026. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  23027. BABYLON.Tools.Error("Error: " + this._compilationError);
  23028. if (fallbacks && fallbacks.isMoreFallbacks) {
  23029. BABYLON.Tools.Error("Trying next fallback.");
  23030. defines = fallbacks.reduce(defines);
  23031. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23032. }
  23033. else {
  23034. if (this.onError) {
  23035. this.onError(this, this._compilationError);
  23036. }
  23037. this.onErrorObservable.notifyObservers(this);
  23038. }
  23039. }
  23040. };
  23041. Object.defineProperty(Effect.prototype, "isSupported", {
  23042. get: function () {
  23043. return this._compilationError === "";
  23044. },
  23045. enumerable: true,
  23046. configurable: true
  23047. });
  23048. Effect.prototype._bindTexture = function (channel, texture) {
  23049. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23050. };
  23051. Effect.prototype.setTexture = function (channel, texture) {
  23052. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23053. };
  23054. Effect.prototype.setTextureArray = function (channel, textures) {
  23055. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23056. var initialPos = this._samplers.indexOf(channel);
  23057. for (var index = 1; index < textures.length; index++) {
  23058. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23059. }
  23060. }
  23061. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23062. };
  23063. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23064. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23065. };
  23066. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23067. var cache = this._valueCache[uniformName];
  23068. var flag = matrix.updateFlag;
  23069. if (cache !== undefined && cache === flag) {
  23070. return false;
  23071. }
  23072. this._valueCache[uniformName] = flag;
  23073. return true;
  23074. };
  23075. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23076. var cache = this._valueCache[uniformName];
  23077. if (!cache) {
  23078. cache = [x, y];
  23079. this._valueCache[uniformName] = cache;
  23080. return true;
  23081. }
  23082. var changed = false;
  23083. if (cache[0] !== x) {
  23084. cache[0] = x;
  23085. changed = true;
  23086. }
  23087. if (cache[1] !== y) {
  23088. cache[1] = y;
  23089. changed = true;
  23090. }
  23091. return changed;
  23092. };
  23093. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23094. var cache = this._valueCache[uniformName];
  23095. if (!cache) {
  23096. cache = [x, y, z];
  23097. this._valueCache[uniformName] = cache;
  23098. return true;
  23099. }
  23100. var changed = false;
  23101. if (cache[0] !== x) {
  23102. cache[0] = x;
  23103. changed = true;
  23104. }
  23105. if (cache[1] !== y) {
  23106. cache[1] = y;
  23107. changed = true;
  23108. }
  23109. if (cache[2] !== z) {
  23110. cache[2] = z;
  23111. changed = true;
  23112. }
  23113. return changed;
  23114. };
  23115. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  23116. var cache = this._valueCache[uniformName];
  23117. if (!cache) {
  23118. cache = [x, y, z, w];
  23119. this._valueCache[uniformName] = cache;
  23120. return true;
  23121. }
  23122. var changed = false;
  23123. if (cache[0] !== x) {
  23124. cache[0] = x;
  23125. changed = true;
  23126. }
  23127. if (cache[1] !== y) {
  23128. cache[1] = y;
  23129. changed = true;
  23130. }
  23131. if (cache[2] !== z) {
  23132. cache[2] = z;
  23133. changed = true;
  23134. }
  23135. if (cache[3] !== w) {
  23136. cache[3] = w;
  23137. changed = true;
  23138. }
  23139. return changed;
  23140. };
  23141. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  23142. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  23143. return;
  23144. }
  23145. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  23146. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  23147. };
  23148. Effect.prototype.bindUniformBlock = function (blockName, index) {
  23149. this._engine.bindUniformBlock(this._program, blockName, index);
  23150. };
  23151. Effect.prototype.setIntArray = function (uniformName, array) {
  23152. this._valueCache[uniformName] = null;
  23153. this._engine.setIntArray(this.getUniform(uniformName), array);
  23154. return this;
  23155. };
  23156. Effect.prototype.setIntArray2 = function (uniformName, array) {
  23157. this._valueCache[uniformName] = null;
  23158. this._engine.setIntArray2(this.getUniform(uniformName), array);
  23159. return this;
  23160. };
  23161. Effect.prototype.setIntArray3 = function (uniformName, array) {
  23162. this._valueCache[uniformName] = null;
  23163. this._engine.setIntArray3(this.getUniform(uniformName), array);
  23164. return this;
  23165. };
  23166. Effect.prototype.setIntArray4 = function (uniformName, array) {
  23167. this._valueCache[uniformName] = null;
  23168. this._engine.setIntArray4(this.getUniform(uniformName), array);
  23169. return this;
  23170. };
  23171. Effect.prototype.setFloatArray = function (uniformName, array) {
  23172. this._valueCache[uniformName] = null;
  23173. this._engine.setFloatArray(this.getUniform(uniformName), array);
  23174. return this;
  23175. };
  23176. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  23177. this._valueCache[uniformName] = null;
  23178. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  23179. return this;
  23180. };
  23181. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  23182. this._valueCache[uniformName] = null;
  23183. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  23184. return this;
  23185. };
  23186. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  23187. this._valueCache[uniformName] = null;
  23188. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  23189. return this;
  23190. };
  23191. Effect.prototype.setArray = function (uniformName, array) {
  23192. this._valueCache[uniformName] = null;
  23193. this._engine.setArray(this.getUniform(uniformName), array);
  23194. return this;
  23195. };
  23196. Effect.prototype.setArray2 = function (uniformName, array) {
  23197. this._valueCache[uniformName] = null;
  23198. this._engine.setArray2(this.getUniform(uniformName), array);
  23199. return this;
  23200. };
  23201. Effect.prototype.setArray3 = function (uniformName, array) {
  23202. this._valueCache[uniformName] = null;
  23203. this._engine.setArray3(this.getUniform(uniformName), array);
  23204. return this;
  23205. };
  23206. Effect.prototype.setArray4 = function (uniformName, array) {
  23207. this._valueCache[uniformName] = null;
  23208. this._engine.setArray4(this.getUniform(uniformName), array);
  23209. return this;
  23210. };
  23211. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23212. if (!matrices) {
  23213. return;
  23214. }
  23215. this._valueCache[uniformName] = null;
  23216. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23217. return this;
  23218. };
  23219. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23220. if (this._cacheMatrix(uniformName, matrix)) {
  23221. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23222. }
  23223. return this;
  23224. };
  23225. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23226. this._valueCache[uniformName] = null;
  23227. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23228. return this;
  23229. };
  23230. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23231. this._valueCache[uniformName] = null;
  23232. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23233. return this;
  23234. };
  23235. Effect.prototype.setFloat = function (uniformName, value) {
  23236. var cache = this._valueCache[uniformName];
  23237. if (cache !== undefined && cache === value)
  23238. return this;
  23239. this._valueCache[uniformName] = value;
  23240. this._engine.setFloat(this.getUniform(uniformName), value);
  23241. return this;
  23242. };
  23243. Effect.prototype.setBool = function (uniformName, bool) {
  23244. var cache = this._valueCache[uniformName];
  23245. if (cache !== undefined && cache === bool)
  23246. return this;
  23247. this._valueCache[uniformName] = bool;
  23248. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23249. return this;
  23250. };
  23251. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23252. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23253. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23254. }
  23255. return this;
  23256. };
  23257. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23258. if (this._cacheFloat2(uniformName, x, y)) {
  23259. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23260. }
  23261. return this;
  23262. };
  23263. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23264. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23265. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23266. }
  23267. return this;
  23268. };
  23269. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23270. if (this._cacheFloat3(uniformName, x, y, z)) {
  23271. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23272. }
  23273. return this;
  23274. };
  23275. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23276. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23277. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23278. }
  23279. return this;
  23280. };
  23281. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23282. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23283. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23284. }
  23285. return this;
  23286. };
  23287. Effect.prototype.setColor3 = function (uniformName, color3) {
  23288. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23289. this._engine.setColor3(this.getUniform(uniformName), color3);
  23290. }
  23291. return this;
  23292. };
  23293. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23294. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23295. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23296. }
  23297. return this;
  23298. };
  23299. Effect.prototype._recombineShader = function (node) {
  23300. if (node.define) {
  23301. if (node.condition) {
  23302. var defineIndex = this.defines.indexOf("#define " + node.define);
  23303. if (defineIndex === -1) {
  23304. return null;
  23305. }
  23306. var nextComma = this.defines.indexOf("\n", defineIndex);
  23307. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23308. var condition = defineValue + node.condition;
  23309. if (!eval(condition)) {
  23310. return null;
  23311. }
  23312. }
  23313. else if (node.ndef) {
  23314. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23315. return null;
  23316. }
  23317. }
  23318. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23319. return null;
  23320. }
  23321. }
  23322. var result = "";
  23323. for (var index = 0; index < node.children.length; index++) {
  23324. var line = node.children[index];
  23325. if (line.children) {
  23326. var combined = this._recombineShader(line);
  23327. if (combined !== null) {
  23328. result += combined + "\r\n";
  23329. }
  23330. continue;
  23331. }
  23332. if (line.length > 0) {
  23333. result += line + "\r\n";
  23334. }
  23335. }
  23336. return result;
  23337. };
  23338. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23339. var root = {
  23340. children: []
  23341. };
  23342. var currentNode = root;
  23343. var lines = shaderString.split("\n");
  23344. for (var index = 0; index < lines.length; index++) {
  23345. var line = lines[index].trim();
  23346. // #ifdef
  23347. var pos = line.indexOf("#ifdef ");
  23348. if (pos !== -1) {
  23349. var define = line.substr(pos + 7);
  23350. var newNode = {
  23351. condition: null,
  23352. ndef: false,
  23353. define: define,
  23354. children: [],
  23355. parent: currentNode
  23356. };
  23357. currentNode.children.push(newNode);
  23358. currentNode = newNode;
  23359. continue;
  23360. }
  23361. // #ifndef
  23362. var pos = line.indexOf("#ifndef ");
  23363. if (pos !== -1) {
  23364. var define = line.substr(pos + 8);
  23365. newNode = {
  23366. condition: null,
  23367. define: define,
  23368. ndef: true,
  23369. children: [],
  23370. parent: currentNode
  23371. };
  23372. currentNode.children.push(newNode);
  23373. currentNode = newNode;
  23374. continue;
  23375. }
  23376. // #if
  23377. var pos = line.indexOf("#if ");
  23378. if (pos !== -1) {
  23379. var define = line.substr(pos + 4).trim();
  23380. var conditionPos = define.indexOf(" ");
  23381. newNode = {
  23382. condition: define.substr(conditionPos + 1),
  23383. define: define.substr(0, conditionPos),
  23384. ndef: false,
  23385. children: [],
  23386. parent: currentNode
  23387. };
  23388. currentNode.children.push(newNode);
  23389. currentNode = newNode;
  23390. continue;
  23391. }
  23392. // #endif
  23393. pos = line.indexOf("#endif");
  23394. if (pos !== -1) {
  23395. currentNode = currentNode.parent;
  23396. continue;
  23397. }
  23398. currentNode.children.push(line);
  23399. }
  23400. // Recombine
  23401. return this._recombineShader(root);
  23402. };
  23403. return Effect;
  23404. }());
  23405. Effect._uniqueIdSeed = 0;
  23406. Effect._baseCache = {};
  23407. // Statics
  23408. Effect.ShadersStore = {};
  23409. Effect.IncludesShadersStore = {};
  23410. BABYLON.Effect = Effect;
  23411. })(BABYLON || (BABYLON = {}));
  23412. //# sourceMappingURL=babylon.effect.js.map
  23413. var BABYLON;
  23414. (function (BABYLON) {
  23415. var MaterialHelper = (function () {
  23416. function MaterialHelper() {
  23417. }
  23418. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23419. if (defines._areMiscDirty) {
  23420. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23421. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23422. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23423. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23424. }
  23425. };
  23426. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23427. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23428. var changed = false;
  23429. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23430. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23431. changed = true;
  23432. }
  23433. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23434. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23435. changed = true;
  23436. }
  23437. if (defines["INSTANCES"] !== useInstances) {
  23438. defines["INSTANCES"] = useInstances;
  23439. changed = true;
  23440. }
  23441. if (changed) {
  23442. defines.markAsUnprocessed();
  23443. }
  23444. };
  23445. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23446. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23447. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23448. return false;
  23449. }
  23450. defines._normals = defines._needNormals;
  23451. defines._uvs = defines._needUVs;
  23452. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23453. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23454. defines["TANGENT"] = true;
  23455. }
  23456. if (defines._needUVs) {
  23457. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23458. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23459. }
  23460. else {
  23461. defines["UV1"] = false;
  23462. defines["UV2"] = false;
  23463. }
  23464. if (useVertexColor) {
  23465. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23466. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23467. }
  23468. if (useBones) {
  23469. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23470. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23471. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23472. }
  23473. else {
  23474. defines["NUM_BONE_INFLUENCERS"] = 0;
  23475. defines["BonesPerMesh"] = 0;
  23476. }
  23477. }
  23478. if (useMorphTargets) {
  23479. if (mesh.morphTargetManager) {
  23480. var manager = mesh.morphTargetManager;
  23481. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23482. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23483. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23484. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23485. }
  23486. else {
  23487. defines["MORPHTARGETS_TANGENT"] = false;
  23488. defines["MORPHTARGETS_NORMAL"] = false;
  23489. defines["MORPHTARGETS"] = false;
  23490. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23491. }
  23492. }
  23493. return true;
  23494. };
  23495. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23496. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23497. if (disableLighting === void 0) { disableLighting = false; }
  23498. if (!defines._areLightsDirty) {
  23499. return defines._needNormals;
  23500. }
  23501. var lightIndex = 0;
  23502. var needNormals = false;
  23503. var needRebuild = false;
  23504. var lightmapMode = false;
  23505. var shadowEnabled = false;
  23506. var specularEnabled = false;
  23507. if (scene.lightsEnabled && !disableLighting) {
  23508. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23509. var light = _a[_i];
  23510. needNormals = true;
  23511. if (defines["LIGHT" + lightIndex] === undefined) {
  23512. needRebuild = true;
  23513. }
  23514. defines["LIGHT" + lightIndex] = true;
  23515. defines["SPOTLIGHT" + lightIndex] = false;
  23516. defines["HEMILIGHT" + lightIndex] = false;
  23517. defines["POINTLIGHT" + lightIndex] = false;
  23518. defines["DIRLIGHT" + lightIndex] = false;
  23519. var type;
  23520. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23521. type = "SPOTLIGHT" + lightIndex;
  23522. }
  23523. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23524. type = "HEMILIGHT" + lightIndex;
  23525. }
  23526. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23527. type = "POINTLIGHT" + lightIndex;
  23528. }
  23529. else {
  23530. type = "DIRLIGHT" + lightIndex;
  23531. }
  23532. defines[type] = true;
  23533. // Specular
  23534. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23535. specularEnabled = true;
  23536. }
  23537. // Shadows
  23538. defines["SHADOW" + lightIndex] = false;
  23539. defines["SHADOWPCF" + lightIndex] = false;
  23540. defines["SHADOWESM" + lightIndex] = false;
  23541. defines["SHADOWCUBE" + lightIndex] = false;
  23542. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23543. var shadowGenerator = light.getShadowGenerator();
  23544. if (shadowGenerator) {
  23545. shadowEnabled = true;
  23546. shadowGenerator.prepareDefines(defines, lightIndex);
  23547. }
  23548. }
  23549. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23550. lightmapMode = true;
  23551. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23552. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23553. }
  23554. else {
  23555. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23556. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23557. }
  23558. lightIndex++;
  23559. if (lightIndex === maxSimultaneousLights)
  23560. break;
  23561. }
  23562. }
  23563. defines["SPECULARTERM"] = specularEnabled;
  23564. defines["SHADOWS"] = shadowEnabled;
  23565. // Resetting all other lights if any
  23566. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23567. if (defines["LIGHT" + index] !== undefined) {
  23568. defines["LIGHT" + index] = false;
  23569. defines["HEMILIGHT" + lightIndex] = false;
  23570. defines["POINTLIGHT" + lightIndex] = false;
  23571. defines["DIRLIGHT" + lightIndex] = false;
  23572. defines["SPOTLIGHT" + lightIndex] = false;
  23573. defines["SHADOW" + lightIndex] = false;
  23574. }
  23575. }
  23576. var caps = scene.getEngine().getCaps();
  23577. if (defines["SHADOWFLOAT"] === undefined) {
  23578. needRebuild = true;
  23579. }
  23580. defines["SHADOWFLOAT"] = shadowEnabled &&
  23581. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23582. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23583. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23584. if (needRebuild) {
  23585. defines.rebuild();
  23586. }
  23587. return needNormals;
  23588. };
  23589. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23590. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23591. var uniformsList, uniformBuffersList, samplersList, defines;
  23592. if (uniformsListOrOptions.uniformsNames) {
  23593. var options = uniformsListOrOptions;
  23594. uniformsList = options.uniformsNames;
  23595. uniformBuffersList = options.uniformBuffersNames;
  23596. samplersList = options.samplers;
  23597. defines = options.defines;
  23598. maxSimultaneousLights = options.maxSimultaneousLights;
  23599. }
  23600. else {
  23601. uniformsList = uniformsListOrOptions;
  23602. }
  23603. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23604. if (!defines["LIGHT" + lightIndex]) {
  23605. break;
  23606. }
  23607. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23608. if (uniformBuffersList) {
  23609. uniformBuffersList.push("Light" + lightIndex);
  23610. }
  23611. samplersList.push("shadowSampler" + lightIndex);
  23612. }
  23613. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23614. uniformsList.push("morphTargetInfluences");
  23615. }
  23616. };
  23617. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23618. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23619. if (!defines["SHADOWS"]) {
  23620. return;
  23621. }
  23622. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23623. if (!defines["LIGHT" + lightIndex]) {
  23624. break;
  23625. }
  23626. if (lightIndex > 0) {
  23627. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23628. }
  23629. if (defines["SHADOW" + lightIndex]) {
  23630. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23631. }
  23632. if (defines["SHADOWPCF" + lightIndex]) {
  23633. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23634. }
  23635. if (defines["SHADOWESM" + lightIndex]) {
  23636. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23637. }
  23638. }
  23639. };
  23640. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23641. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23642. if (influencers > 0) {
  23643. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23644. var manager = mesh.morphTargetManager;
  23645. var normal = manager.supportsNormals && defines["NORMAL"];
  23646. var tangent = manager.supportsTangents && defines["TANGENT"];
  23647. for (var index = 0; index < influencers; index++) {
  23648. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23649. if (normal) {
  23650. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23651. }
  23652. if (tangent) {
  23653. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23654. }
  23655. if (attribs.length > maxAttributesCount) {
  23656. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23657. }
  23658. }
  23659. }
  23660. };
  23661. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23662. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23663. fallbacks.addCPUSkinningFallback(0, mesh);
  23664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23666. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23669. }
  23670. }
  23671. };
  23672. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23673. if (defines["INSTANCES"]) {
  23674. attribs.push("world0");
  23675. attribs.push("world1");
  23676. attribs.push("world2");
  23677. attribs.push("world3");
  23678. }
  23679. };
  23680. // Bindings
  23681. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23682. if (light.shadowEnabled && mesh.receiveShadows) {
  23683. var shadowGenerator = light.getShadowGenerator();
  23684. if (shadowGenerator) {
  23685. shadowGenerator.bindShadowLight(lightIndex, effect);
  23686. }
  23687. }
  23688. };
  23689. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23690. light.transferToEffect(effect, lightIndex + "");
  23691. };
  23692. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  23693. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23694. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  23695. var lightIndex = 0;
  23696. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23697. var light = _a[_i];
  23698. var scaledIntensity = light.getScaledIntensity();
  23699. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23700. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23701. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  23702. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  23703. if (defines["SPECULARTERM"]) {
  23704. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  23705. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23706. }
  23707. // Shadows
  23708. if (scene.shadowsEnabled) {
  23709. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23710. }
  23711. light._uniformBuffer.update();
  23712. lightIndex++;
  23713. if (lightIndex === maxSimultaneousLights)
  23714. break;
  23715. }
  23716. };
  23717. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23718. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23719. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23720. effect.setColor3("vFogColor", scene.fogColor);
  23721. }
  23722. };
  23723. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23724. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23725. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23726. if (matrices) {
  23727. effect.setMatrices("mBones", matrices);
  23728. }
  23729. }
  23730. };
  23731. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23732. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23733. return;
  23734. }
  23735. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23736. };
  23737. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23738. if (defines["LOGARITHMICDEPTH"]) {
  23739. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23740. }
  23741. };
  23742. MaterialHelper.BindClipPlane = function (effect, scene) {
  23743. if (scene.clipPlane) {
  23744. var clipPlane = scene.clipPlane;
  23745. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23746. }
  23747. };
  23748. return MaterialHelper;
  23749. }());
  23750. BABYLON.MaterialHelper = MaterialHelper;
  23751. })(BABYLON || (BABYLON = {}));
  23752. //# sourceMappingURL=babylon.materialHelper.js.map
  23753. var BABYLON;
  23754. (function (BABYLON) {
  23755. var MaterialDefines = (function () {
  23756. function MaterialDefines() {
  23757. this._isDirty = true;
  23758. this._areLightsDirty = true;
  23759. this._areAttributesDirty = true;
  23760. this._areTexturesDirty = true;
  23761. this._areFresnelDirty = true;
  23762. this._areMiscDirty = true;
  23763. this._areImageProcessingDirty = true;
  23764. this._normals = false;
  23765. this._uvs = false;
  23766. this._needNormals = false;
  23767. this._needUVs = false;
  23768. }
  23769. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23770. get: function () {
  23771. return this._isDirty;
  23772. },
  23773. enumerable: true,
  23774. configurable: true
  23775. });
  23776. MaterialDefines.prototype.markAsProcessed = function () {
  23777. this._isDirty = false;
  23778. this._areAttributesDirty = false;
  23779. this._areTexturesDirty = false;
  23780. this._areFresnelDirty = false;
  23781. this._areLightsDirty = false;
  23782. this._areMiscDirty = false;
  23783. this._areImageProcessingDirty = false;
  23784. };
  23785. MaterialDefines.prototype.markAsUnprocessed = function () {
  23786. this._isDirty = true;
  23787. };
  23788. MaterialDefines.prototype.markAllAsDirty = function () {
  23789. this._areTexturesDirty = true;
  23790. this._areAttributesDirty = true;
  23791. this._areLightsDirty = true;
  23792. this._areFresnelDirty = true;
  23793. this._areMiscDirty = true;
  23794. this._areImageProcessingDirty = true;
  23795. this._isDirty = true;
  23796. };
  23797. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  23798. this._areImageProcessingDirty = true;
  23799. this._isDirty = true;
  23800. };
  23801. MaterialDefines.prototype.markAsLightDirty = function () {
  23802. this._areLightsDirty = true;
  23803. this._isDirty = true;
  23804. };
  23805. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23806. this._areAttributesDirty = true;
  23807. this._isDirty = true;
  23808. };
  23809. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23810. this._areTexturesDirty = true;
  23811. this._isDirty = true;
  23812. };
  23813. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23814. this._areFresnelDirty = true;
  23815. this._isDirty = true;
  23816. };
  23817. MaterialDefines.prototype.markAsMiscDirty = function () {
  23818. this._areMiscDirty = true;
  23819. this._isDirty = true;
  23820. };
  23821. MaterialDefines.prototype.rebuild = function () {
  23822. if (this._keys) {
  23823. delete this._keys;
  23824. }
  23825. this._keys = [];
  23826. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23827. var key = _a[_i];
  23828. if (key[0] === "_") {
  23829. continue;
  23830. }
  23831. this._keys.push(key);
  23832. }
  23833. };
  23834. MaterialDefines.prototype.isEqual = function (other) {
  23835. if (this._keys.length !== other._keys.length) {
  23836. return false;
  23837. }
  23838. for (var index = 0; index < this._keys.length; index++) {
  23839. var prop = this._keys[index];
  23840. if (this[prop] !== other[prop]) {
  23841. return false;
  23842. }
  23843. }
  23844. return true;
  23845. };
  23846. MaterialDefines.prototype.cloneTo = function (other) {
  23847. if (this._keys.length !== other._keys.length) {
  23848. other._keys = this._keys.slice(0);
  23849. }
  23850. for (var index = 0; index < this._keys.length; index++) {
  23851. var prop = this._keys[index];
  23852. other[prop] = this[prop];
  23853. }
  23854. };
  23855. MaterialDefines.prototype.reset = function () {
  23856. for (var index = 0; index < this._keys.length; index++) {
  23857. var prop = this._keys[index];
  23858. if (typeof (this[prop]) === "number") {
  23859. this[prop] = 0;
  23860. }
  23861. else {
  23862. this[prop] = false;
  23863. }
  23864. }
  23865. };
  23866. MaterialDefines.prototype.toString = function () {
  23867. var result = "";
  23868. for (var index = 0; index < this._keys.length; index++) {
  23869. var prop = this._keys[index];
  23870. var value = this[prop];
  23871. if (typeof (value) === "number") {
  23872. result += "#define " + prop + " " + this[prop] + "\n";
  23873. }
  23874. else if (value) {
  23875. result += "#define " + prop + "\n";
  23876. }
  23877. }
  23878. return result;
  23879. };
  23880. return MaterialDefines;
  23881. }());
  23882. BABYLON.MaterialDefines = MaterialDefines;
  23883. var Material = (function () {
  23884. function Material(name, scene, doNotAdd) {
  23885. this.checkReadyOnEveryCall = false;
  23886. this.checkReadyOnlyOnce = false;
  23887. this.state = "";
  23888. this.alpha = 1.0;
  23889. this._backFaceCulling = true;
  23890. this.doNotSerialize = false;
  23891. this.storeEffectOnSubMeshes = false;
  23892. /**
  23893. * An event triggered when the material is disposed.
  23894. * @type {BABYLON.Observable}
  23895. */
  23896. this.onDisposeObservable = new BABYLON.Observable();
  23897. /**
  23898. * An event triggered when the material is bound.
  23899. * @type {BABYLON.Observable}
  23900. */
  23901. this.onBindObservable = new BABYLON.Observable();
  23902. /**
  23903. * An event triggered when the material is unbound.
  23904. * @type {BABYLON.Observable}
  23905. */
  23906. this.onUnBindObservable = new BABYLON.Observable();
  23907. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23908. this.disableDepthWrite = false;
  23909. this._fogEnabled = true;
  23910. this.pointSize = 1.0;
  23911. this.zOffset = 0;
  23912. this._wasPreviouslyReady = false;
  23913. this._fillMode = Material.TriangleFillMode;
  23914. this.name = name;
  23915. this.id = name;
  23916. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23917. if (this._scene.useRightHandedSystem) {
  23918. this.sideOrientation = Material.ClockWiseSideOrientation;
  23919. }
  23920. else {
  23921. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23922. }
  23923. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23924. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23925. if (!doNotAdd) {
  23926. this._scene.materials.push(this);
  23927. }
  23928. }
  23929. Object.defineProperty(Material, "TriangleFillMode", {
  23930. get: function () {
  23931. return Material._TriangleFillMode;
  23932. },
  23933. enumerable: true,
  23934. configurable: true
  23935. });
  23936. Object.defineProperty(Material, "WireFrameFillMode", {
  23937. get: function () {
  23938. return Material._WireFrameFillMode;
  23939. },
  23940. enumerable: true,
  23941. configurable: true
  23942. });
  23943. Object.defineProperty(Material, "PointFillMode", {
  23944. get: function () {
  23945. return Material._PointFillMode;
  23946. },
  23947. enumerable: true,
  23948. configurable: true
  23949. });
  23950. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23951. get: function () {
  23952. return Material._ClockWiseSideOrientation;
  23953. },
  23954. enumerable: true,
  23955. configurable: true
  23956. });
  23957. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23958. get: function () {
  23959. return Material._CounterClockWiseSideOrientation;
  23960. },
  23961. enumerable: true,
  23962. configurable: true
  23963. });
  23964. Object.defineProperty(Material, "TextureDirtyFlag", {
  23965. get: function () {
  23966. return Material._TextureDirtyFlag;
  23967. },
  23968. enumerable: true,
  23969. configurable: true
  23970. });
  23971. Object.defineProperty(Material, "LightDirtyFlag", {
  23972. get: function () {
  23973. return Material._LightDirtyFlag;
  23974. },
  23975. enumerable: true,
  23976. configurable: true
  23977. });
  23978. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23979. get: function () {
  23980. return Material._FresnelDirtyFlag;
  23981. },
  23982. enumerable: true,
  23983. configurable: true
  23984. });
  23985. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23986. get: function () {
  23987. return Material._AttributesDirtyFlag;
  23988. },
  23989. enumerable: true,
  23990. configurable: true
  23991. });
  23992. Object.defineProperty(Material, "MiscDirtyFlag", {
  23993. get: function () {
  23994. return Material._MiscDirtyFlag;
  23995. },
  23996. enumerable: true,
  23997. configurable: true
  23998. });
  23999. Object.defineProperty(Material.prototype, "backFaceCulling", {
  24000. get: function () {
  24001. return this._backFaceCulling;
  24002. },
  24003. set: function (value) {
  24004. if (this._backFaceCulling === value) {
  24005. return;
  24006. }
  24007. this._backFaceCulling = value;
  24008. this.markAsDirty(Material.TextureDirtyFlag);
  24009. },
  24010. enumerable: true,
  24011. configurable: true
  24012. });
  24013. Object.defineProperty(Material.prototype, "onDispose", {
  24014. set: function (callback) {
  24015. if (this._onDisposeObserver) {
  24016. this.onDisposeObservable.remove(this._onDisposeObserver);
  24017. }
  24018. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(Material.prototype, "onBind", {
  24024. set: function (callback) {
  24025. if (this._onBindObserver) {
  24026. this.onBindObservable.remove(this._onBindObserver);
  24027. }
  24028. this._onBindObserver = this.onBindObservable.add(callback);
  24029. },
  24030. enumerable: true,
  24031. configurable: true
  24032. });
  24033. Object.defineProperty(Material.prototype, "fogEnabled", {
  24034. get: function () {
  24035. return this._fogEnabled;
  24036. },
  24037. set: function (value) {
  24038. if (this._fogEnabled === value) {
  24039. return;
  24040. }
  24041. this._fogEnabled = value;
  24042. this.markAsDirty(Material.MiscDirtyFlag);
  24043. },
  24044. enumerable: true,
  24045. configurable: true
  24046. });
  24047. Object.defineProperty(Material.prototype, "wireframe", {
  24048. get: function () {
  24049. return this._fillMode === Material.WireFrameFillMode;
  24050. },
  24051. set: function (value) {
  24052. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24053. },
  24054. enumerable: true,
  24055. configurable: true
  24056. });
  24057. Object.defineProperty(Material.prototype, "pointsCloud", {
  24058. get: function () {
  24059. return this._fillMode === Material.PointFillMode;
  24060. },
  24061. set: function (value) {
  24062. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(Material.prototype, "fillMode", {
  24068. get: function () {
  24069. return this._fillMode;
  24070. },
  24071. set: function (value) {
  24072. if (this._fillMode === value) {
  24073. return;
  24074. }
  24075. this._fillMode = value;
  24076. this.markAsDirty(Material.MiscDirtyFlag);
  24077. },
  24078. enumerable: true,
  24079. configurable: true
  24080. });
  24081. /**
  24082. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24083. * subclasses should override adding information pertainent to themselves
  24084. */
  24085. Material.prototype.toString = function (fullDetails) {
  24086. var ret = "Name: " + this.name;
  24087. if (fullDetails) {
  24088. }
  24089. return ret;
  24090. };
  24091. /**
  24092. * Child classes can use it to update shaders
  24093. */
  24094. Material.prototype.getClassName = function () {
  24095. return "Material";
  24096. };
  24097. Object.defineProperty(Material.prototype, "isFrozen", {
  24098. get: function () {
  24099. return this.checkReadyOnlyOnce;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Material.prototype.freeze = function () {
  24105. this.checkReadyOnlyOnce = true;
  24106. };
  24107. Material.prototype.unfreeze = function () {
  24108. this.checkReadyOnlyOnce = false;
  24109. };
  24110. Material.prototype.isReady = function (mesh, useInstances) {
  24111. return true;
  24112. };
  24113. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  24114. return false;
  24115. };
  24116. Material.prototype.getEffect = function () {
  24117. return this._effect;
  24118. };
  24119. Material.prototype.getScene = function () {
  24120. return this._scene;
  24121. };
  24122. Material.prototype.needAlphaBlending = function () {
  24123. return (this.alpha < 1.0);
  24124. };
  24125. Material.prototype.needAlphaTesting = function () {
  24126. return false;
  24127. };
  24128. Material.prototype.getAlphaTestTexture = function () {
  24129. return null;
  24130. };
  24131. Material.prototype.markDirty = function () {
  24132. this._wasPreviouslyReady = false;
  24133. };
  24134. Material.prototype._preBind = function (effect) {
  24135. var engine = this._scene.getEngine();
  24136. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  24137. engine.enableEffect(effect ? effect : this._effect);
  24138. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  24139. };
  24140. Material.prototype.bind = function (world, mesh) {
  24141. };
  24142. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  24143. };
  24144. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24145. };
  24146. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  24147. sceneUbo.bindToEffect(effect, "Scene");
  24148. };
  24149. Material.prototype.bindView = function (effect) {
  24150. if (!this._useUBO) {
  24151. effect.setMatrix("view", this.getScene().getViewMatrix());
  24152. }
  24153. else {
  24154. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24155. }
  24156. };
  24157. Material.prototype.bindViewProjection = function (effect) {
  24158. if (!this._useUBO) {
  24159. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24160. }
  24161. else {
  24162. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  24163. }
  24164. };
  24165. Material.prototype._afterBind = function (mesh) {
  24166. this._scene._cachedMaterial = this;
  24167. this.onBindObservable.notifyObservers(mesh);
  24168. if (this.disableDepthWrite) {
  24169. var engine = this._scene.getEngine();
  24170. this._cachedDepthWriteState = engine.getDepthWrite();
  24171. engine.setDepthWrite(false);
  24172. }
  24173. };
  24174. Material.prototype.unbind = function () {
  24175. this.onUnBindObservable.notifyObservers(this);
  24176. if (this.disableDepthWrite) {
  24177. var engine = this._scene.getEngine();
  24178. engine.setDepthWrite(this._cachedDepthWriteState);
  24179. }
  24180. };
  24181. Material.prototype.getActiveTextures = function () {
  24182. return [];
  24183. };
  24184. Material.prototype.clone = function (name) {
  24185. return null;
  24186. };
  24187. Material.prototype.getBindedMeshes = function () {
  24188. var result = new Array();
  24189. for (var index = 0; index < this._scene.meshes.length; index++) {
  24190. var mesh = this._scene.meshes[index];
  24191. if (mesh.material === this) {
  24192. result.push(mesh);
  24193. }
  24194. }
  24195. return result;
  24196. };
  24197. // Force shader compilation including textures ready check
  24198. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  24199. var _this = this;
  24200. var subMesh = new BABYLON.BaseSubMesh();
  24201. var scene = this.getScene();
  24202. var engine = scene.getEngine();
  24203. var beforeRenderCallback = function () {
  24204. if (subMesh._materialDefines) {
  24205. subMesh._materialDefines._renderId = -1;
  24206. }
  24207. var alphaTestState = engine.getAlphaTesting();
  24208. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  24209. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  24210. scene.unregisterBeforeRender(beforeRenderCallback);
  24211. if (onCompiled) {
  24212. onCompiled(_this);
  24213. }
  24214. }
  24215. engine.setAlphaTesting(alphaTestState);
  24216. };
  24217. scene.registerBeforeRender(beforeRenderCallback);
  24218. };
  24219. Material.prototype.markAsDirty = function (flag) {
  24220. if (flag & Material.TextureDirtyFlag) {
  24221. this._markAllSubMeshesAsTexturesDirty();
  24222. }
  24223. if (flag & Material.LightDirtyFlag) {
  24224. this._markAllSubMeshesAsLightsDirty();
  24225. }
  24226. if (flag & Material.FresnelDirtyFlag) {
  24227. this._markAllSubMeshesAsFresnelDirty();
  24228. }
  24229. if (flag & Material.AttributesDirtyFlag) {
  24230. this._markAllSubMeshesAsAttributesDirty();
  24231. }
  24232. if (flag & Material.MiscDirtyFlag) {
  24233. this._markAllSubMeshesAsMiscDirty();
  24234. }
  24235. this.getScene().resetCachedMaterial();
  24236. };
  24237. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  24238. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24239. var mesh = _a[_i];
  24240. if (!mesh.subMeshes) {
  24241. continue;
  24242. }
  24243. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24244. var subMesh = _c[_b];
  24245. if (subMesh.getMaterial() !== this) {
  24246. continue;
  24247. }
  24248. if (!subMesh._materialDefines) {
  24249. return;
  24250. }
  24251. func(subMesh._materialDefines);
  24252. }
  24253. }
  24254. };
  24255. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  24256. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  24257. };
  24258. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24259. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24260. };
  24261. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24262. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24263. };
  24264. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  24265. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24266. };
  24267. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24268. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24269. };
  24270. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  24271. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24272. };
  24273. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24274. // Animations
  24275. this.getScene().stopAnimation(this);
  24276. // Remove from scene
  24277. var index = this._scene.materials.indexOf(this);
  24278. if (index >= 0) {
  24279. this._scene.materials.splice(index, 1);
  24280. }
  24281. // Remove from meshes
  24282. for (index = 0; index < this._scene.meshes.length; index++) {
  24283. var mesh = this._scene.meshes[index];
  24284. if (mesh.material === this) {
  24285. mesh.material = null;
  24286. if (mesh.geometry) {
  24287. var geometry = mesh.geometry;
  24288. if (this.storeEffectOnSubMeshes) {
  24289. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24290. var subMesh = _a[_i];
  24291. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24292. }
  24293. }
  24294. else {
  24295. geometry._releaseVertexArrayObject(this._effect);
  24296. }
  24297. }
  24298. }
  24299. }
  24300. this._uniformBuffer.dispose();
  24301. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24302. if (forceDisposeEffect && this._effect) {
  24303. if (this.storeEffectOnSubMeshes) {
  24304. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24305. var subMesh = _c[_b];
  24306. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24307. }
  24308. }
  24309. else {
  24310. this._scene.getEngine()._releaseEffect(this._effect);
  24311. }
  24312. this._effect = null;
  24313. }
  24314. // Callback
  24315. this.onDisposeObservable.notifyObservers(this);
  24316. this.onDisposeObservable.clear();
  24317. this.onBindObservable.clear();
  24318. this.onUnBindObservable.clear();
  24319. };
  24320. Material.prototype.serialize = function () {
  24321. return BABYLON.SerializationHelper.Serialize(this);
  24322. };
  24323. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24324. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24325. multiMaterial.id = parsedMultiMaterial.id;
  24326. if (BABYLON.Tags) {
  24327. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24328. }
  24329. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24330. var subMatId = parsedMultiMaterial.materials[matIndex];
  24331. if (subMatId) {
  24332. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24333. }
  24334. else {
  24335. multiMaterial.subMaterials.push(null);
  24336. }
  24337. }
  24338. return multiMaterial;
  24339. };
  24340. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24341. if (!parsedMaterial.customType) {
  24342. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24343. }
  24344. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  24345. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24346. if (!BABYLON.LegacyPBRMaterial) {
  24347. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24348. return;
  24349. }
  24350. }
  24351. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24352. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24353. ;
  24354. };
  24355. return Material;
  24356. }());
  24357. Material._TriangleFillMode = 0;
  24358. Material._WireFrameFillMode = 1;
  24359. Material._PointFillMode = 2;
  24360. Material._ClockWiseSideOrientation = 0;
  24361. Material._CounterClockWiseSideOrientation = 1;
  24362. Material._TextureDirtyFlag = 1;
  24363. Material._LightDirtyFlag = 2;
  24364. Material._FresnelDirtyFlag = 4;
  24365. Material._AttributesDirtyFlag = 8;
  24366. Material._MiscDirtyFlag = 16;
  24367. __decorate([
  24368. BABYLON.serialize()
  24369. ], Material.prototype, "id", void 0);
  24370. __decorate([
  24371. BABYLON.serialize()
  24372. ], Material.prototype, "name", void 0);
  24373. __decorate([
  24374. BABYLON.serialize()
  24375. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24376. __decorate([
  24377. BABYLON.serialize()
  24378. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24379. __decorate([
  24380. BABYLON.serialize()
  24381. ], Material.prototype, "state", void 0);
  24382. __decorate([
  24383. BABYLON.serialize()
  24384. ], Material.prototype, "alpha", void 0);
  24385. __decorate([
  24386. BABYLON.serialize("backFaceCulling")
  24387. ], Material.prototype, "_backFaceCulling", void 0);
  24388. __decorate([
  24389. BABYLON.serialize()
  24390. ], Material.prototype, "sideOrientation", void 0);
  24391. __decorate([
  24392. BABYLON.serialize()
  24393. ], Material.prototype, "alphaMode", void 0);
  24394. __decorate([
  24395. BABYLON.serialize()
  24396. ], Material.prototype, "disableDepthWrite", void 0);
  24397. __decorate([
  24398. BABYLON.serialize("fogEnabled")
  24399. ], Material.prototype, "_fogEnabled", void 0);
  24400. __decorate([
  24401. BABYLON.serialize()
  24402. ], Material.prototype, "pointSize", void 0);
  24403. __decorate([
  24404. BABYLON.serialize()
  24405. ], Material.prototype, "zOffset", void 0);
  24406. __decorate([
  24407. BABYLON.serialize()
  24408. ], Material.prototype, "wireframe", null);
  24409. __decorate([
  24410. BABYLON.serialize()
  24411. ], Material.prototype, "pointsCloud", null);
  24412. __decorate([
  24413. BABYLON.serialize()
  24414. ], Material.prototype, "fillMode", null);
  24415. BABYLON.Material = Material;
  24416. })(BABYLON || (BABYLON = {}));
  24417. //# sourceMappingURL=babylon.material.js.map
  24418. var BABYLON;
  24419. (function (BABYLON) {
  24420. var UniformBuffer = (function () {
  24421. /**
  24422. * Uniform buffer objects.
  24423. *
  24424. * Handles blocks of uniform on the GPU.
  24425. *
  24426. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24427. *
  24428. * For more information, please refer to :
  24429. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24430. */
  24431. function UniformBuffer(engine, data, dynamic) {
  24432. this._engine = engine;
  24433. this._noUBO = engine.webGLVersion === 1;
  24434. this._dynamic = dynamic;
  24435. this._data = data || [];
  24436. this._uniformLocations = {};
  24437. this._uniformSizes = {};
  24438. this._uniformLocationPointer = 0;
  24439. this._needSync = false;
  24440. if (this._noUBO) {
  24441. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24442. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24443. this.updateFloat = this._updateFloatForEffect;
  24444. this.updateFloat2 = this._updateFloat2ForEffect;
  24445. this.updateFloat3 = this._updateFloat3ForEffect;
  24446. this.updateFloat4 = this._updateFloat4ForEffect;
  24447. this.updateMatrix = this._updateMatrixForEffect;
  24448. this.updateVector3 = this._updateVector3ForEffect;
  24449. this.updateVector4 = this._updateVector4ForEffect;
  24450. this.updateColor3 = this._updateColor3ForEffect;
  24451. this.updateColor4 = this._updateColor4ForEffect;
  24452. }
  24453. else {
  24454. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24455. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24456. this.updateFloat = this._updateFloatForUniform;
  24457. this.updateFloat2 = this._updateFloat2ForUniform;
  24458. this.updateFloat3 = this._updateFloat3ForUniform;
  24459. this.updateFloat4 = this._updateFloat4ForUniform;
  24460. this.updateMatrix = this._updateMatrixForUniform;
  24461. this.updateVector3 = this._updateVector3ForUniform;
  24462. this.updateVector4 = this._updateVector4ForUniform;
  24463. this.updateColor3 = this._updateColor3ForUniform;
  24464. this.updateColor4 = this._updateColor4ForUniform;
  24465. }
  24466. }
  24467. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24468. // Properties
  24469. /**
  24470. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24471. * or just falling back on setUniformXXX calls.
  24472. */
  24473. get: function () {
  24474. return !this._noUBO;
  24475. },
  24476. enumerable: true,
  24477. configurable: true
  24478. });
  24479. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24480. /**
  24481. * Indicates if the WebGL underlying uniform buffer is in sync
  24482. * with the javascript cache data.
  24483. */
  24484. get: function () {
  24485. return !this._needSync;
  24486. },
  24487. enumerable: true,
  24488. configurable: true
  24489. });
  24490. /**
  24491. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24492. * Also, a dynamic UniformBuffer will disable cache verification and always
  24493. * update the underlying WebGL uniform buffer to the GPU.
  24494. */
  24495. UniformBuffer.prototype.isDynamic = function () {
  24496. return this._dynamic;
  24497. };
  24498. /**
  24499. * The data cache on JS side.
  24500. */
  24501. UniformBuffer.prototype.getData = function () {
  24502. return this._bufferData;
  24503. };
  24504. /**
  24505. * The underlying WebGL Uniform buffer.
  24506. */
  24507. UniformBuffer.prototype.getBuffer = function () {
  24508. return this._buffer;
  24509. };
  24510. /**
  24511. * std140 layout specifies how to align data within an UBO structure.
  24512. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24513. * for specs.
  24514. */
  24515. UniformBuffer.prototype._fillAlignment = function (size) {
  24516. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24517. // and 4x4 matrices
  24518. // TODO : change if other types are used
  24519. var alignment;
  24520. if (size <= 2) {
  24521. alignment = size;
  24522. }
  24523. else {
  24524. alignment = 4;
  24525. }
  24526. if ((this._uniformLocationPointer % alignment) !== 0) {
  24527. var oldPointer = this._uniformLocationPointer;
  24528. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24529. var diff = this._uniformLocationPointer - oldPointer;
  24530. for (var i = 0; i < diff; i++) {
  24531. this._data.push(0);
  24532. }
  24533. }
  24534. };
  24535. /**
  24536. * Adds an uniform in the buffer.
  24537. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24538. * for the layout to be correct !
  24539. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24540. * @param {number|number[]} size Data size, or data directly.
  24541. */
  24542. UniformBuffer.prototype.addUniform = function (name, size) {
  24543. if (this._noUBO) {
  24544. return;
  24545. }
  24546. if (this._uniformLocations[name] !== undefined) {
  24547. // Already existing uniform
  24548. return;
  24549. }
  24550. // This function must be called in the order of the shader layout !
  24551. // size can be the size of the uniform, or data directly
  24552. var data;
  24553. if (size instanceof Array) {
  24554. data = size;
  24555. size = data.length;
  24556. }
  24557. else {
  24558. size = size;
  24559. data = [];
  24560. // Fill with zeros
  24561. for (var i = 0; i < size; i++) {
  24562. data.push(0);
  24563. }
  24564. }
  24565. this._fillAlignment(size);
  24566. this._uniformSizes[name] = size;
  24567. this._uniformLocations[name] = this._uniformLocationPointer;
  24568. this._uniformLocationPointer += size;
  24569. for (var i = 0; i < size; i++) {
  24570. this._data.push(data[i]);
  24571. }
  24572. this._needSync = true;
  24573. };
  24574. /**
  24575. * Wrapper for addUniform.
  24576. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24577. * @param {Matrix} mat A 4x4 matrix.
  24578. */
  24579. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24580. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24581. };
  24582. /**
  24583. * Wrapper for addUniform.
  24584. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24585. * @param {number} x
  24586. * @param {number} y
  24587. */
  24588. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24589. var temp = [x, y];
  24590. this.addUniform(name, temp);
  24591. };
  24592. /**
  24593. * Wrapper for addUniform.
  24594. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24595. * @param {number} x
  24596. * @param {number} y
  24597. * @param {number} z
  24598. */
  24599. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24600. var temp = [x, y, z];
  24601. this.addUniform(name, temp);
  24602. };
  24603. /**
  24604. * Wrapper for addUniform.
  24605. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24606. * @param {Color3} color
  24607. */
  24608. UniformBuffer.prototype.addColor3 = function (name, color) {
  24609. var temp = [];
  24610. color.toArray(temp);
  24611. this.addUniform(name, temp);
  24612. };
  24613. /**
  24614. * Wrapper for addUniform.
  24615. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24616. * @param {Color3} color
  24617. * @param {number} alpha
  24618. */
  24619. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24620. var temp = [];
  24621. color.toArray(temp);
  24622. temp.push(alpha);
  24623. this.addUniform(name, temp);
  24624. };
  24625. /**
  24626. * Wrapper for addUniform.
  24627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24628. * @param {Vector3} vector
  24629. */
  24630. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24631. var temp = [];
  24632. vector.toArray(temp);
  24633. this.addUniform(name, temp);
  24634. };
  24635. /**
  24636. * Wrapper for addUniform.
  24637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24638. */
  24639. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24640. this.addUniform(name, 12);
  24641. };
  24642. /**
  24643. * Wrapper for addUniform.
  24644. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24645. */
  24646. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24647. this.addUniform(name, 8);
  24648. };
  24649. /**
  24650. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24651. */
  24652. UniformBuffer.prototype.create = function () {
  24653. if (this._noUBO) {
  24654. return;
  24655. }
  24656. if (this._buffer) {
  24657. return; // nothing to do
  24658. }
  24659. // See spec, alignment must be filled as a vec4
  24660. this._fillAlignment(4);
  24661. this._bufferData = new Float32Array(this._data);
  24662. if (this._dynamic) {
  24663. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24664. }
  24665. else {
  24666. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24667. }
  24668. this._needSync = true;
  24669. };
  24670. /**
  24671. * Updates the WebGL Uniform Buffer on the GPU.
  24672. * If the `dynamic` flag is set to true, no cache comparison is done.
  24673. * Otherwise, the buffer will be updated only if the cache differs.
  24674. */
  24675. UniformBuffer.prototype.update = function () {
  24676. if (!this._buffer) {
  24677. this.create();
  24678. return;
  24679. }
  24680. if (!this._dynamic && !this._needSync) {
  24681. return;
  24682. }
  24683. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24684. this._needSync = false;
  24685. };
  24686. /**
  24687. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24688. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24689. * @param {number[]|Float32Array} data Flattened data
  24690. * @param {number} size Size of the data.
  24691. */
  24692. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24693. var location = this._uniformLocations[uniformName];
  24694. if (location === undefined) {
  24695. if (this._buffer) {
  24696. // Cannot add an uniform if the buffer is already created
  24697. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24698. return;
  24699. }
  24700. this.addUniform(uniformName, size);
  24701. location = this._uniformLocations[uniformName];
  24702. }
  24703. if (!this._buffer) {
  24704. this.create();
  24705. }
  24706. if (!this._dynamic) {
  24707. // Cache for static uniform buffers
  24708. var changed = false;
  24709. for (var i = 0; i < size; i++) {
  24710. if (this._bufferData[location + i] !== data[i]) {
  24711. changed = true;
  24712. this._bufferData[location + i] = data[i];
  24713. }
  24714. }
  24715. this._needSync = this._needSync || changed;
  24716. }
  24717. else {
  24718. // No cache for dynamic
  24719. for (var i = 0; i < size; i++) {
  24720. this._bufferData[location + i] = data[i];
  24721. }
  24722. }
  24723. };
  24724. // Update methods
  24725. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24726. // To match std140, matrix must be realigned
  24727. for (var i = 0; i < 3; i++) {
  24728. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24729. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24730. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24731. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24732. }
  24733. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24734. };
  24735. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24736. this._currentEffect.setMatrix3x3(name, matrix);
  24737. };
  24738. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24739. this._currentEffect.setMatrix2x2(name, matrix);
  24740. };
  24741. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24742. // To match std140, matrix must be realigned
  24743. for (var i = 0; i < 2; i++) {
  24744. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24745. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24746. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24747. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24748. }
  24749. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24750. };
  24751. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24752. this._currentEffect.setFloat(name, x);
  24753. };
  24754. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24755. UniformBuffer._tempBuffer[0] = x;
  24756. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24757. };
  24758. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24759. if (suffix === void 0) { suffix = ""; }
  24760. this._currentEffect.setFloat2(name + suffix, x, y);
  24761. };
  24762. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24763. if (suffix === void 0) { suffix = ""; }
  24764. UniformBuffer._tempBuffer[0] = x;
  24765. UniformBuffer._tempBuffer[1] = y;
  24766. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24767. };
  24768. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24769. if (suffix === void 0) { suffix = ""; }
  24770. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24771. };
  24772. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24773. if (suffix === void 0) { suffix = ""; }
  24774. UniformBuffer._tempBuffer[0] = x;
  24775. UniformBuffer._tempBuffer[1] = y;
  24776. UniformBuffer._tempBuffer[2] = z;
  24777. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24778. };
  24779. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24780. if (suffix === void 0) { suffix = ""; }
  24781. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24782. };
  24783. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24784. if (suffix === void 0) { suffix = ""; }
  24785. UniformBuffer._tempBuffer[0] = x;
  24786. UniformBuffer._tempBuffer[1] = y;
  24787. UniformBuffer._tempBuffer[2] = z;
  24788. UniformBuffer._tempBuffer[3] = w;
  24789. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24790. };
  24791. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24792. this._currentEffect.setMatrix(name, mat);
  24793. };
  24794. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24795. this.updateUniform(name, mat.toArray(), 16);
  24796. };
  24797. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24798. this._currentEffect.setVector3(name, vector);
  24799. };
  24800. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24801. vector.toArray(UniformBuffer._tempBuffer);
  24802. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24803. };
  24804. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24805. this._currentEffect.setVector4(name, vector);
  24806. };
  24807. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24808. vector.toArray(UniformBuffer._tempBuffer);
  24809. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24810. };
  24811. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24812. if (suffix === void 0) { suffix = ""; }
  24813. this._currentEffect.setColor3(name + suffix, color);
  24814. };
  24815. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24816. if (suffix === void 0) { suffix = ""; }
  24817. color.toArray(UniformBuffer._tempBuffer);
  24818. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24819. };
  24820. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24821. if (suffix === void 0) { suffix = ""; }
  24822. this._currentEffect.setColor4(name + suffix, color, alpha);
  24823. };
  24824. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24825. if (suffix === void 0) { suffix = ""; }
  24826. color.toArray(UniformBuffer._tempBuffer);
  24827. UniformBuffer._tempBuffer[3] = alpha;
  24828. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24829. };
  24830. /**
  24831. * Sets a sampler uniform on the effect.
  24832. * @param {string} name Name of the sampler.
  24833. * @param {Texture} texture
  24834. */
  24835. UniformBuffer.prototype.setTexture = function (name, texture) {
  24836. this._currentEffect.setTexture(name, texture);
  24837. };
  24838. /**
  24839. * Directly updates the value of the uniform in the cache AND on the GPU.
  24840. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24841. * @param {number[]|Float32Array} data Flattened data
  24842. */
  24843. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24844. this.updateUniform(uniformName, data, data.length);
  24845. this.update();
  24846. };
  24847. /**
  24848. * Binds this uniform buffer to an effect.
  24849. * @param {Effect} effect
  24850. * @param {string} name Name of the uniform block in the shader.
  24851. */
  24852. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24853. this._currentEffect = effect;
  24854. if (this._noUBO) {
  24855. return;
  24856. }
  24857. effect.bindUniformBuffer(this._buffer, name);
  24858. };
  24859. /**
  24860. * Disposes the uniform buffer.
  24861. */
  24862. UniformBuffer.prototype.dispose = function () {
  24863. if (!this._buffer) {
  24864. return;
  24865. }
  24866. if (this._engine._releaseBuffer(this._buffer)) {
  24867. this._buffer = null;
  24868. }
  24869. };
  24870. return UniformBuffer;
  24871. }());
  24872. // Pool for avoiding memory leaks
  24873. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24874. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24875. BABYLON.UniformBuffer = UniformBuffer;
  24876. })(BABYLON || (BABYLON = {}));
  24877. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24878. var BABYLON;
  24879. (function (BABYLON) {
  24880. var PushMaterial = (function (_super) {
  24881. __extends(PushMaterial, _super);
  24882. function PushMaterial(name, scene) {
  24883. var _this = _super.call(this, name, scene) || this;
  24884. _this.storeEffectOnSubMeshes = true;
  24885. return _this;
  24886. }
  24887. PushMaterial.prototype.getEffect = function () {
  24888. return this._activeEffect;
  24889. };
  24890. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24891. if (!mesh) {
  24892. return false;
  24893. }
  24894. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24895. return true;
  24896. }
  24897. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24898. };
  24899. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24900. this._activeEffect.setMatrix("world", world);
  24901. };
  24902. PushMaterial.prototype.bind = function (world, mesh) {
  24903. if (!mesh) {
  24904. return;
  24905. }
  24906. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24907. };
  24908. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24909. _super.prototype._afterBind.call(this, mesh);
  24910. this.getScene()._cachedEffect = effect;
  24911. };
  24912. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24913. if (visibility === void 0) { visibility = 0; }
  24914. return scene.isCachedMaterialValid(this, effect, visibility);
  24915. };
  24916. return PushMaterial;
  24917. }(BABYLON.Material));
  24918. BABYLON.PushMaterial = PushMaterial;
  24919. })(BABYLON || (BABYLON = {}));
  24920. //# sourceMappingURL=babylon.pushMaterial.js.map
  24921. var BABYLON;
  24922. (function (BABYLON) {
  24923. var VertexData = (function () {
  24924. function VertexData() {
  24925. }
  24926. VertexData.prototype.set = function (data, kind) {
  24927. switch (kind) {
  24928. case BABYLON.VertexBuffer.PositionKind:
  24929. this.positions = data;
  24930. break;
  24931. case BABYLON.VertexBuffer.NormalKind:
  24932. this.normals = data;
  24933. break;
  24934. case BABYLON.VertexBuffer.TangentKind:
  24935. this.tangents = data;
  24936. break;
  24937. case BABYLON.VertexBuffer.UVKind:
  24938. this.uvs = data;
  24939. break;
  24940. case BABYLON.VertexBuffer.UV2Kind:
  24941. this.uvs2 = data;
  24942. break;
  24943. case BABYLON.VertexBuffer.UV3Kind:
  24944. this.uvs3 = data;
  24945. break;
  24946. case BABYLON.VertexBuffer.UV4Kind:
  24947. this.uvs4 = data;
  24948. break;
  24949. case BABYLON.VertexBuffer.UV5Kind:
  24950. this.uvs5 = data;
  24951. break;
  24952. case BABYLON.VertexBuffer.UV6Kind:
  24953. this.uvs6 = data;
  24954. break;
  24955. case BABYLON.VertexBuffer.ColorKind:
  24956. this.colors = data;
  24957. break;
  24958. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24959. this.matricesIndices = data;
  24960. break;
  24961. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24962. this.matricesWeights = data;
  24963. break;
  24964. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24965. this.matricesIndicesExtra = data;
  24966. break;
  24967. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24968. this.matricesWeightsExtra = data;
  24969. break;
  24970. }
  24971. };
  24972. /**
  24973. * Associates the vertexData to the passed Mesh.
  24974. * Sets it as updatable or not (default `false`).
  24975. * Returns the VertexData.
  24976. */
  24977. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24978. this._applyTo(mesh, updatable);
  24979. return this;
  24980. };
  24981. /**
  24982. * Associates the vertexData to the passed Geometry.
  24983. * Sets it as updatable or not (default `false`).
  24984. * Returns the VertexData.
  24985. */
  24986. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24987. this._applyTo(geometry, updatable);
  24988. return this;
  24989. };
  24990. /**
  24991. * Updates the associated mesh.
  24992. * Returns the VertexData.
  24993. */
  24994. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24995. this._update(mesh);
  24996. return this;
  24997. };
  24998. /**
  24999. * Updates the associated geometry.
  25000. * Returns the VertexData.
  25001. */
  25002. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25003. this._update(geometry);
  25004. return this;
  25005. };
  25006. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25007. if (this.positions) {
  25008. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25009. }
  25010. if (this.normals) {
  25011. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25012. }
  25013. if (this.tangents) {
  25014. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  25015. }
  25016. if (this.uvs) {
  25017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25018. }
  25019. if (this.uvs2) {
  25020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25021. }
  25022. if (this.uvs3) {
  25023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25024. }
  25025. if (this.uvs4) {
  25026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25027. }
  25028. if (this.uvs5) {
  25029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25030. }
  25031. if (this.uvs6) {
  25032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25033. }
  25034. if (this.colors) {
  25035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25036. }
  25037. if (this.matricesIndices) {
  25038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25039. }
  25040. if (this.matricesWeights) {
  25041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25042. }
  25043. if (this.matricesIndicesExtra) {
  25044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  25045. }
  25046. if (this.matricesWeightsExtra) {
  25047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  25048. }
  25049. if (this.indices) {
  25050. meshOrGeometry.setIndices(this.indices);
  25051. }
  25052. return this;
  25053. };
  25054. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25055. if (this.positions) {
  25056. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25057. }
  25058. if (this.normals) {
  25059. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25060. }
  25061. if (this.tangents) {
  25062. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  25063. }
  25064. if (this.uvs) {
  25065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25066. }
  25067. if (this.uvs2) {
  25068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25069. }
  25070. if (this.uvs3) {
  25071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25072. }
  25073. if (this.uvs4) {
  25074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25075. }
  25076. if (this.uvs5) {
  25077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25078. }
  25079. if (this.uvs6) {
  25080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25081. }
  25082. if (this.colors) {
  25083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25084. }
  25085. if (this.matricesIndices) {
  25086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25087. }
  25088. if (this.matricesWeights) {
  25089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25090. }
  25091. if (this.matricesIndicesExtra) {
  25092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  25093. }
  25094. if (this.matricesWeightsExtra) {
  25095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  25096. }
  25097. if (this.indices) {
  25098. meshOrGeometry.setIndices(this.indices);
  25099. }
  25100. return this;
  25101. };
  25102. /**
  25103. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  25104. * Returns the VertexData.
  25105. */
  25106. VertexData.prototype.transform = function (matrix) {
  25107. var transformed = BABYLON.Vector3.Zero();
  25108. var index;
  25109. if (this.positions) {
  25110. var position = BABYLON.Vector3.Zero();
  25111. for (index = 0; index < this.positions.length; index += 3) {
  25112. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25113. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25114. this.positions[index] = transformed.x;
  25115. this.positions[index + 1] = transformed.y;
  25116. this.positions[index + 2] = transformed.z;
  25117. }
  25118. }
  25119. if (this.normals) {
  25120. var normal = BABYLON.Vector3.Zero();
  25121. for (index = 0; index < this.normals.length; index += 3) {
  25122. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25123. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25124. this.normals[index] = transformed.x;
  25125. this.normals[index + 1] = transformed.y;
  25126. this.normals[index + 2] = transformed.z;
  25127. }
  25128. }
  25129. if (this.tangents) {
  25130. var tangent = BABYLON.Vector4.Zero();
  25131. var tangentTransformed = BABYLON.Vector4.Zero();
  25132. for (index = 0; index < this.tangents.length; index += 4) {
  25133. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  25134. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  25135. this.tangents[index] = tangentTransformed.x;
  25136. this.tangents[index + 1] = tangentTransformed.y;
  25137. this.tangents[index + 2] = tangentTransformed.z;
  25138. this.tangents[index + 3] = tangentTransformed.w;
  25139. }
  25140. }
  25141. return this;
  25142. };
  25143. /**
  25144. * Merges the passed VertexData into the current one.
  25145. * Returns the modified VertexData.
  25146. */
  25147. VertexData.prototype.merge = function (other) {
  25148. if (other.indices) {
  25149. if (!this.indices) {
  25150. this.indices = [];
  25151. }
  25152. var offset = this.positions ? this.positions.length / 3 : 0;
  25153. for (var index = 0; index < other.indices.length; index++) {
  25154. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  25155. this.indices.push(other.indices[index] + offset);
  25156. }
  25157. }
  25158. this.positions = this._mergeElement(this.positions, other.positions);
  25159. this.normals = this._mergeElement(this.normals, other.normals);
  25160. this.tangents = this._mergeElement(this.tangents, other.tangents);
  25161. this.uvs = this._mergeElement(this.uvs, other.uvs);
  25162. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  25163. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  25164. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  25165. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  25166. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  25167. this.colors = this._mergeElement(this.colors, other.colors);
  25168. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  25169. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  25170. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  25171. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  25172. return this;
  25173. };
  25174. VertexData.prototype._mergeElement = function (source, other) {
  25175. if (!other)
  25176. return source;
  25177. if (!source)
  25178. return other;
  25179. var len = other.length + source.length;
  25180. var isSrcTypedArray = source instanceof Float32Array;
  25181. var isOthTypedArray = other instanceof Float32Array;
  25182. // use non-loop method when the source is Float32Array
  25183. if (isSrcTypedArray) {
  25184. var ret32 = new Float32Array(len);
  25185. ret32.set(source);
  25186. ret32.set(other, source.length);
  25187. return ret32;
  25188. // source is number[], when other is also use concat
  25189. }
  25190. else if (!isOthTypedArray) {
  25191. return source.concat(other);
  25192. // source is a number[], but other is a Float32Array, loop required
  25193. }
  25194. else {
  25195. var ret = source.slice(0); // copy source to a separate array
  25196. for (var i = 0, len = other.length; i < len; i++) {
  25197. ret.push(other[i]);
  25198. }
  25199. return ret;
  25200. }
  25201. };
  25202. /**
  25203. * Serializes the VertexData.
  25204. * Returns a serialized object.
  25205. */
  25206. VertexData.prototype.serialize = function () {
  25207. var serializationObject = this.serialize();
  25208. if (this.positions) {
  25209. serializationObject.positions = this.positions;
  25210. }
  25211. if (this.normals) {
  25212. serializationObject.normals = this.normals;
  25213. }
  25214. if (this.tangents) {
  25215. serializationObject.tangents = this.tangents;
  25216. }
  25217. if (this.uvs) {
  25218. serializationObject.uvs = this.uvs;
  25219. }
  25220. if (this.uvs2) {
  25221. serializationObject.uvs2 = this.uvs2;
  25222. }
  25223. if (this.uvs3) {
  25224. serializationObject.uvs3 = this.uvs3;
  25225. }
  25226. if (this.uvs4) {
  25227. serializationObject.uvs4 = this.uvs4;
  25228. }
  25229. if (this.uvs5) {
  25230. serializationObject.uvs5 = this.uvs5;
  25231. }
  25232. if (this.uvs6) {
  25233. serializationObject.uvs6 = this.uvs6;
  25234. }
  25235. if (this.colors) {
  25236. serializationObject.colors = this.colors;
  25237. }
  25238. if (this.matricesIndices) {
  25239. serializationObject.matricesIndices = this.matricesIndices;
  25240. serializationObject.matricesIndices._isExpanded = true;
  25241. }
  25242. if (this.matricesWeights) {
  25243. serializationObject.matricesWeights = this.matricesWeights;
  25244. }
  25245. if (this.matricesIndicesExtra) {
  25246. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25247. serializationObject.matricesIndicesExtra._isExpanded = true;
  25248. }
  25249. if (this.matricesWeightsExtra) {
  25250. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25251. }
  25252. serializationObject.indices = this.indices;
  25253. return serializationObject;
  25254. };
  25255. // Statics
  25256. /**
  25257. * Returns the object VertexData associated to the passed mesh.
  25258. */
  25259. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25260. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25261. };
  25262. /**
  25263. * Returns the object VertexData associated to the passed geometry.
  25264. */
  25265. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25266. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25267. };
  25268. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25269. var result = new VertexData();
  25270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25271. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25272. }
  25273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25274. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25275. }
  25276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25277. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25278. }
  25279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25280. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25281. }
  25282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25283. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25284. }
  25285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25286. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25287. }
  25288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25289. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25290. }
  25291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25292. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25293. }
  25294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25295. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25296. }
  25297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25298. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25299. }
  25300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25301. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25302. }
  25303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25304. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25305. }
  25306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25307. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25308. }
  25309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25310. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25311. }
  25312. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25313. return result;
  25314. };
  25315. /**
  25316. * Creates the vertexData of the Ribbon.
  25317. */
  25318. VertexData.CreateRibbon = function (options) {
  25319. var pathArray = options.pathArray;
  25320. var closeArray = options.closeArray || false;
  25321. var closePath = options.closePath || false;
  25322. var invertUV = options.invertUV || false;
  25323. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25324. var offset = options.offset || defaultOffset;
  25325. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25326. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25327. var customUV = options.uvs;
  25328. var customColors = options.colors;
  25329. var positions = [];
  25330. var indices = [];
  25331. var normals = [];
  25332. var uvs = [];
  25333. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25334. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25335. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25336. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25337. var minlg; // minimal length among all paths from pathArray
  25338. var lg = []; // array of path lengths : nb of vertex per path
  25339. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25340. var p; // path iterator
  25341. var i; // point iterator
  25342. var j; // point iterator
  25343. // if single path in pathArray
  25344. if (pathArray.length < 2) {
  25345. var ar1 = [];
  25346. var ar2 = [];
  25347. for (i = 0; i < pathArray[0].length - offset; i++) {
  25348. ar1.push(pathArray[0][i]);
  25349. ar2.push(pathArray[0][i + offset]);
  25350. }
  25351. pathArray = [ar1, ar2];
  25352. }
  25353. // positions and horizontal distances (u)
  25354. var idc = 0;
  25355. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25356. var path;
  25357. var l;
  25358. minlg = pathArray[0].length;
  25359. var vectlg;
  25360. var dist;
  25361. for (p = 0; p < pathArray.length; p++) {
  25362. uTotalDistance[p] = 0;
  25363. us[p] = [0];
  25364. path = pathArray[p];
  25365. l = path.length;
  25366. minlg = (minlg < l) ? minlg : l;
  25367. j = 0;
  25368. while (j < l) {
  25369. positions.push(path[j].x, path[j].y, path[j].z);
  25370. if (j > 0) {
  25371. vectlg = path[j].subtract(path[j - 1]).length();
  25372. dist = vectlg + uTotalDistance[p];
  25373. us[p].push(dist);
  25374. uTotalDistance[p] = dist;
  25375. }
  25376. j++;
  25377. }
  25378. if (closePath) {
  25379. j--;
  25380. positions.push(path[0].x, path[0].y, path[0].z);
  25381. vectlg = path[j].subtract(path[0]).length();
  25382. dist = vectlg + uTotalDistance[p];
  25383. us[p].push(dist);
  25384. uTotalDistance[p] = dist;
  25385. }
  25386. lg[p] = l + closePathCorr;
  25387. idx[p] = idc;
  25388. idc += (l + closePathCorr);
  25389. }
  25390. // vertical distances (v)
  25391. var path1;
  25392. var path2;
  25393. var vertex1;
  25394. var vertex2;
  25395. for (i = 0; i < minlg + closePathCorr; i++) {
  25396. vTotalDistance[i] = 0;
  25397. vs[i] = [0];
  25398. for (p = 0; p < pathArray.length - 1; p++) {
  25399. path1 = pathArray[p];
  25400. path2 = pathArray[p + 1];
  25401. if (i === minlg) {
  25402. vertex1 = path1[0];
  25403. vertex2 = path2[0];
  25404. }
  25405. else {
  25406. vertex1 = path1[i];
  25407. vertex2 = path2[i];
  25408. }
  25409. vectlg = vertex2.subtract(vertex1).length();
  25410. dist = vectlg + vTotalDistance[i];
  25411. vs[i].push(dist);
  25412. vTotalDistance[i] = dist;
  25413. }
  25414. if (closeArray) {
  25415. path1 = pathArray[p];
  25416. path2 = pathArray[0];
  25417. if (i === minlg) {
  25418. vertex2 = path2[0];
  25419. }
  25420. vectlg = vertex2.subtract(vertex1).length();
  25421. dist = vectlg + vTotalDistance[i];
  25422. vTotalDistance[i] = dist;
  25423. }
  25424. }
  25425. // uvs
  25426. var u;
  25427. var v;
  25428. if (customUV) {
  25429. for (p = 0; p < customUV.length; p++) {
  25430. uvs.push(customUV[p].x, customUV[p].y);
  25431. }
  25432. }
  25433. else {
  25434. for (p = 0; p < pathArray.length; p++) {
  25435. for (i = 0; i < minlg + closePathCorr; i++) {
  25436. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25437. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25438. if (invertUV) {
  25439. uvs.push(v, u);
  25440. }
  25441. else {
  25442. uvs.push(u, v);
  25443. }
  25444. }
  25445. }
  25446. }
  25447. // indices
  25448. p = 0; // path index
  25449. var pi = 0; // positions array index
  25450. var l1 = lg[p] - 1; // path1 length
  25451. var l2 = lg[p + 1] - 1; // path2 length
  25452. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25453. var shft = idx[1] - idx[0]; // shift
  25454. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25455. while (pi <= min && p < path1nb) {
  25456. // 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
  25457. indices.push(pi, pi + shft, pi + 1);
  25458. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25459. pi += 1;
  25460. if (pi === min) {
  25461. p++;
  25462. if (p === lg.length - 1) {
  25463. shft = idx[0] - idx[p];
  25464. l1 = lg[p] - 1;
  25465. l2 = lg[0] - 1;
  25466. }
  25467. else {
  25468. shft = idx[p + 1] - idx[p];
  25469. l1 = lg[p] - 1;
  25470. l2 = lg[p + 1] - 1;
  25471. }
  25472. pi = idx[p];
  25473. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25474. }
  25475. }
  25476. // normals
  25477. VertexData.ComputeNormals(positions, indices, normals);
  25478. if (closePath) {
  25479. var indexFirst = 0;
  25480. var indexLast = 0;
  25481. for (p = 0; p < pathArray.length; p++) {
  25482. indexFirst = idx[p] * 3;
  25483. if (p + 1 < pathArray.length) {
  25484. indexLast = (idx[p + 1] - 1) * 3;
  25485. }
  25486. else {
  25487. indexLast = normals.length - 3;
  25488. }
  25489. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25490. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25491. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25492. normals[indexLast] = normals[indexFirst];
  25493. normals[indexLast + 1] = normals[indexFirst + 1];
  25494. normals[indexLast + 2] = normals[indexFirst + 2];
  25495. }
  25496. }
  25497. // sides
  25498. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25499. // Colors
  25500. if (customColors) {
  25501. var colors = new Float32Array(customColors.length * 4);
  25502. for (var c = 0; c < customColors.length; c++) {
  25503. colors[c * 4] = customColors[c].r;
  25504. colors[c * 4 + 1] = customColors[c].g;
  25505. colors[c * 4 + 2] = customColors[c].b;
  25506. colors[c * 4 + 3] = customColors[c].a;
  25507. }
  25508. }
  25509. // Result
  25510. var vertexData = new VertexData();
  25511. var positions32 = new Float32Array(positions);
  25512. var normals32 = new Float32Array(normals);
  25513. var uvs32 = new Float32Array(uvs);
  25514. vertexData.indices = indices;
  25515. vertexData.positions = positions32;
  25516. vertexData.normals = normals32;
  25517. vertexData.uvs = uvs32;
  25518. if (customColors) {
  25519. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25520. }
  25521. if (closePath) {
  25522. vertexData._idx = idx;
  25523. }
  25524. return vertexData;
  25525. };
  25526. /**
  25527. * Creates the VertexData of the Box.
  25528. */
  25529. VertexData.CreateBox = function (options) {
  25530. var normalsSource = [
  25531. new BABYLON.Vector3(0, 0, 1),
  25532. new BABYLON.Vector3(0, 0, -1),
  25533. new BABYLON.Vector3(1, 0, 0),
  25534. new BABYLON.Vector3(-1, 0, 0),
  25535. new BABYLON.Vector3(0, 1, 0),
  25536. new BABYLON.Vector3(0, -1, 0)
  25537. ];
  25538. var indices = [];
  25539. var positions = [];
  25540. var normals = [];
  25541. var uvs = [];
  25542. var width = options.width || options.size || 1;
  25543. var height = options.height || options.size || 1;
  25544. var depth = options.depth || options.size || 1;
  25545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25546. var faceUV = options.faceUV || new Array(6);
  25547. var faceColors = options.faceColors;
  25548. var colors = [];
  25549. // default face colors and UV if undefined
  25550. for (var f = 0; f < 6; f++) {
  25551. if (faceUV[f] === undefined) {
  25552. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25553. }
  25554. if (faceColors && faceColors[f] === undefined) {
  25555. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25556. }
  25557. }
  25558. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25559. // Create each face in turn.
  25560. for (var index = 0; index < normalsSource.length; index++) {
  25561. var normal = normalsSource[index];
  25562. // Get two vectors perpendicular to the face normal and to each other.
  25563. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25564. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25565. // Six indices (two triangles) per face.
  25566. var verticesLength = positions.length / 3;
  25567. indices.push(verticesLength);
  25568. indices.push(verticesLength + 1);
  25569. indices.push(verticesLength + 2);
  25570. indices.push(verticesLength);
  25571. indices.push(verticesLength + 2);
  25572. indices.push(verticesLength + 3);
  25573. // Four vertices per face.
  25574. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25575. positions.push(vertex.x, vertex.y, vertex.z);
  25576. normals.push(normal.x, normal.y, normal.z);
  25577. uvs.push(faceUV[index].z, faceUV[index].w);
  25578. if (faceColors) {
  25579. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25580. }
  25581. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25582. positions.push(vertex.x, vertex.y, vertex.z);
  25583. normals.push(normal.x, normal.y, normal.z);
  25584. uvs.push(faceUV[index].x, faceUV[index].w);
  25585. if (faceColors) {
  25586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25587. }
  25588. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25589. positions.push(vertex.x, vertex.y, vertex.z);
  25590. normals.push(normal.x, normal.y, normal.z);
  25591. uvs.push(faceUV[index].x, faceUV[index].y);
  25592. if (faceColors) {
  25593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25594. }
  25595. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25596. positions.push(vertex.x, vertex.y, vertex.z);
  25597. normals.push(normal.x, normal.y, normal.z);
  25598. uvs.push(faceUV[index].z, faceUV[index].y);
  25599. if (faceColors) {
  25600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25601. }
  25602. }
  25603. // sides
  25604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25605. // Result
  25606. var vertexData = new VertexData();
  25607. vertexData.indices = indices;
  25608. vertexData.positions = positions;
  25609. vertexData.normals = normals;
  25610. vertexData.uvs = uvs;
  25611. if (faceColors) {
  25612. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25613. vertexData.colors = totalColors;
  25614. }
  25615. return vertexData;
  25616. };
  25617. /**
  25618. * Creates the VertexData of the Sphere.
  25619. */
  25620. VertexData.CreateSphere = function (options) {
  25621. var segments = options.segments || 32;
  25622. var diameterX = options.diameterX || options.diameter || 1;
  25623. var diameterY = options.diameterY || options.diameter || 1;
  25624. var diameterZ = options.diameterZ || options.diameter || 1;
  25625. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25626. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25627. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25628. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25629. var totalZRotationSteps = 2 + segments;
  25630. var totalYRotationSteps = 2 * totalZRotationSteps;
  25631. var indices = [];
  25632. var positions = [];
  25633. var normals = [];
  25634. var uvs = [];
  25635. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25636. var normalizedZ = zRotationStep / totalZRotationSteps;
  25637. var angleZ = normalizedZ * Math.PI * slice;
  25638. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25639. var normalizedY = yRotationStep / totalYRotationSteps;
  25640. var angleY = normalizedY * Math.PI * 2 * arc;
  25641. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25642. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25643. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25644. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25645. var vertex = complete.multiply(radius);
  25646. var normal = complete.divide(radius).normalize();
  25647. positions.push(vertex.x, vertex.y, vertex.z);
  25648. normals.push(normal.x, normal.y, normal.z);
  25649. uvs.push(normalizedY, normalizedZ);
  25650. }
  25651. if (zRotationStep > 0) {
  25652. var verticesCount = positions.length / 3;
  25653. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25654. indices.push((firstIndex));
  25655. indices.push((firstIndex + 1));
  25656. indices.push(firstIndex + totalYRotationSteps + 1);
  25657. indices.push((firstIndex + totalYRotationSteps + 1));
  25658. indices.push((firstIndex + 1));
  25659. indices.push((firstIndex + totalYRotationSteps + 2));
  25660. }
  25661. }
  25662. }
  25663. // Sides
  25664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25665. // Result
  25666. var vertexData = new VertexData();
  25667. vertexData.indices = indices;
  25668. vertexData.positions = positions;
  25669. vertexData.normals = normals;
  25670. vertexData.uvs = uvs;
  25671. return vertexData;
  25672. };
  25673. /**
  25674. * Creates the VertexData of the Cylinder or Cone.
  25675. */
  25676. VertexData.CreateCylinder = function (options) {
  25677. var height = options.height || 2;
  25678. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25679. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25680. var tessellation = options.tessellation || 24;
  25681. var subdivisions = options.subdivisions || 1;
  25682. var hasRings = options.hasRings;
  25683. var enclose = options.enclose;
  25684. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25685. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25686. var faceUV = options.faceUV || new Array(3);
  25687. var faceColors = options.faceColors;
  25688. // default face colors and UV if undefined
  25689. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25690. var ringNb = (hasRings) ? subdivisions : 1;
  25691. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25692. var f;
  25693. for (f = 0; f < surfaceNb; f++) {
  25694. if (faceColors && faceColors[f] === undefined) {
  25695. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25696. }
  25697. }
  25698. for (f = 0; f < surfaceNb; f++) {
  25699. if (faceUV && faceUV[f] === undefined) {
  25700. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25701. }
  25702. }
  25703. var indices = [];
  25704. var positions = [];
  25705. var normals = [];
  25706. var uvs = [];
  25707. var colors = [];
  25708. var angle_step = Math.PI * 2 * arc / tessellation;
  25709. var angle;
  25710. var h;
  25711. var radius;
  25712. var tan = (diameterBottom - diameterTop) / 2 / height;
  25713. var ringVertex = BABYLON.Vector3.Zero();
  25714. var ringNormal = BABYLON.Vector3.Zero();
  25715. var ringFirstVertex = BABYLON.Vector3.Zero();
  25716. var ringFirstNormal = BABYLON.Vector3.Zero();
  25717. var quadNormal = BABYLON.Vector3.Zero();
  25718. var Y = BABYLON.Axis.Y;
  25719. // positions, normals, uvs
  25720. var i;
  25721. var j;
  25722. var r;
  25723. var ringIdx = 1;
  25724. var s = 1; // surface index
  25725. var cs = 0;
  25726. var v = 0;
  25727. for (i = 0; i <= subdivisions; i++) {
  25728. h = i / subdivisions;
  25729. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25730. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25731. for (r = 0; r < ringIdx; r++) {
  25732. if (hasRings) {
  25733. s += r;
  25734. }
  25735. if (enclose) {
  25736. s += 2 * r;
  25737. }
  25738. for (j = 0; j <= tessellation; j++) {
  25739. angle = j * angle_step;
  25740. // position
  25741. ringVertex.x = Math.cos(-angle) * radius;
  25742. ringVertex.y = -height / 2 + h * height;
  25743. ringVertex.z = Math.sin(-angle) * radius;
  25744. // normal
  25745. if (diameterTop === 0 && i === subdivisions) {
  25746. // if no top cap, reuse former normals
  25747. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25748. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25749. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25750. }
  25751. else {
  25752. ringNormal.x = ringVertex.x;
  25753. ringNormal.z = ringVertex.z;
  25754. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25755. ringNormal.normalize();
  25756. }
  25757. // keep first ring vertex values for enclose
  25758. if (j === 0) {
  25759. ringFirstVertex.copyFrom(ringVertex);
  25760. ringFirstNormal.copyFrom(ringNormal);
  25761. }
  25762. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25763. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25764. if (hasRings) {
  25765. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25766. }
  25767. else {
  25768. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25769. }
  25770. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25771. if (faceColors) {
  25772. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25773. }
  25774. }
  25775. // if enclose, add four vertices and their dedicated normals
  25776. if (arc !== 1 && enclose) {
  25777. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25778. positions.push(0, ringVertex.y, 0);
  25779. positions.push(0, ringVertex.y, 0);
  25780. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25781. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25782. quadNormal.normalize();
  25783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25784. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25785. quadNormal.normalize();
  25786. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25787. if (hasRings) {
  25788. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25789. }
  25790. else {
  25791. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25792. }
  25793. uvs.push(faceUV[s + 1].x, v);
  25794. uvs.push(faceUV[s + 1].z, v);
  25795. if (hasRings) {
  25796. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25797. }
  25798. else {
  25799. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25800. }
  25801. uvs.push(faceUV[s + 2].x, v);
  25802. uvs.push(faceUV[s + 2].z, v);
  25803. if (faceColors) {
  25804. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25805. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25806. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25807. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25808. }
  25809. }
  25810. if (cs !== s) {
  25811. cs = s;
  25812. }
  25813. }
  25814. }
  25815. // indices
  25816. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25817. var s;
  25818. i = 0;
  25819. for (s = 0; s < subdivisions; s++) {
  25820. for (j = 0; j < tessellation; j++) {
  25821. var i0 = i * (e + 1) + j;
  25822. var i1 = (i + 1) * (e + 1) + j;
  25823. var i2 = i * (e + 1) + (j + 1);
  25824. var i3 = (i + 1) * (e + 1) + (j + 1);
  25825. indices.push(i0, i1, i2);
  25826. indices.push(i3, i2, i1);
  25827. }
  25828. if (arc !== 1 && enclose) {
  25829. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25830. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25831. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25832. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25833. }
  25834. i = (hasRings) ? (i + 2) : (i + 1);
  25835. }
  25836. // Caps
  25837. var createCylinderCap = function (isTop) {
  25838. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25839. if (radius === 0) {
  25840. return;
  25841. }
  25842. // Cap positions, normals & uvs
  25843. var angle;
  25844. var circleVector;
  25845. var i;
  25846. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25847. var c;
  25848. if (faceColors) {
  25849. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25850. }
  25851. // cap center
  25852. var vbase = positions.length / 3;
  25853. var offset = isTop ? height / 2 : -height / 2;
  25854. var center = new BABYLON.Vector3(0, offset, 0);
  25855. positions.push(center.x, center.y, center.z);
  25856. normals.push(0, isTop ? 1 : -1, 0);
  25857. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25858. if (faceColors) {
  25859. colors.push(c.r, c.g, c.b, c.a);
  25860. }
  25861. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25862. for (i = 0; i <= tessellation; i++) {
  25863. angle = Math.PI * 2 * i * arc / tessellation;
  25864. var cos = Math.cos(-angle);
  25865. var sin = Math.sin(-angle);
  25866. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25867. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25868. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25869. normals.push(0, isTop ? 1 : -1, 0);
  25870. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25871. if (faceColors) {
  25872. colors.push(c.r, c.g, c.b, c.a);
  25873. }
  25874. }
  25875. // Cap indices
  25876. for (i = 0; i < tessellation; i++) {
  25877. if (!isTop) {
  25878. indices.push(vbase);
  25879. indices.push(vbase + (i + 1));
  25880. indices.push(vbase + (i + 2));
  25881. }
  25882. else {
  25883. indices.push(vbase);
  25884. indices.push(vbase + (i + 2));
  25885. indices.push(vbase + (i + 1));
  25886. }
  25887. }
  25888. };
  25889. // add caps to geometry
  25890. createCylinderCap(false);
  25891. createCylinderCap(true);
  25892. // Sides
  25893. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25894. var vertexData = new VertexData();
  25895. vertexData.indices = indices;
  25896. vertexData.positions = positions;
  25897. vertexData.normals = normals;
  25898. vertexData.uvs = uvs;
  25899. if (faceColors) {
  25900. vertexData.colors = colors;
  25901. }
  25902. return vertexData;
  25903. };
  25904. /**
  25905. * Creates the VertexData of the Torus.
  25906. */
  25907. VertexData.CreateTorus = function (options) {
  25908. var indices = [];
  25909. var positions = [];
  25910. var normals = [];
  25911. var uvs = [];
  25912. var diameter = options.diameter || 1;
  25913. var thickness = options.thickness || 0.5;
  25914. var tessellation = options.tessellation || 16;
  25915. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25916. var stride = tessellation + 1;
  25917. for (var i = 0; i <= tessellation; i++) {
  25918. var u = i / tessellation;
  25919. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25920. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25921. for (var j = 0; j <= tessellation; j++) {
  25922. var v = 1 - j / tessellation;
  25923. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25924. var dx = Math.cos(innerAngle);
  25925. var dy = Math.sin(innerAngle);
  25926. // Create a vertex.
  25927. var normal = new BABYLON.Vector3(dx, dy, 0);
  25928. var position = normal.scale(thickness / 2);
  25929. var textureCoordinate = new BABYLON.Vector2(u, v);
  25930. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25931. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25932. positions.push(position.x, position.y, position.z);
  25933. normals.push(normal.x, normal.y, normal.z);
  25934. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25935. // And create indices for two triangles.
  25936. var nextI = (i + 1) % stride;
  25937. var nextJ = (j + 1) % stride;
  25938. indices.push(i * stride + j);
  25939. indices.push(i * stride + nextJ);
  25940. indices.push(nextI * stride + j);
  25941. indices.push(i * stride + nextJ);
  25942. indices.push(nextI * stride + nextJ);
  25943. indices.push(nextI * stride + j);
  25944. }
  25945. }
  25946. // Sides
  25947. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25948. // Result
  25949. var vertexData = new VertexData();
  25950. vertexData.indices = indices;
  25951. vertexData.positions = positions;
  25952. vertexData.normals = normals;
  25953. vertexData.uvs = uvs;
  25954. return vertexData;
  25955. };
  25956. /**
  25957. * Creates the VertexData of the LineSystem.
  25958. */
  25959. VertexData.CreateLineSystem = function (options) {
  25960. var indices = [];
  25961. var positions = [];
  25962. var lines = options.lines;
  25963. var idx = 0;
  25964. for (var l = 0; l < lines.length; l++) {
  25965. var points = lines[l];
  25966. for (var index = 0; index < points.length; index++) {
  25967. positions.push(points[index].x, points[index].y, points[index].z);
  25968. if (index > 0) {
  25969. indices.push(idx - 1);
  25970. indices.push(idx);
  25971. }
  25972. idx++;
  25973. }
  25974. }
  25975. var vertexData = new VertexData();
  25976. vertexData.indices = indices;
  25977. vertexData.positions = positions;
  25978. return vertexData;
  25979. };
  25980. /**
  25981. * Create the VertexData of the DashedLines.
  25982. */
  25983. VertexData.CreateDashedLines = function (options) {
  25984. var dashSize = options.dashSize || 3;
  25985. var gapSize = options.gapSize || 1;
  25986. var dashNb = options.dashNb || 200;
  25987. var points = options.points;
  25988. var positions = new Array();
  25989. var indices = new Array();
  25990. var curvect = BABYLON.Vector3.Zero();
  25991. var lg = 0;
  25992. var nb = 0;
  25993. var shft = 0;
  25994. var dashshft = 0;
  25995. var curshft = 0;
  25996. var idx = 0;
  25997. var i = 0;
  25998. for (i = 0; i < points.length - 1; i++) {
  25999. points[i + 1].subtractToRef(points[i], curvect);
  26000. lg += curvect.length();
  26001. }
  26002. shft = lg / dashNb;
  26003. dashshft = dashSize * shft / (dashSize + gapSize);
  26004. for (i = 0; i < points.length - 1; i++) {
  26005. points[i + 1].subtractToRef(points[i], curvect);
  26006. nb = Math.floor(curvect.length() / shft);
  26007. curvect.normalize();
  26008. for (var j = 0; j < nb; j++) {
  26009. curshft = shft * j;
  26010. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26011. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26012. indices.push(idx, idx + 1);
  26013. idx += 2;
  26014. }
  26015. }
  26016. // Result
  26017. var vertexData = new VertexData();
  26018. vertexData.positions = positions;
  26019. vertexData.indices = indices;
  26020. return vertexData;
  26021. };
  26022. /**
  26023. * Creates the VertexData of the Ground.
  26024. */
  26025. VertexData.CreateGround = function (options) {
  26026. var indices = [];
  26027. var positions = [];
  26028. var normals = [];
  26029. var uvs = [];
  26030. var row, col;
  26031. var width = options.width || 1;
  26032. var height = options.height || 1;
  26033. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  26034. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  26035. for (row = 0; row <= subdivisionsY; row++) {
  26036. for (col = 0; col <= subdivisionsX; col++) {
  26037. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  26038. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26039. positions.push(position.x, position.y, position.z);
  26040. normals.push(normal.x, normal.y, normal.z);
  26041. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  26042. }
  26043. }
  26044. for (row = 0; row < subdivisionsY; row++) {
  26045. for (col = 0; col < subdivisionsX; col++) {
  26046. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26047. indices.push(col + 1 + row * (subdivisionsX + 1));
  26048. indices.push(col + row * (subdivisionsX + 1));
  26049. indices.push(col + (row + 1) * (subdivisionsX + 1));
  26050. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  26051. indices.push(col + row * (subdivisionsX + 1));
  26052. }
  26053. }
  26054. // Result
  26055. var vertexData = new VertexData();
  26056. vertexData.indices = indices;
  26057. vertexData.positions = positions;
  26058. vertexData.normals = normals;
  26059. vertexData.uvs = uvs;
  26060. return vertexData;
  26061. };
  26062. /**
  26063. * Creates the VertexData of the TiledGround.
  26064. */
  26065. VertexData.CreateTiledGround = function (options) {
  26066. var xmin = options.xmin || -1.0;
  26067. var zmin = options.zmin || -1.0;
  26068. var xmax = options.xmax || 1.0;
  26069. var zmax = options.zmax || 1.0;
  26070. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  26071. var precision = options.precision || { w: 1, h: 1 };
  26072. var indices = [];
  26073. var positions = [];
  26074. var normals = [];
  26075. var uvs = [];
  26076. var row, col, tileRow, tileCol;
  26077. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  26078. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26079. precision.w = (precision.w < 1) ? 1 : precision.w;
  26080. precision.h = (precision.h < 1) ? 1 : precision.h;
  26081. var tileSize = {
  26082. 'w': (xmax - xmin) / subdivisions.w,
  26083. 'h': (zmax - zmin) / subdivisions.h
  26084. };
  26085. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26086. // Indices
  26087. var base = positions.length / 3;
  26088. var rowLength = precision.w + 1;
  26089. for (row = 0; row < precision.h; row++) {
  26090. for (col = 0; col < precision.w; col++) {
  26091. var square = [
  26092. base + col + row * rowLength,
  26093. base + (col + 1) + row * rowLength,
  26094. base + (col + 1) + (row + 1) * rowLength,
  26095. base + col + (row + 1) * rowLength
  26096. ];
  26097. indices.push(square[1]);
  26098. indices.push(square[2]);
  26099. indices.push(square[3]);
  26100. indices.push(square[0]);
  26101. indices.push(square[1]);
  26102. indices.push(square[3]);
  26103. }
  26104. }
  26105. // Position, normals and uvs
  26106. var position = BABYLON.Vector3.Zero();
  26107. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26108. for (row = 0; row <= precision.h; row++) {
  26109. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26110. for (col = 0; col <= precision.w; col++) {
  26111. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26112. position.y = 0;
  26113. positions.push(position.x, position.y, position.z);
  26114. normals.push(normal.x, normal.y, normal.z);
  26115. uvs.push(col / precision.w, row / precision.h);
  26116. }
  26117. }
  26118. }
  26119. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26120. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26121. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26122. }
  26123. }
  26124. // Result
  26125. var vertexData = new VertexData();
  26126. vertexData.indices = indices;
  26127. vertexData.positions = positions;
  26128. vertexData.normals = normals;
  26129. vertexData.uvs = uvs;
  26130. return vertexData;
  26131. };
  26132. /**
  26133. * Creates the VertexData of the Ground designed from a heightmap.
  26134. */
  26135. VertexData.CreateGroundFromHeightMap = function (options) {
  26136. var indices = [];
  26137. var positions = [];
  26138. var normals = [];
  26139. var uvs = [];
  26140. var row, col;
  26141. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  26142. // Vertices
  26143. for (row = 0; row <= options.subdivisions; row++) {
  26144. for (col = 0; col <= options.subdivisions; col++) {
  26145. 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));
  26146. // Compute height
  26147. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  26148. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  26149. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  26150. var r = options.buffer[pos] / 255.0;
  26151. var g = options.buffer[pos + 1] / 255.0;
  26152. var b = options.buffer[pos + 2] / 255.0;
  26153. var gradient = r * filter.r + g * filter.g + b * filter.b;
  26154. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  26155. // Add vertex
  26156. positions.push(position.x, position.y, position.z);
  26157. normals.push(0, 0, 0);
  26158. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  26159. }
  26160. }
  26161. // Indices
  26162. for (row = 0; row < options.subdivisions; row++) {
  26163. for (col = 0; col < options.subdivisions; col++) {
  26164. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26165. indices.push(col + 1 + row * (options.subdivisions + 1));
  26166. indices.push(col + row * (options.subdivisions + 1));
  26167. indices.push(col + (row + 1) * (options.subdivisions + 1));
  26168. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  26169. indices.push(col + row * (options.subdivisions + 1));
  26170. }
  26171. }
  26172. // Normals
  26173. VertexData.ComputeNormals(positions, indices, normals);
  26174. // Result
  26175. var vertexData = new VertexData();
  26176. vertexData.indices = indices;
  26177. vertexData.positions = positions;
  26178. vertexData.normals = normals;
  26179. vertexData.uvs = uvs;
  26180. return vertexData;
  26181. };
  26182. /**
  26183. * Creates the VertexData of the Plane.
  26184. */
  26185. VertexData.CreatePlane = function (options) {
  26186. var indices = [];
  26187. var positions = [];
  26188. var normals = [];
  26189. var uvs = [];
  26190. var width = options.width || options.size || 1;
  26191. var height = options.height || options.size || 1;
  26192. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26193. // Vertices
  26194. var halfWidth = width / 2.0;
  26195. var halfHeight = height / 2.0;
  26196. positions.push(-halfWidth, -halfHeight, 0);
  26197. normals.push(0, 0, -1.0);
  26198. uvs.push(0.0, 0.0);
  26199. positions.push(halfWidth, -halfHeight, 0);
  26200. normals.push(0, 0, -1.0);
  26201. uvs.push(1.0, 0.0);
  26202. positions.push(halfWidth, halfHeight, 0);
  26203. normals.push(0, 0, -1.0);
  26204. uvs.push(1.0, 1.0);
  26205. positions.push(-halfWidth, halfHeight, 0);
  26206. normals.push(0, 0, -1.0);
  26207. uvs.push(0.0, 1.0);
  26208. // Indices
  26209. indices.push(0);
  26210. indices.push(1);
  26211. indices.push(2);
  26212. indices.push(0);
  26213. indices.push(2);
  26214. indices.push(3);
  26215. // Sides
  26216. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26217. // Result
  26218. var vertexData = new VertexData();
  26219. vertexData.indices = indices;
  26220. vertexData.positions = positions;
  26221. vertexData.normals = normals;
  26222. vertexData.uvs = uvs;
  26223. return vertexData;
  26224. };
  26225. /**
  26226. * Creates the VertexData of the Disc or regular Polygon.
  26227. */
  26228. VertexData.CreateDisc = function (options) {
  26229. var positions = [];
  26230. var indices = [];
  26231. var normals = [];
  26232. var uvs = [];
  26233. var radius = options.radius || 0.5;
  26234. var tessellation = options.tessellation || 64;
  26235. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26236. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26237. // positions and uvs
  26238. positions.push(0, 0, 0); // disc center first
  26239. uvs.push(0.5, 0.5);
  26240. var theta = Math.PI * 2 * arc;
  26241. var step = theta / tessellation;
  26242. for (var a = 0; a < theta; a += step) {
  26243. var x = Math.cos(a);
  26244. var y = Math.sin(a);
  26245. var u = (x + 1) / 2;
  26246. var v = (1 - y) / 2;
  26247. positions.push(radius * x, radius * y, 0);
  26248. uvs.push(u, v);
  26249. }
  26250. if (arc === 1) {
  26251. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26252. uvs.push(uvs[2], uvs[3]);
  26253. }
  26254. //indices
  26255. var vertexNb = positions.length / 3;
  26256. for (var i = 1; i < vertexNb - 1; i++) {
  26257. indices.push(i + 1, 0, i);
  26258. }
  26259. // result
  26260. VertexData.ComputeNormals(positions, indices, normals);
  26261. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26262. var vertexData = new VertexData();
  26263. vertexData.indices = indices;
  26264. vertexData.positions = positions;
  26265. vertexData.normals = normals;
  26266. vertexData.uvs = uvs;
  26267. return vertexData;
  26268. };
  26269. /**
  26270. * Re-creates the VertexData of the Polygon for sideOrientation.
  26271. */
  26272. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26273. var faceUV = fUV || new Array(3);
  26274. var faceColors = fColors;
  26275. var colors = [];
  26276. // default face colors and UV if undefined
  26277. for (var f = 0; f < 3; f++) {
  26278. if (faceUV[f] === undefined) {
  26279. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26280. }
  26281. if (faceColors && faceColors[f] === undefined) {
  26282. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26283. }
  26284. }
  26285. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26286. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26287. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26288. var indices = polygon.getIndices();
  26289. // set face colours and textures
  26290. var idx = 0;
  26291. var face = 0;
  26292. for (var index = 0; index < normals.length; index += 3) {
  26293. //Edge Face no. 1
  26294. if (Math.abs(normals[index + 1]) == 0) {
  26295. face = 1;
  26296. }
  26297. //Top Face no. 0
  26298. if (normals[index + 1] == 1) {
  26299. face = 0;
  26300. }
  26301. //Bottom Face no. 2
  26302. if (normals[index + 1] == -1) {
  26303. face = 2;
  26304. }
  26305. idx = index / 3;
  26306. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26307. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26308. if (faceColors) {
  26309. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26310. }
  26311. }
  26312. // sides
  26313. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26314. // Result
  26315. var vertexData = new VertexData();
  26316. vertexData.indices = indices;
  26317. vertexData.positions = positions;
  26318. vertexData.normals = normals;
  26319. vertexData.uvs = uvs;
  26320. if (faceColors) {
  26321. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26322. vertexData.colors = totalColors;
  26323. }
  26324. return vertexData;
  26325. };
  26326. /**
  26327. * Creates the VertexData of the IcoSphere.
  26328. */
  26329. VertexData.CreateIcoSphere = function (options) {
  26330. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26331. var radius = options.radius || 1;
  26332. var flat = (options.flat === undefined) ? true : options.flat;
  26333. var subdivisions = options.subdivisions || 4;
  26334. var radiusX = options.radiusX || radius;
  26335. var radiusY = options.radiusY || radius;
  26336. var radiusZ = options.radiusZ || radius;
  26337. var t = (1 + Math.sqrt(5)) / 2;
  26338. // 12 vertex x,y,z
  26339. var ico_vertices = [
  26340. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26341. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26342. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26343. ];
  26344. // index of 3 vertex makes a face of icopshere
  26345. var ico_indices = [
  26346. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26347. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26348. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26349. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26350. ];
  26351. // vertex for uv have aliased position, not for UV
  26352. var vertices_unalias_id = [
  26353. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26354. // vertex alias
  26355. 0,
  26356. 2,
  26357. 3,
  26358. 3,
  26359. 3,
  26360. 4,
  26361. 7,
  26362. 8,
  26363. 9,
  26364. 9,
  26365. 10,
  26366. 11 // 23: B + 12
  26367. ];
  26368. // uv as integer step (not pixels !)
  26369. var ico_vertexuv = [
  26370. 5, 1, 3, 1, 6, 4, 0, 0,
  26371. 5, 3, 4, 2, 2, 2, 4, 0,
  26372. 2, 0, 1, 1, 6, 0, 6, 2,
  26373. // vertex alias (for same vertex on different faces)
  26374. 0, 4,
  26375. 3, 3,
  26376. 4, 4,
  26377. 3, 1,
  26378. 4, 2,
  26379. 4, 4,
  26380. 0, 2,
  26381. 1, 1,
  26382. 2, 2,
  26383. 3, 3,
  26384. 1, 3,
  26385. 2, 4 // 23: B + 12
  26386. ];
  26387. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26388. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26389. // First island of uv mapping
  26390. // v = 4h 3+ 2
  26391. // v = 3h 9+ 4
  26392. // v = 2h 9+ 5 B
  26393. // v = 1h 9 1 0
  26394. // v = 0h 3 8 7 A
  26395. // u = 0 1 2 3 4 5 6 *a
  26396. // Second island of uv mapping
  26397. // v = 4h 0+ B+ 4+
  26398. // v = 3h A+ 2+
  26399. // v = 2h 7+ 6 3+
  26400. // v = 1h 8+ 3+
  26401. // v = 0h
  26402. // u = 0 1 2 3 4 5 6 *a
  26403. // Face layout on texture UV mapping
  26404. // ============
  26405. // \ 4 /\ 16 / ======
  26406. // \ / \ / /\ 11 /
  26407. // \/ 7 \/ / \ /
  26408. // ======= / 10 \/
  26409. // /\ 17 /\ =======
  26410. // / \ / \ \ 15 /\
  26411. // / 8 \/ 12 \ \ / \
  26412. // ============ \/ 6 \
  26413. // \ 18 /\ ============
  26414. // \ / \ \ 5 /\ 0 /
  26415. // \/ 13 \ \ / \ /
  26416. // ======= \/ 1 \/
  26417. // =============
  26418. // /\ 19 /\ 2 /\
  26419. // / \ / \ / \
  26420. // / 14 \/ 9 \/ 3 \
  26421. // ===================
  26422. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26423. var ustep = 138 / 1024;
  26424. var vstep = 239 / 1024;
  26425. var uoffset = 60 / 1024;
  26426. var voffset = 26 / 1024;
  26427. // Second island should have margin, not to touch the first island
  26428. // avoid any borderline artefact in pixel rounding
  26429. var island_u_offset = -40 / 1024;
  26430. var island_v_offset = +20 / 1024;
  26431. // face is either island 0 or 1 :
  26432. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26433. var island = [
  26434. 0, 0, 0, 0, 1,
  26435. 0, 0, 1, 1, 0,
  26436. 0, 0, 1, 1, 0,
  26437. 0, 1, 1, 1, 0 // 15 - 19
  26438. ];
  26439. var indices = [];
  26440. var positions = [];
  26441. var normals = [];
  26442. var uvs = [];
  26443. var current_indice = 0;
  26444. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26445. var face_vertex_pos = new Array(3);
  26446. var face_vertex_uv = new Array(3);
  26447. var v012;
  26448. for (v012 = 0; v012 < 3; v012++) {
  26449. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26450. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26451. }
  26452. // create all with normals
  26453. for (var face = 0; face < 20; face++) {
  26454. // 3 vertex per face
  26455. for (v012 = 0; v012 < 3; v012++) {
  26456. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26457. var v_id = ico_indices[3 * face + v012];
  26458. // vertex have 3D position (x,y,z)
  26459. 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]);
  26460. // Normalize to get normal, then scale to radius
  26461. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26462. // uv Coordinates from vertex ID
  26463. 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);
  26464. }
  26465. // Subdivide the face (interpolate pos, norm, uv)
  26466. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26467. // - norm is linear interpolation of vertex corner normal
  26468. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26469. // - uv is linear interpolation
  26470. //
  26471. // Topology is as below for sub-divide by 2
  26472. // vertex shown as v0,v1,v2
  26473. // interp index is i1 to progress in range [v0,v1[
  26474. // interp index is i2 to progress in range [v0,v2[
  26475. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26476. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26477. //
  26478. //
  26479. // i2 v2
  26480. // ^ ^
  26481. // / / \
  26482. // / / \
  26483. // / / \
  26484. // / / (0,1) \
  26485. // / #---------\
  26486. // / / \ (0,0)'/ \
  26487. // / / \ / \
  26488. // / / \ / \
  26489. // / / (0,0) \ / (1,0) \
  26490. // / #---------#---------\
  26491. // v0 v1
  26492. //
  26493. // --------------------> i1
  26494. //
  26495. // interp of (i1,i2):
  26496. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26497. // along i1 : lerp(x0,x1, i1/(S-i2))
  26498. //
  26499. // centroid of triangle is needed to get help normal computation
  26500. // (c1,c2) are used for centroid location
  26501. var interp_vertex = function (i1, i2, c1, c2) {
  26502. // vertex is interpolated from
  26503. // - face_vertex_pos[0..2]
  26504. // - face_vertex_uv[0..2]
  26505. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26506. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26507. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26508. pos_interp.normalize();
  26509. var vertex_normal;
  26510. if (flat) {
  26511. // in flat mode, recalculate normal as face centroid normal
  26512. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26513. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26514. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26515. }
  26516. else {
  26517. // in smooth mode, recalculate normal from each single vertex position
  26518. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26519. }
  26520. // Vertex normal need correction due to X,Y,Z radius scaling
  26521. vertex_normal.x /= radiusX;
  26522. vertex_normal.y /= radiusY;
  26523. vertex_normal.z /= radiusZ;
  26524. vertex_normal.normalize();
  26525. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26526. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26527. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26528. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26529. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26530. uvs.push(uv_interp.x, uv_interp.y);
  26531. // push each vertex has member of a face
  26532. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26533. indices.push(current_indice);
  26534. current_indice++;
  26535. };
  26536. for (var i2 = 0; i2 < subdivisions; i2++) {
  26537. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26538. // face : (i1,i2) for /\ :
  26539. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26540. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26541. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26542. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26543. if (i1 + i2 + 1 < subdivisions) {
  26544. // face : (i1,i2)' for \/ :
  26545. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26546. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26547. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26548. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26549. }
  26550. }
  26551. }
  26552. }
  26553. // Sides
  26554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26555. // Result
  26556. var vertexData = new VertexData();
  26557. vertexData.indices = indices;
  26558. vertexData.positions = positions;
  26559. vertexData.normals = normals;
  26560. vertexData.uvs = uvs;
  26561. return vertexData;
  26562. };
  26563. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26564. /**
  26565. * Creates the VertexData of the Polyhedron.
  26566. */
  26567. VertexData.CreatePolyhedron = function (options) {
  26568. // provided polyhedron types :
  26569. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26570. // 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)
  26571. var polyhedra = [];
  26572. 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]] };
  26573. 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]] };
  26574. polyhedra[2] = {
  26575. 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]],
  26576. 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]]
  26577. };
  26578. polyhedra[3] = {
  26579. 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]],
  26580. 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]]
  26581. };
  26582. polyhedra[4] = {
  26583. 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]],
  26584. 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]]
  26585. };
  26586. 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]] };
  26587. 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]] };
  26588. 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]] };
  26589. 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]] };
  26590. 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]] };
  26591. 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]] };
  26592. 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]] };
  26593. 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]] };
  26594. 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]] };
  26595. polyhedra[14] = {
  26596. 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]],
  26597. 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]]
  26598. };
  26599. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26600. var size = options.size;
  26601. var sizeX = options.sizeX || size || 1;
  26602. var sizeY = options.sizeY || size || 1;
  26603. var sizeZ = options.sizeZ || size || 1;
  26604. var data = options.custom || polyhedra[type];
  26605. var nbfaces = data.face.length;
  26606. var faceUV = options.faceUV || new Array(nbfaces);
  26607. var faceColors = options.faceColors;
  26608. var flat = (options.flat === undefined) ? true : options.flat;
  26609. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26610. var positions = [];
  26611. var indices = [];
  26612. var normals = [];
  26613. var uvs = [];
  26614. var colors = [];
  26615. var index = 0;
  26616. var faceIdx = 0; // face cursor in the array "indexes"
  26617. var indexes = [];
  26618. var i = 0;
  26619. var f = 0;
  26620. var u, v, ang, x, y, tmp;
  26621. // default face colors and UV if undefined
  26622. if (flat) {
  26623. for (f = 0; f < nbfaces; f++) {
  26624. if (faceColors && faceColors[f] === undefined) {
  26625. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26626. }
  26627. if (faceUV && faceUV[f] === undefined) {
  26628. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26629. }
  26630. }
  26631. }
  26632. if (!flat) {
  26633. for (i = 0; i < data.vertex.length; i++) {
  26634. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26635. uvs.push(0, 0);
  26636. }
  26637. for (f = 0; f < nbfaces; f++) {
  26638. for (i = 0; i < data.face[f].length - 2; i++) {
  26639. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26640. }
  26641. }
  26642. }
  26643. else {
  26644. for (f = 0; f < nbfaces; f++) {
  26645. var fl = data.face[f].length; // number of vertices of the current face
  26646. ang = 2 * Math.PI / fl;
  26647. x = 0.5 * Math.tan(ang / 2);
  26648. y = 0.5;
  26649. // positions, uvs, colors
  26650. for (i = 0; i < fl; i++) {
  26651. // positions
  26652. 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);
  26653. indexes.push(index);
  26654. index++;
  26655. // uvs
  26656. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26657. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26658. uvs.push(u, v);
  26659. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26660. y = x * Math.sin(ang) + y * Math.cos(ang);
  26661. x = tmp;
  26662. // colors
  26663. if (faceColors) {
  26664. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26665. }
  26666. }
  26667. // indices from indexes
  26668. for (i = 0; i < fl - 2; i++) {
  26669. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26670. }
  26671. faceIdx += fl;
  26672. }
  26673. }
  26674. VertexData.ComputeNormals(positions, indices, normals);
  26675. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26676. var vertexData = new VertexData();
  26677. vertexData.positions = positions;
  26678. vertexData.indices = indices;
  26679. vertexData.normals = normals;
  26680. vertexData.uvs = uvs;
  26681. if (faceColors && flat) {
  26682. vertexData.colors = colors;
  26683. }
  26684. return vertexData;
  26685. };
  26686. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26687. /**
  26688. * Creates the VertexData of the Torus Knot.
  26689. */
  26690. VertexData.CreateTorusKnot = function (options) {
  26691. var indices = [];
  26692. var positions = [];
  26693. var normals = [];
  26694. var uvs = [];
  26695. var radius = options.radius || 2;
  26696. var tube = options.tube || 0.5;
  26697. var radialSegments = options.radialSegments || 32;
  26698. var tubularSegments = options.tubularSegments || 32;
  26699. var p = options.p || 2;
  26700. var q = options.q || 3;
  26701. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26702. // Helper
  26703. var getPos = function (angle) {
  26704. var cu = Math.cos(angle);
  26705. var su = Math.sin(angle);
  26706. var quOverP = q / p * angle;
  26707. var cs = Math.cos(quOverP);
  26708. var tx = radius * (2 + cs) * 0.5 * cu;
  26709. var ty = radius * (2 + cs) * su * 0.5;
  26710. var tz = radius * Math.sin(quOverP) * 0.5;
  26711. return new BABYLON.Vector3(tx, ty, tz);
  26712. };
  26713. // Vertices
  26714. var i;
  26715. var j;
  26716. for (i = 0; i <= radialSegments; i++) {
  26717. var modI = i % radialSegments;
  26718. var u = modI / radialSegments * 2 * p * Math.PI;
  26719. var p1 = getPos(u);
  26720. var p2 = getPos(u + 0.01);
  26721. var tang = p2.subtract(p1);
  26722. var n = p2.add(p1);
  26723. var bitan = BABYLON.Vector3.Cross(tang, n);
  26724. n = BABYLON.Vector3.Cross(bitan, tang);
  26725. bitan.normalize();
  26726. n.normalize();
  26727. for (j = 0; j < tubularSegments; j++) {
  26728. var modJ = j % tubularSegments;
  26729. var v = modJ / tubularSegments * 2 * Math.PI;
  26730. var cx = -tube * Math.cos(v);
  26731. var cy = tube * Math.sin(v);
  26732. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26733. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26734. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26735. uvs.push(i / radialSegments);
  26736. uvs.push(j / tubularSegments);
  26737. }
  26738. }
  26739. for (i = 0; i < radialSegments; i++) {
  26740. for (j = 0; j < tubularSegments; j++) {
  26741. var jNext = (j + 1) % tubularSegments;
  26742. var a = i * tubularSegments + j;
  26743. var b = (i + 1) * tubularSegments + j;
  26744. var c = (i + 1) * tubularSegments + jNext;
  26745. var d = i * tubularSegments + jNext;
  26746. indices.push(d);
  26747. indices.push(b);
  26748. indices.push(a);
  26749. indices.push(d);
  26750. indices.push(c);
  26751. indices.push(b);
  26752. }
  26753. }
  26754. // Normals
  26755. VertexData.ComputeNormals(positions, indices, normals);
  26756. // Sides
  26757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26758. // Result
  26759. var vertexData = new VertexData();
  26760. vertexData.indices = indices;
  26761. vertexData.positions = positions;
  26762. vertexData.normals = normals;
  26763. vertexData.uvs = uvs;
  26764. return vertexData;
  26765. };
  26766. // Tools
  26767. /**
  26768. * @param {any} - positions (number[] or Float32Array)
  26769. * @param {any} - indices (number[] or Uint16Array)
  26770. * @param {any} - normals (number[] or Float32Array)
  26771. * options (optional) :
  26772. * facetPositions : optional array of facet positions (vector3)
  26773. * facetNormals : optional array of facet normals (vector3)
  26774. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26775. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26776. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26777. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26778. * bInfo : optional bounding info, required for facetPartitioning computation
  26779. */
  26780. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26781. // temporary scalar variables
  26782. var index = 0; // facet index
  26783. var p1p2x = 0.0; // p1p2 vector x coordinate
  26784. var p1p2y = 0.0; // p1p2 vector y coordinate
  26785. var p1p2z = 0.0; // p1p2 vector z coordinate
  26786. var p3p2x = 0.0; // p3p2 vector x coordinate
  26787. var p3p2y = 0.0; // p3p2 vector y coordinate
  26788. var p3p2z = 0.0; // p3p2 vector z coordinate
  26789. var faceNormalx = 0.0; // facet normal x coordinate
  26790. var faceNormaly = 0.0; // facet normal y coordinate
  26791. var faceNormalz = 0.0; // facet normal z coordinate
  26792. var length = 0.0; // facet normal length before normalization
  26793. var v1x = 0; // vector1 x index in the positions array
  26794. var v1y = 0; // vector1 y index in the positions array
  26795. var v1z = 0; // vector1 z index in the positions array
  26796. var v2x = 0; // vector2 x index in the positions array
  26797. var v2y = 0; // vector2 y index in the positions array
  26798. var v2z = 0; // vector2 z index in the positions array
  26799. var v3x = 0; // vector3 x index in the positions array
  26800. var v3y = 0; // vector3 y index in the positions array
  26801. var v3z = 0; // vector3 z index in the positions array
  26802. var computeFacetNormals = false;
  26803. var computeFacetPositions = false;
  26804. var computeFacetPartitioning = false;
  26805. var faceNormalSign = 1;
  26806. if (options) {
  26807. computeFacetNormals = (options.facetNormals) ? true : false;
  26808. computeFacetPositions = (options.facetPositions) ? true : false;
  26809. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26810. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26811. }
  26812. // facetPartitioning reinit if needed
  26813. if (computeFacetPartitioning) {
  26814. var ox = 0; // X partitioning index for facet position
  26815. var oy = 0; // Y partinioning index for facet position
  26816. var oz = 0; // Z partinioning index for facet position
  26817. var b1x = 0; // X partitioning index for facet v1 vertex
  26818. var b1y = 0; // Y partitioning index for facet v1 vertex
  26819. var b1z = 0; // z partitioning index for facet v1 vertex
  26820. var b2x = 0; // X partitioning index for facet v2 vertex
  26821. var b2y = 0; // Y partitioning index for facet v2 vertex
  26822. var b2z = 0; // Z partitioning index for facet v2 vertex
  26823. var b3x = 0; // X partitioning index for facet v3 vertex
  26824. var b3y = 0; // Y partitioning index for facet v3 vertex
  26825. var b3z = 0; // Z partitioning index for facet v3 vertex
  26826. var block_idx_o = 0; // facet barycenter block index
  26827. var block_idx_v1 = 0; // v1 vertex block index
  26828. var block_idx_v2 = 0; // v2 vertex block index
  26829. var block_idx_v3 = 0; // v3 vertex block index
  26830. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26831. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26832. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26833. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26834. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26835. var subSq = options.subDiv.max * options.subDiv.max;
  26836. options.facetPartitioning.length = 0;
  26837. }
  26838. // reset the normals
  26839. for (index = 0; index < positions.length; index++) {
  26840. normals[index] = 0.0;
  26841. }
  26842. // Loop : 1 indice triplet = 1 facet
  26843. var nbFaces = indices.length / 3;
  26844. for (index = 0; index < nbFaces; index++) {
  26845. // get the indexes of the coordinates of each vertex of the facet
  26846. v1x = indices[index * 3] * 3;
  26847. v1y = v1x + 1;
  26848. v1z = v1x + 2;
  26849. v2x = indices[index * 3 + 1] * 3;
  26850. v2y = v2x + 1;
  26851. v2z = v2x + 2;
  26852. v3x = indices[index * 3 + 2] * 3;
  26853. v3y = v3x + 1;
  26854. v3z = v3x + 2;
  26855. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26856. p1p2y = positions[v1y] - positions[v2y];
  26857. p1p2z = positions[v1z] - positions[v2z];
  26858. p3p2x = positions[v3x] - positions[v2x];
  26859. p3p2y = positions[v3y] - positions[v2y];
  26860. p3p2z = positions[v3z] - positions[v2z];
  26861. // compute the face normal with the cross product
  26862. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26863. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26864. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26865. // normalize this normal and store it in the array facetData
  26866. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26867. length = (length === 0) ? 1.0 : length;
  26868. faceNormalx /= length;
  26869. faceNormaly /= length;
  26870. faceNormalz /= length;
  26871. if (computeFacetNormals) {
  26872. options.facetNormals[index].x = faceNormalx;
  26873. options.facetNormals[index].y = faceNormaly;
  26874. options.facetNormals[index].z = faceNormalz;
  26875. }
  26876. if (computeFacetPositions) {
  26877. // compute and the facet barycenter coordinates in the array facetPositions
  26878. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26879. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26880. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26881. }
  26882. if (computeFacetPartitioning) {
  26883. // store the facet indexes in arrays in the main facetPartitioning array :
  26884. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26885. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26886. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26887. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26888. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26889. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26890. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26891. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26892. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26893. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26894. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26895. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26896. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26897. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26898. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26899. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26900. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26901. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26902. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26903. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26904. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26905. // push each facet index in each block containing the vertex
  26906. options.facetPartitioning[block_idx_v1].push(index);
  26907. if (block_idx_v2 != block_idx_v1) {
  26908. options.facetPartitioning[block_idx_v2].push(index);
  26909. }
  26910. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26911. options.facetPartitioning[block_idx_v3].push(index);
  26912. }
  26913. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26914. options.facetPartitioning[block_idx_o].push(index);
  26915. }
  26916. }
  26917. // compute the normals anyway
  26918. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26919. normals[v1y] += faceNormaly;
  26920. normals[v1z] += faceNormalz;
  26921. normals[v2x] += faceNormalx;
  26922. normals[v2y] += faceNormaly;
  26923. normals[v2z] += faceNormalz;
  26924. normals[v3x] += faceNormalx;
  26925. normals[v3y] += faceNormaly;
  26926. normals[v3z] += faceNormalz;
  26927. }
  26928. // last normalization of each normal
  26929. for (index = 0; index < normals.length / 3; index++) {
  26930. faceNormalx = normals[index * 3];
  26931. faceNormaly = normals[index * 3 + 1];
  26932. faceNormalz = normals[index * 3 + 2];
  26933. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26934. length = (length === 0) ? 1.0 : length;
  26935. faceNormalx /= length;
  26936. faceNormaly /= length;
  26937. faceNormalz /= length;
  26938. normals[index * 3] = faceNormalx;
  26939. normals[index * 3 + 1] = faceNormaly;
  26940. normals[index * 3 + 2] = faceNormalz;
  26941. }
  26942. };
  26943. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26944. var li = indices.length;
  26945. var ln = normals.length;
  26946. var i;
  26947. var n;
  26948. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26949. switch (sideOrientation) {
  26950. case BABYLON.Mesh.FRONTSIDE:
  26951. // nothing changed
  26952. break;
  26953. case BABYLON.Mesh.BACKSIDE:
  26954. var tmp;
  26955. // indices
  26956. for (i = 0; i < li; i += 3) {
  26957. tmp = indices[i];
  26958. indices[i] = indices[i + 2];
  26959. indices[i + 2] = tmp;
  26960. }
  26961. // normals
  26962. for (n = 0; n < ln; n++) {
  26963. normals[n] = -normals[n];
  26964. }
  26965. break;
  26966. case BABYLON.Mesh.DOUBLESIDE:
  26967. // positions
  26968. var lp = positions.length;
  26969. var l = lp / 3;
  26970. for (var p = 0; p < lp; p++) {
  26971. positions[lp + p] = positions[p];
  26972. }
  26973. // indices
  26974. for (i = 0; i < li; i += 3) {
  26975. indices[i + li] = indices[i + 2] + l;
  26976. indices[i + 1 + li] = indices[i + 1] + l;
  26977. indices[i + 2 + li] = indices[i] + l;
  26978. }
  26979. // normals
  26980. for (n = 0; n < ln; n++) {
  26981. normals[ln + n] = -normals[n];
  26982. }
  26983. // uvs
  26984. var lu = uvs.length;
  26985. var u = 0;
  26986. for (u = 0; u < lu; u++) {
  26987. uvs[u + lu] = uvs[u];
  26988. }
  26989. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26990. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26991. u = 0;
  26992. for (i = 0; i < lu / 2; i++) {
  26993. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26994. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26995. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26996. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26997. u += 2;
  26998. }
  26999. break;
  27000. }
  27001. };
  27002. /**
  27003. * Creates a new VertexData from the imported parameters.
  27004. */
  27005. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  27006. var vertexData = new VertexData();
  27007. // positions
  27008. var positions = parsedVertexData.positions;
  27009. if (positions) {
  27010. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  27011. }
  27012. // normals
  27013. var normals = parsedVertexData.normals;
  27014. if (normals) {
  27015. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  27016. }
  27017. // tangents
  27018. var tangents = parsedVertexData.tangents;
  27019. if (tangents) {
  27020. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  27021. }
  27022. // uvs
  27023. var uvs = parsedVertexData.uvs;
  27024. if (uvs) {
  27025. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  27026. }
  27027. // uv2s
  27028. var uv2s = parsedVertexData.uv2s;
  27029. if (uv2s) {
  27030. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  27031. }
  27032. // uv3s
  27033. var uv3s = parsedVertexData.uv3s;
  27034. if (uv3s) {
  27035. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  27036. }
  27037. // uv4s
  27038. var uv4s = parsedVertexData.uv4s;
  27039. if (uv4s) {
  27040. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  27041. }
  27042. // uv5s
  27043. var uv5s = parsedVertexData.uv5s;
  27044. if (uv5s) {
  27045. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  27046. }
  27047. // uv6s
  27048. var uv6s = parsedVertexData.uv6s;
  27049. if (uv6s) {
  27050. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  27051. }
  27052. // colors
  27053. var colors = parsedVertexData.colors;
  27054. if (colors) {
  27055. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  27056. }
  27057. // matricesIndices
  27058. var matricesIndices = parsedVertexData.matricesIndices;
  27059. if (matricesIndices) {
  27060. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  27061. }
  27062. // matricesWeights
  27063. var matricesWeights = parsedVertexData.matricesWeights;
  27064. if (matricesWeights) {
  27065. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  27066. }
  27067. // indices
  27068. var indices = parsedVertexData.indices;
  27069. if (indices) {
  27070. vertexData.indices = indices;
  27071. }
  27072. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  27073. };
  27074. return VertexData;
  27075. }());
  27076. BABYLON.VertexData = VertexData;
  27077. })(BABYLON || (BABYLON = {}));
  27078. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  27079. var BABYLON;
  27080. (function (BABYLON) {
  27081. var Geometry = (function () {
  27082. function Geometry(id, scene, vertexData, updatable, mesh) {
  27083. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27084. this._totalVertices = 0;
  27085. this._isDisposed = false;
  27086. this.id = id;
  27087. this._engine = scene.getEngine();
  27088. this._meshes = [];
  27089. this._scene = scene;
  27090. //Init vertex buffer cache
  27091. this._vertexBuffers = {};
  27092. this._indices = [];
  27093. // vertexData
  27094. if (vertexData) {
  27095. this.setAllVerticesData(vertexData, updatable);
  27096. }
  27097. else {
  27098. this._totalVertices = 0;
  27099. this._indices = [];
  27100. }
  27101. if (this._engine.getCaps().vertexArrayObject) {
  27102. this._vertexArrayObjects = {};
  27103. }
  27104. // applyToMesh
  27105. if (mesh) {
  27106. if (mesh.getClassName() === "LinesMesh") {
  27107. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  27108. this.updateExtend();
  27109. }
  27110. this.applyToMesh(mesh);
  27111. mesh.computeWorldMatrix(true);
  27112. }
  27113. }
  27114. Object.defineProperty(Geometry.prototype, "boundingBias", {
  27115. /**
  27116. * 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
  27117. * @returns The Bias Vector
  27118. */
  27119. get: function () {
  27120. return this._boundingBias;
  27121. },
  27122. set: function (value) {
  27123. if (this._boundingBias && this._boundingBias.equals(value)) {
  27124. return;
  27125. }
  27126. this._boundingBias = value.clone();
  27127. this.updateBoundingInfo(true, null);
  27128. },
  27129. enumerable: true,
  27130. configurable: true
  27131. });
  27132. Object.defineProperty(Geometry.prototype, "extend", {
  27133. get: function () {
  27134. return this._extend;
  27135. },
  27136. enumerable: true,
  27137. configurable: true
  27138. });
  27139. Geometry.prototype.getScene = function () {
  27140. return this._scene;
  27141. };
  27142. Geometry.prototype.getEngine = function () {
  27143. return this._engine;
  27144. };
  27145. Geometry.prototype.isReady = function () {
  27146. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27147. };
  27148. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  27149. get: function () {
  27150. for (var index = 0; index < this._meshes.length; index++) {
  27151. if (!this._meshes[index].doNotSerialize) {
  27152. return false;
  27153. }
  27154. }
  27155. return true;
  27156. },
  27157. enumerable: true,
  27158. configurable: true
  27159. });
  27160. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27161. vertexData.applyToGeometry(this, updatable);
  27162. this.notifyUpdate();
  27163. };
  27164. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27165. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27166. this.setVerticesBuffer(buffer);
  27167. };
  27168. Geometry.prototype.removeVerticesData = function (kind) {
  27169. if (this._vertexBuffers[kind]) {
  27170. this._vertexBuffers[kind].dispose();
  27171. delete this._vertexBuffers[kind];
  27172. }
  27173. };
  27174. Geometry.prototype.setVerticesBuffer = function (buffer) {
  27175. var kind = buffer.getKind();
  27176. if (this._vertexBuffers[kind]) {
  27177. this._vertexBuffers[kind].dispose();
  27178. }
  27179. this._vertexBuffers[kind] = buffer;
  27180. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27181. var data = buffer.getData();
  27182. var stride = buffer.getStrideSize();
  27183. this._totalVertices = data.length / stride;
  27184. this.updateExtend(data, stride);
  27185. this._resetPointsArrayCache();
  27186. var meshes = this._meshes;
  27187. var numOfMeshes = meshes.length;
  27188. for (var index = 0; index < numOfMeshes; index++) {
  27189. var mesh = meshes[index];
  27190. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27191. mesh._createGlobalSubMesh();
  27192. mesh.computeWorldMatrix(true);
  27193. }
  27194. }
  27195. this.notifyUpdate(kind);
  27196. if (this._vertexArrayObjects) {
  27197. this._disposeVertexArrayObjects();
  27198. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  27199. }
  27200. };
  27201. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27202. var vertexBuffer = this.getVertexBuffer(kind);
  27203. if (!vertexBuffer) {
  27204. return;
  27205. }
  27206. vertexBuffer.updateDirectly(data, offset);
  27207. this.notifyUpdate(kind);
  27208. };
  27209. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27210. var vertexBuffer = this.getVertexBuffer(kind);
  27211. if (!vertexBuffer) {
  27212. return;
  27213. }
  27214. vertexBuffer.update(data);
  27215. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27216. var stride = vertexBuffer.getStrideSize();
  27217. this._totalVertices = data.length / stride;
  27218. this.updateBoundingInfo(updateExtends, data);
  27219. }
  27220. this.notifyUpdate(kind);
  27221. };
  27222. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  27223. if (updateExtends) {
  27224. this.updateExtend(data);
  27225. }
  27226. var meshes = this._meshes;
  27227. var numOfMeshes = meshes.length;
  27228. this._resetPointsArrayCache();
  27229. for (var index = 0; index < numOfMeshes; index++) {
  27230. var mesh = meshes[index];
  27231. if (updateExtends) {
  27232. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27233. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27234. var subMesh = mesh.subMeshes[subIndex];
  27235. subMesh.refreshBoundingInfo();
  27236. }
  27237. }
  27238. }
  27239. };
  27240. Geometry.prototype._bind = function (effect, indexToBind) {
  27241. if (indexToBind === void 0) { indexToBind = undefined; }
  27242. if (indexToBind === undefined) {
  27243. indexToBind = this._indexBuffer;
  27244. }
  27245. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27246. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27247. return;
  27248. }
  27249. // Using VAO
  27250. if (!this._vertexArrayObjects[effect.key]) {
  27251. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27252. }
  27253. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27254. };
  27255. Geometry.prototype.getTotalVertices = function () {
  27256. if (!this.isReady()) {
  27257. return 0;
  27258. }
  27259. return this._totalVertices;
  27260. };
  27261. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27262. var vertexBuffer = this.getVertexBuffer(kind);
  27263. if (!vertexBuffer) {
  27264. return null;
  27265. }
  27266. var orig = vertexBuffer.getData();
  27267. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27268. return orig;
  27269. }
  27270. else {
  27271. var len = orig.length;
  27272. var copy = [];
  27273. for (var i = 0; i < len; i++) {
  27274. copy.push(orig[i]);
  27275. }
  27276. return copy;
  27277. }
  27278. };
  27279. Geometry.prototype.getVertexBuffer = function (kind) {
  27280. if (!this.isReady()) {
  27281. return null;
  27282. }
  27283. return this._vertexBuffers[kind];
  27284. };
  27285. Geometry.prototype.getVertexBuffers = function () {
  27286. if (!this.isReady()) {
  27287. return null;
  27288. }
  27289. return this._vertexBuffers;
  27290. };
  27291. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27292. if (!this._vertexBuffers) {
  27293. if (this._delayInfo) {
  27294. return this._delayInfo.indexOf(kind) !== -1;
  27295. }
  27296. return false;
  27297. }
  27298. return this._vertexBuffers[kind] !== undefined;
  27299. };
  27300. Geometry.prototype.getVerticesDataKinds = function () {
  27301. var result = [];
  27302. var kind;
  27303. if (!this._vertexBuffers && this._delayInfo) {
  27304. for (kind in this._delayInfo) {
  27305. result.push(kind);
  27306. }
  27307. }
  27308. else {
  27309. for (kind in this._vertexBuffers) {
  27310. result.push(kind);
  27311. }
  27312. }
  27313. return result;
  27314. };
  27315. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27316. if (this._indexBuffer) {
  27317. this._engine._releaseBuffer(this._indexBuffer);
  27318. }
  27319. this._disposeVertexArrayObjects();
  27320. this._indices = indices;
  27321. if (this._meshes.length !== 0 && this._indices) {
  27322. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27323. }
  27324. if (totalVertices !== undefined) {
  27325. this._totalVertices = totalVertices;
  27326. }
  27327. var meshes = this._meshes;
  27328. var numOfMeshes = meshes.length;
  27329. for (var index = 0; index < numOfMeshes; index++) {
  27330. meshes[index]._createGlobalSubMesh();
  27331. }
  27332. this.notifyUpdate();
  27333. };
  27334. Geometry.prototype.getTotalIndices = function () {
  27335. if (!this.isReady()) {
  27336. return 0;
  27337. }
  27338. return this._indices.length;
  27339. };
  27340. Geometry.prototype.getIndices = function (copyWhenShared) {
  27341. if (!this.isReady()) {
  27342. return null;
  27343. }
  27344. var orig = this._indices;
  27345. if (!copyWhenShared || this._meshes.length === 1) {
  27346. return orig;
  27347. }
  27348. else {
  27349. var len = orig.length;
  27350. var copy = [];
  27351. for (var i = 0; i < len; i++) {
  27352. copy.push(orig[i]);
  27353. }
  27354. return copy;
  27355. }
  27356. };
  27357. Geometry.prototype.getIndexBuffer = function () {
  27358. if (!this.isReady()) {
  27359. return null;
  27360. }
  27361. return this._indexBuffer;
  27362. };
  27363. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27364. if (!effect || !this._vertexArrayObjects) {
  27365. return;
  27366. }
  27367. if (this._vertexArrayObjects[effect.key]) {
  27368. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27369. delete this._vertexArrayObjects[effect.key];
  27370. }
  27371. };
  27372. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27373. var meshes = this._meshes;
  27374. var index = meshes.indexOf(mesh);
  27375. if (index === -1) {
  27376. return;
  27377. }
  27378. meshes.splice(index, 1);
  27379. mesh._geometry = null;
  27380. if (meshes.length === 0 && shouldDispose) {
  27381. this.dispose();
  27382. }
  27383. };
  27384. Geometry.prototype.applyToMesh = function (mesh) {
  27385. if (mesh._geometry === this) {
  27386. return;
  27387. }
  27388. var previousGeometry = mesh._geometry;
  27389. if (previousGeometry) {
  27390. previousGeometry.releaseForMesh(mesh);
  27391. }
  27392. var meshes = this._meshes;
  27393. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27394. mesh._geometry = this;
  27395. this._scene.pushGeometry(this);
  27396. meshes.push(mesh);
  27397. if (this.isReady()) {
  27398. this._applyToMesh(mesh);
  27399. }
  27400. else {
  27401. mesh._boundingInfo = this._boundingInfo;
  27402. }
  27403. };
  27404. Geometry.prototype.updateExtend = function (data, stride) {
  27405. if (data === void 0) { data = null; }
  27406. if (!data) {
  27407. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27408. }
  27409. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27410. };
  27411. Geometry.prototype._applyToMesh = function (mesh) {
  27412. var numOfMeshes = this._meshes.length;
  27413. // vertexBuffers
  27414. for (var kind in this._vertexBuffers) {
  27415. if (numOfMeshes === 1) {
  27416. this._vertexBuffers[kind].create();
  27417. }
  27418. var buffer = this._vertexBuffers[kind].getBuffer();
  27419. if (buffer)
  27420. buffer.references = numOfMeshes;
  27421. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27422. if (!this._extend) {
  27423. this.updateExtend(this._vertexBuffers[kind].getData());
  27424. }
  27425. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27426. mesh._createGlobalSubMesh();
  27427. //bounding info was just created again, world matrix should be applied again.
  27428. mesh._updateBoundingInfo();
  27429. }
  27430. }
  27431. // indexBuffer
  27432. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27433. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27434. }
  27435. if (this._indexBuffer) {
  27436. this._indexBuffer.references = numOfMeshes;
  27437. }
  27438. };
  27439. Geometry.prototype.notifyUpdate = function (kind) {
  27440. if (this.onGeometryUpdated) {
  27441. this.onGeometryUpdated(this, kind);
  27442. }
  27443. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27444. var mesh = _a[_i];
  27445. mesh._markSubMeshesAsAttributesDirty();
  27446. }
  27447. };
  27448. Geometry.prototype.load = function (scene, onLoaded) {
  27449. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27450. return;
  27451. }
  27452. if (this.isReady()) {
  27453. if (onLoaded) {
  27454. onLoaded();
  27455. }
  27456. return;
  27457. }
  27458. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27459. this._queueLoad(scene, onLoaded);
  27460. };
  27461. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27462. var _this = this;
  27463. scene._addPendingData(this);
  27464. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27465. _this._delayLoadingFunction(JSON.parse(data), _this);
  27466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27467. _this._delayInfo = [];
  27468. scene._removePendingData(_this);
  27469. var meshes = _this._meshes;
  27470. var numOfMeshes = meshes.length;
  27471. for (var index = 0; index < numOfMeshes; index++) {
  27472. _this._applyToMesh(meshes[index]);
  27473. }
  27474. if (onLoaded) {
  27475. onLoaded();
  27476. }
  27477. }, function () { }, scene.database);
  27478. };
  27479. /**
  27480. * Invert the geometry to move from a right handed system to a left handed one.
  27481. */
  27482. Geometry.prototype.toLeftHanded = function () {
  27483. // Flip faces
  27484. var tIndices = this.getIndices(false);
  27485. if (tIndices != null && tIndices.length > 0) {
  27486. for (var i = 0; i < tIndices.length; i += 3) {
  27487. var tTemp = tIndices[i + 0];
  27488. tIndices[i + 0] = tIndices[i + 2];
  27489. tIndices[i + 2] = tTemp;
  27490. }
  27491. this.setIndices(tIndices);
  27492. }
  27493. // Negate position.z
  27494. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27495. if (tPositions != null && tPositions.length > 0) {
  27496. for (var i = 0; i < tPositions.length; i += 3) {
  27497. tPositions[i + 2] = -tPositions[i + 2];
  27498. }
  27499. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27500. }
  27501. // Negate normal.z
  27502. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27503. if (tNormals != null && tNormals.length > 0) {
  27504. for (var i = 0; i < tNormals.length; i += 3) {
  27505. tNormals[i + 2] = -tNormals[i + 2];
  27506. }
  27507. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27508. }
  27509. };
  27510. // Cache
  27511. Geometry.prototype._resetPointsArrayCache = function () {
  27512. this._positions = null;
  27513. };
  27514. Geometry.prototype._generatePointsArray = function () {
  27515. if (this._positions)
  27516. return true;
  27517. this._positions = [];
  27518. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27519. if (!data) {
  27520. return false;
  27521. }
  27522. for (var index = 0; index < data.length; index += 3) {
  27523. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27524. }
  27525. return true;
  27526. };
  27527. Geometry.prototype.isDisposed = function () {
  27528. return this._isDisposed;
  27529. };
  27530. Geometry.prototype._disposeVertexArrayObjects = function () {
  27531. if (this._vertexArrayObjects) {
  27532. for (var kind in this._vertexArrayObjects) {
  27533. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27534. }
  27535. this._vertexArrayObjects = {};
  27536. }
  27537. };
  27538. Geometry.prototype.dispose = function () {
  27539. var meshes = this._meshes;
  27540. var numOfMeshes = meshes.length;
  27541. var index;
  27542. for (index = 0; index < numOfMeshes; index++) {
  27543. this.releaseForMesh(meshes[index]);
  27544. }
  27545. this._meshes = [];
  27546. this._disposeVertexArrayObjects();
  27547. for (var kind in this._vertexBuffers) {
  27548. this._vertexBuffers[kind].dispose();
  27549. }
  27550. this._vertexBuffers = {};
  27551. this._totalVertices = 0;
  27552. if (this._indexBuffer) {
  27553. this._engine._releaseBuffer(this._indexBuffer);
  27554. }
  27555. this._indexBuffer = null;
  27556. this._indices = [];
  27557. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27558. this.delayLoadingFile = null;
  27559. this._delayLoadingFunction = null;
  27560. this._delayInfo = [];
  27561. this._boundingInfo = null;
  27562. this._scene.removeGeometry(this);
  27563. this._isDisposed = true;
  27564. };
  27565. Geometry.prototype.copy = function (id) {
  27566. var vertexData = new BABYLON.VertexData();
  27567. vertexData.indices = [];
  27568. var indices = this.getIndices();
  27569. for (var index = 0; index < indices.length; index++) {
  27570. vertexData.indices.push(indices[index]);
  27571. }
  27572. var updatable = false;
  27573. var stopChecking = false;
  27574. var kind;
  27575. for (kind in this._vertexBuffers) {
  27576. // using slice() to make a copy of the array and not just reference it
  27577. var data = this.getVerticesData(kind);
  27578. if (data instanceof Float32Array) {
  27579. vertexData.set(new Float32Array(data), kind);
  27580. }
  27581. else {
  27582. vertexData.set(data.slice(0), kind);
  27583. }
  27584. if (!stopChecking) {
  27585. updatable = this.getVertexBuffer(kind).isUpdatable();
  27586. stopChecking = !updatable;
  27587. }
  27588. }
  27589. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27590. geometry.delayLoadState = this.delayLoadState;
  27591. geometry.delayLoadingFile = this.delayLoadingFile;
  27592. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27593. for (kind in this._delayInfo) {
  27594. geometry._delayInfo = geometry._delayInfo || [];
  27595. geometry._delayInfo.push(kind);
  27596. }
  27597. // Bounding info
  27598. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27599. return geometry;
  27600. };
  27601. Geometry.prototype.serialize = function () {
  27602. var serializationObject = {};
  27603. serializationObject.id = this.id;
  27604. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27605. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27606. }
  27607. return serializationObject;
  27608. };
  27609. Geometry.prototype.toNumberArray = function (origin) {
  27610. if (Array.isArray(origin)) {
  27611. return origin;
  27612. }
  27613. else {
  27614. return Array.prototype.slice.call(origin);
  27615. }
  27616. };
  27617. Geometry.prototype.serializeVerticeData = function () {
  27618. var serializationObject = this.serialize();
  27619. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27620. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27621. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27622. serializationObject.positions._updatable = true;
  27623. }
  27624. }
  27625. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27626. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27627. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27628. serializationObject.normals._updatable = true;
  27629. }
  27630. }
  27631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27632. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27633. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27634. serializationObject.uvs._updatable = true;
  27635. }
  27636. }
  27637. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27638. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27639. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27640. serializationObject.uv2s._updatable = true;
  27641. }
  27642. }
  27643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27644. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27645. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27646. serializationObject.uv3s._updatable = true;
  27647. }
  27648. }
  27649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27650. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27651. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27652. serializationObject.uv4s._updatable = true;
  27653. }
  27654. }
  27655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27656. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27657. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27658. serializationObject.uv5s._updatable = true;
  27659. }
  27660. }
  27661. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27662. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27663. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27664. serializationObject.uv6s._updatable = true;
  27665. }
  27666. }
  27667. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27668. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27669. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27670. serializationObject.colors._updatable = true;
  27671. }
  27672. }
  27673. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27674. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27675. serializationObject.matricesIndices._isExpanded = true;
  27676. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27677. serializationObject.matricesIndices._updatable = true;
  27678. }
  27679. }
  27680. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27681. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27682. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27683. serializationObject.matricesWeights._updatable = true;
  27684. }
  27685. }
  27686. serializationObject.indices = this.toNumberArray(this.getIndices());
  27687. return serializationObject;
  27688. };
  27689. // Statics
  27690. Geometry.ExtractFromMesh = function (mesh, id) {
  27691. var geometry = mesh._geometry;
  27692. if (!geometry) {
  27693. return null;
  27694. }
  27695. return geometry.copy(id);
  27696. };
  27697. /**
  27698. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27699. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27700. * Be aware Math.random() could cause collisions, but:
  27701. * "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"
  27702. */
  27703. Geometry.RandomId = function () {
  27704. return BABYLON.Tools.RandomId();
  27705. };
  27706. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27707. var scene = mesh.getScene();
  27708. // Geometry
  27709. var geometryId = parsedGeometry.geometryId;
  27710. if (geometryId) {
  27711. var geometry = scene.getGeometryByID(geometryId);
  27712. if (geometry) {
  27713. geometry.applyToMesh(mesh);
  27714. }
  27715. }
  27716. else if (parsedGeometry instanceof ArrayBuffer) {
  27717. var binaryInfo = mesh._binaryInfo;
  27718. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27719. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27720. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27721. }
  27722. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27723. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27724. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27725. }
  27726. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27727. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27728. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27729. }
  27730. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27731. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27732. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27733. }
  27734. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27735. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27736. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27737. }
  27738. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27739. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27740. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27741. }
  27742. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27743. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27744. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27745. }
  27746. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27747. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27748. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27749. }
  27750. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27751. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27752. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27753. }
  27754. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27755. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27756. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27757. }
  27758. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27759. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27760. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27761. }
  27762. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27763. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27764. mesh.setIndices(indicesData);
  27765. }
  27766. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27767. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27768. mesh.subMeshes = [];
  27769. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27770. var materialIndex = subMeshesData[(i * 5) + 0];
  27771. var verticesStart = subMeshesData[(i * 5) + 1];
  27772. var verticesCount = subMeshesData[(i * 5) + 2];
  27773. var indexStart = subMeshesData[(i * 5) + 3];
  27774. var indexCount = subMeshesData[(i * 5) + 4];
  27775. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27776. }
  27777. }
  27778. }
  27779. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27780. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27781. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27782. if (parsedGeometry.uvs) {
  27783. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27784. }
  27785. if (parsedGeometry.uvs2) {
  27786. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27787. }
  27788. if (parsedGeometry.uvs3) {
  27789. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27790. }
  27791. if (parsedGeometry.uvs4) {
  27792. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27793. }
  27794. if (parsedGeometry.uvs5) {
  27795. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27796. }
  27797. if (parsedGeometry.uvs6) {
  27798. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27799. }
  27800. if (parsedGeometry.colors) {
  27801. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27802. }
  27803. if (parsedGeometry.matricesIndices) {
  27804. if (!parsedGeometry.matricesIndices._isExpanded) {
  27805. var floatIndices = [];
  27806. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27807. var matricesIndex = parsedGeometry.matricesIndices[i];
  27808. floatIndices.push(matricesIndex & 0x000000FF);
  27809. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27810. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27811. floatIndices.push(matricesIndex >> 24);
  27812. }
  27813. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27814. }
  27815. else {
  27816. delete parsedGeometry.matricesIndices._isExpanded;
  27817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27818. }
  27819. }
  27820. if (parsedGeometry.matricesIndicesExtra) {
  27821. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27822. var floatIndices = [];
  27823. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27824. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27825. floatIndices.push(matricesIndex & 0x000000FF);
  27826. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27827. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27828. floatIndices.push(matricesIndex >> 24);
  27829. }
  27830. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27831. }
  27832. else {
  27833. delete parsedGeometry.matricesIndices._isExpanded;
  27834. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27835. }
  27836. }
  27837. if (parsedGeometry.matricesWeights) {
  27838. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27839. }
  27840. if (parsedGeometry.matricesWeightsExtra) {
  27841. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27842. }
  27843. mesh.setIndices(parsedGeometry.indices);
  27844. }
  27845. // SubMeshes
  27846. if (parsedGeometry.subMeshes) {
  27847. mesh.subMeshes = [];
  27848. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27849. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27850. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27851. }
  27852. }
  27853. // Flat shading
  27854. if (mesh._shouldGenerateFlatShading) {
  27855. mesh.convertToFlatShadedMesh();
  27856. delete mesh._shouldGenerateFlatShading;
  27857. }
  27858. // Update
  27859. mesh.computeWorldMatrix(true);
  27860. // Octree
  27861. if (scene['_selectionOctree']) {
  27862. scene['_selectionOctree'].addMesh(mesh);
  27863. }
  27864. };
  27865. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27866. if (scene.getGeometryByID(parsedVertexData.id)) {
  27867. return null; // null since geometry could be something else than a box...
  27868. }
  27869. var geometry = new Geometry(parsedVertexData.id, scene);
  27870. if (BABYLON.Tags) {
  27871. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27872. }
  27873. if (parsedVertexData.delayLoadingFile) {
  27874. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27875. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27876. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27877. geometry._delayInfo = [];
  27878. if (parsedVertexData.hasUVs) {
  27879. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27880. }
  27881. if (parsedVertexData.hasUVs2) {
  27882. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27883. }
  27884. if (parsedVertexData.hasUVs3) {
  27885. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27886. }
  27887. if (parsedVertexData.hasUVs4) {
  27888. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27889. }
  27890. if (parsedVertexData.hasUVs5) {
  27891. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27892. }
  27893. if (parsedVertexData.hasUVs6) {
  27894. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27895. }
  27896. if (parsedVertexData.hasColors) {
  27897. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27898. }
  27899. if (parsedVertexData.hasMatricesIndices) {
  27900. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27901. }
  27902. if (parsedVertexData.hasMatricesWeights) {
  27903. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27904. }
  27905. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27906. }
  27907. else {
  27908. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27909. }
  27910. scene.pushGeometry(geometry, true);
  27911. return geometry;
  27912. };
  27913. return Geometry;
  27914. }());
  27915. BABYLON.Geometry = Geometry;
  27916. /////// Primitives //////////////////////////////////////////////
  27917. (function (Geometry) {
  27918. var Primitives;
  27919. (function (Primitives) {
  27920. /// Abstract class
  27921. var _Primitive = (function (_super) {
  27922. __extends(_Primitive, _super);
  27923. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27924. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27925. _this._canBeRegenerated = _canBeRegenerated;
  27926. _this._beingRegenerated = true;
  27927. _this.regenerate();
  27928. _this._beingRegenerated = false;
  27929. return _this;
  27930. }
  27931. _Primitive.prototype.canBeRegenerated = function () {
  27932. return this._canBeRegenerated;
  27933. };
  27934. _Primitive.prototype.regenerate = function () {
  27935. if (!this._canBeRegenerated) {
  27936. return;
  27937. }
  27938. this._beingRegenerated = true;
  27939. this.setAllVerticesData(this._regenerateVertexData(), false);
  27940. this._beingRegenerated = false;
  27941. };
  27942. _Primitive.prototype.asNewGeometry = function (id) {
  27943. return _super.prototype.copy.call(this, id);
  27944. };
  27945. // overrides
  27946. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27947. if (!this._beingRegenerated) {
  27948. return;
  27949. }
  27950. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27951. };
  27952. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27953. if (!this._beingRegenerated) {
  27954. return;
  27955. }
  27956. _super.prototype.setVerticesData.call(this, kind, data, false);
  27957. };
  27958. // to override
  27959. // protected
  27960. _Primitive.prototype._regenerateVertexData = function () {
  27961. throw new Error("Abstract method");
  27962. };
  27963. _Primitive.prototype.copy = function (id) {
  27964. throw new Error("Must be overriden in sub-classes.");
  27965. };
  27966. _Primitive.prototype.serialize = function () {
  27967. var serializationObject = _super.prototype.serialize.call(this);
  27968. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27969. return serializationObject;
  27970. };
  27971. return _Primitive;
  27972. }(Geometry));
  27973. Primitives._Primitive = _Primitive;
  27974. var Ribbon = (function (_super) {
  27975. __extends(Ribbon, _super);
  27976. // Members
  27977. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27978. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27979. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27980. _this.pathArray = pathArray;
  27981. _this.closeArray = closeArray;
  27982. _this.closePath = closePath;
  27983. _this.offset = offset;
  27984. _this.side = side;
  27985. return _this;
  27986. }
  27987. Ribbon.prototype._regenerateVertexData = function () {
  27988. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27989. };
  27990. Ribbon.prototype.copy = function (id) {
  27991. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27992. };
  27993. return Ribbon;
  27994. }(_Primitive));
  27995. Primitives.Ribbon = Ribbon;
  27996. var Box = (function (_super) {
  27997. __extends(Box, _super);
  27998. // Members
  27999. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28000. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28001. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28002. _this.size = size;
  28003. _this.side = side;
  28004. return _this;
  28005. }
  28006. Box.prototype._regenerateVertexData = function () {
  28007. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  28008. };
  28009. Box.prototype.copy = function (id) {
  28010. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28011. };
  28012. Box.prototype.serialize = function () {
  28013. var serializationObject = _super.prototype.serialize.call(this);
  28014. serializationObject.size = this.size;
  28015. return serializationObject;
  28016. };
  28017. Box.Parse = function (parsedBox, scene) {
  28018. if (scene.getGeometryByID(parsedBox.id)) {
  28019. return null; // null since geometry could be something else than a box...
  28020. }
  28021. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  28022. if (BABYLON.Tags) {
  28023. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  28024. }
  28025. scene.pushGeometry(box, true);
  28026. return box;
  28027. };
  28028. return Box;
  28029. }(_Primitive));
  28030. Primitives.Box = Box;
  28031. var Sphere = (function (_super) {
  28032. __extends(Sphere, _super);
  28033. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28034. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28035. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28036. _this.segments = segments;
  28037. _this.diameter = diameter;
  28038. _this.side = side;
  28039. return _this;
  28040. }
  28041. Sphere.prototype._regenerateVertexData = function () {
  28042. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  28043. };
  28044. Sphere.prototype.copy = function (id) {
  28045. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28046. };
  28047. Sphere.prototype.serialize = function () {
  28048. var serializationObject = _super.prototype.serialize.call(this);
  28049. serializationObject.segments = this.segments;
  28050. serializationObject.diameter = this.diameter;
  28051. return serializationObject;
  28052. };
  28053. Sphere.Parse = function (parsedSphere, scene) {
  28054. if (scene.getGeometryByID(parsedSphere.id)) {
  28055. return null; // null since geometry could be something else than a sphere...
  28056. }
  28057. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  28058. if (BABYLON.Tags) {
  28059. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  28060. }
  28061. scene.pushGeometry(sphere, true);
  28062. return sphere;
  28063. };
  28064. return Sphere;
  28065. }(_Primitive));
  28066. Primitives.Sphere = Sphere;
  28067. var Disc = (function (_super) {
  28068. __extends(Disc, _super);
  28069. // Members
  28070. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  28071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28072. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28073. _this.radius = radius;
  28074. _this.tessellation = tessellation;
  28075. _this.side = side;
  28076. return _this;
  28077. }
  28078. Disc.prototype._regenerateVertexData = function () {
  28079. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  28080. };
  28081. Disc.prototype.copy = function (id) {
  28082. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  28083. };
  28084. return Disc;
  28085. }(_Primitive));
  28086. Primitives.Disc = Disc;
  28087. var Cylinder = (function (_super) {
  28088. __extends(Cylinder, _super);
  28089. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28090. if (subdivisions === void 0) { subdivisions = 1; }
  28091. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28092. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28093. _this.height = height;
  28094. _this.diameterTop = diameterTop;
  28095. _this.diameterBottom = diameterBottom;
  28096. _this.tessellation = tessellation;
  28097. _this.subdivisions = subdivisions;
  28098. _this.side = side;
  28099. return _this;
  28100. }
  28101. Cylinder.prototype._regenerateVertexData = function () {
  28102. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  28103. };
  28104. Cylinder.prototype.copy = function (id) {
  28105. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28106. };
  28107. Cylinder.prototype.serialize = function () {
  28108. var serializationObject = _super.prototype.serialize.call(this);
  28109. serializationObject.height = this.height;
  28110. serializationObject.diameterTop = this.diameterTop;
  28111. serializationObject.diameterBottom = this.diameterBottom;
  28112. serializationObject.tessellation = this.tessellation;
  28113. return serializationObject;
  28114. };
  28115. Cylinder.Parse = function (parsedCylinder, scene) {
  28116. if (scene.getGeometryByID(parsedCylinder.id)) {
  28117. return null; // null since geometry could be something else than a cylinder...
  28118. }
  28119. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  28120. if (BABYLON.Tags) {
  28121. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  28122. }
  28123. scene.pushGeometry(cylinder, true);
  28124. return cylinder;
  28125. };
  28126. return Cylinder;
  28127. }(_Primitive));
  28128. Primitives.Cylinder = Cylinder;
  28129. var Torus = (function (_super) {
  28130. __extends(Torus, _super);
  28131. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28132. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28133. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28134. _this.diameter = diameter;
  28135. _this.thickness = thickness;
  28136. _this.tessellation = tessellation;
  28137. _this.side = side;
  28138. return _this;
  28139. }
  28140. Torus.prototype._regenerateVertexData = function () {
  28141. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  28142. };
  28143. Torus.prototype.copy = function (id) {
  28144. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28145. };
  28146. Torus.prototype.serialize = function () {
  28147. var serializationObject = _super.prototype.serialize.call(this);
  28148. serializationObject.diameter = this.diameter;
  28149. serializationObject.thickness = this.thickness;
  28150. serializationObject.tessellation = this.tessellation;
  28151. return serializationObject;
  28152. };
  28153. Torus.Parse = function (parsedTorus, scene) {
  28154. if (scene.getGeometryByID(parsedTorus.id)) {
  28155. return null; // null since geometry could be something else than a torus...
  28156. }
  28157. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  28158. if (BABYLON.Tags) {
  28159. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  28160. }
  28161. scene.pushGeometry(torus, true);
  28162. return torus;
  28163. };
  28164. return Torus;
  28165. }(_Primitive));
  28166. Primitives.Torus = Torus;
  28167. var Ground = (function (_super) {
  28168. __extends(Ground, _super);
  28169. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28170. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28171. _this.width = width;
  28172. _this.height = height;
  28173. _this.subdivisions = subdivisions;
  28174. return _this;
  28175. }
  28176. Ground.prototype._regenerateVertexData = function () {
  28177. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  28178. };
  28179. Ground.prototype.copy = function (id) {
  28180. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28181. };
  28182. Ground.prototype.serialize = function () {
  28183. var serializationObject = _super.prototype.serialize.call(this);
  28184. serializationObject.width = this.width;
  28185. serializationObject.height = this.height;
  28186. serializationObject.subdivisions = this.subdivisions;
  28187. return serializationObject;
  28188. };
  28189. Ground.Parse = function (parsedGround, scene) {
  28190. if (scene.getGeometryByID(parsedGround.id)) {
  28191. return null; // null since geometry could be something else than a ground...
  28192. }
  28193. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  28194. if (BABYLON.Tags) {
  28195. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  28196. }
  28197. scene.pushGeometry(ground, true);
  28198. return ground;
  28199. };
  28200. return Ground;
  28201. }(_Primitive));
  28202. Primitives.Ground = Ground;
  28203. var TiledGround = (function (_super) {
  28204. __extends(TiledGround, _super);
  28205. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28206. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28207. _this.xmin = xmin;
  28208. _this.zmin = zmin;
  28209. _this.xmax = xmax;
  28210. _this.zmax = zmax;
  28211. _this.subdivisions = subdivisions;
  28212. _this.precision = precision;
  28213. return _this;
  28214. }
  28215. TiledGround.prototype._regenerateVertexData = function () {
  28216. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  28217. };
  28218. TiledGround.prototype.copy = function (id) {
  28219. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28220. };
  28221. return TiledGround;
  28222. }(_Primitive));
  28223. Primitives.TiledGround = TiledGround;
  28224. var Plane = (function (_super) {
  28225. __extends(Plane, _super);
  28226. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28227. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28228. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28229. _this.size = size;
  28230. _this.side = side;
  28231. return _this;
  28232. }
  28233. Plane.prototype._regenerateVertexData = function () {
  28234. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  28235. };
  28236. Plane.prototype.copy = function (id) {
  28237. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28238. };
  28239. Plane.prototype.serialize = function () {
  28240. var serializationObject = _super.prototype.serialize.call(this);
  28241. serializationObject.size = this.size;
  28242. return serializationObject;
  28243. };
  28244. Plane.Parse = function (parsedPlane, scene) {
  28245. if (scene.getGeometryByID(parsedPlane.id)) {
  28246. return null; // null since geometry could be something else than a ground...
  28247. }
  28248. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28249. if (BABYLON.Tags) {
  28250. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28251. }
  28252. scene.pushGeometry(plane, true);
  28253. return plane;
  28254. };
  28255. return Plane;
  28256. }(_Primitive));
  28257. Primitives.Plane = Plane;
  28258. var TorusKnot = (function (_super) {
  28259. __extends(TorusKnot, _super);
  28260. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28261. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28262. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28263. _this.radius = radius;
  28264. _this.tube = tube;
  28265. _this.radialSegments = radialSegments;
  28266. _this.tubularSegments = tubularSegments;
  28267. _this.p = p;
  28268. _this.q = q;
  28269. _this.side = side;
  28270. return _this;
  28271. }
  28272. TorusKnot.prototype._regenerateVertexData = function () {
  28273. 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 });
  28274. };
  28275. TorusKnot.prototype.copy = function (id) {
  28276. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28277. };
  28278. TorusKnot.prototype.serialize = function () {
  28279. var serializationObject = _super.prototype.serialize.call(this);
  28280. serializationObject.radius = this.radius;
  28281. serializationObject.tube = this.tube;
  28282. serializationObject.radialSegments = this.radialSegments;
  28283. serializationObject.tubularSegments = this.tubularSegments;
  28284. serializationObject.p = this.p;
  28285. serializationObject.q = this.q;
  28286. return serializationObject;
  28287. };
  28288. ;
  28289. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28290. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28291. return null; // null since geometry could be something else than a ground...
  28292. }
  28293. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28294. if (BABYLON.Tags) {
  28295. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28296. }
  28297. scene.pushGeometry(torusKnot, true);
  28298. return torusKnot;
  28299. };
  28300. return TorusKnot;
  28301. }(_Primitive));
  28302. Primitives.TorusKnot = TorusKnot;
  28303. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28304. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28305. })(BABYLON || (BABYLON = {}));
  28306. //# sourceMappingURL=babylon.geometry.js.map
  28307. var BABYLON;
  28308. (function (BABYLON) {
  28309. var PostProcessManager = (function () {
  28310. function PostProcessManager(scene) {
  28311. this._vertexBuffers = {};
  28312. this._scene = scene;
  28313. }
  28314. PostProcessManager.prototype._prepareBuffers = function () {
  28315. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28316. return;
  28317. }
  28318. // VBO
  28319. var vertices = [];
  28320. vertices.push(1, 1);
  28321. vertices.push(-1, 1);
  28322. vertices.push(-1, -1);
  28323. vertices.push(1, -1);
  28324. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28325. // Indices
  28326. var indices = [];
  28327. indices.push(0);
  28328. indices.push(1);
  28329. indices.push(2);
  28330. indices.push(0);
  28331. indices.push(2);
  28332. indices.push(3);
  28333. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28334. };
  28335. // Methods
  28336. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28337. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28338. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28339. return false;
  28340. }
  28341. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28342. return true;
  28343. };
  28344. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28345. var engine = this._scene.getEngine();
  28346. for (var index = 0; index < postProcesses.length; index++) {
  28347. if (index < postProcesses.length - 1) {
  28348. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28349. }
  28350. else {
  28351. if (targetTexture) {
  28352. engine.bindFramebuffer(targetTexture);
  28353. }
  28354. else {
  28355. engine.restoreDefaultFramebuffer();
  28356. }
  28357. }
  28358. var pp = postProcesses[index];
  28359. var effect = pp.apply();
  28360. if (effect) {
  28361. pp.onBeforeRenderObservable.notifyObservers(effect);
  28362. // VBOs
  28363. this._prepareBuffers();
  28364. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28365. // Draw order
  28366. engine.draw(true, 0, 6);
  28367. pp.onAfterRenderObservable.notifyObservers(effect);
  28368. }
  28369. }
  28370. // Restore depth buffer
  28371. engine.setDepthBuffer(true);
  28372. engine.setDepthWrite(true);
  28373. };
  28374. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28375. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28376. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28377. return;
  28378. }
  28379. var engine = this._scene.getEngine();
  28380. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28381. if (index < len - 1) {
  28382. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28383. }
  28384. else {
  28385. if (targetTexture) {
  28386. engine.bindFramebuffer(targetTexture, faceIndex);
  28387. }
  28388. else {
  28389. engine.restoreDefaultFramebuffer();
  28390. }
  28391. }
  28392. if (doNotPresent) {
  28393. break;
  28394. }
  28395. var pp = postProcesses[index];
  28396. var effect = pp.apply();
  28397. if (effect) {
  28398. pp.onBeforeRenderObservable.notifyObservers(effect);
  28399. // VBOs
  28400. this._prepareBuffers();
  28401. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28402. // Draw order
  28403. engine.draw(true, 0, 6);
  28404. pp.onAfterRenderObservable.notifyObservers(effect);
  28405. }
  28406. }
  28407. // Restore states
  28408. engine.setDepthBuffer(true);
  28409. engine.setDepthWrite(true);
  28410. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28411. };
  28412. PostProcessManager.prototype.dispose = function () {
  28413. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28414. if (buffer) {
  28415. buffer.dispose();
  28416. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28417. }
  28418. if (this._indexBuffer) {
  28419. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28420. this._indexBuffer = null;
  28421. }
  28422. };
  28423. return PostProcessManager;
  28424. }());
  28425. BABYLON.PostProcessManager = PostProcessManager;
  28426. })(BABYLON || (BABYLON = {}));
  28427. //# sourceMappingURL=babylon.postProcessManager.js.map
  28428. var BABYLON;
  28429. (function (BABYLON) {
  28430. var AnimationRange = (function () {
  28431. function AnimationRange(name, from, to) {
  28432. this.name = name;
  28433. this.from = from;
  28434. this.to = to;
  28435. }
  28436. AnimationRange.prototype.clone = function () {
  28437. return new AnimationRange(this.name, this.from, this.to);
  28438. };
  28439. return AnimationRange;
  28440. }());
  28441. BABYLON.AnimationRange = AnimationRange;
  28442. /**
  28443. * Composed of a frame, and an action function
  28444. */
  28445. var AnimationEvent = (function () {
  28446. function AnimationEvent(frame, action, onlyOnce) {
  28447. this.frame = frame;
  28448. this.action = action;
  28449. this.onlyOnce = onlyOnce;
  28450. this.isDone = false;
  28451. }
  28452. return AnimationEvent;
  28453. }());
  28454. BABYLON.AnimationEvent = AnimationEvent;
  28455. var PathCursor = (function () {
  28456. function PathCursor(path) {
  28457. this.path = path;
  28458. this._onchange = new Array();
  28459. this.value = 0;
  28460. this.animations = new Array();
  28461. }
  28462. PathCursor.prototype.getPoint = function () {
  28463. var point = this.path.getPointAtLengthPosition(this.value);
  28464. return new BABYLON.Vector3(point.x, 0, point.y);
  28465. };
  28466. PathCursor.prototype.moveAhead = function (step) {
  28467. if (step === void 0) { step = 0.002; }
  28468. this.move(step);
  28469. return this;
  28470. };
  28471. PathCursor.prototype.moveBack = function (step) {
  28472. if (step === void 0) { step = 0.002; }
  28473. this.move(-step);
  28474. return this;
  28475. };
  28476. PathCursor.prototype.move = function (step) {
  28477. if (Math.abs(step) > 1) {
  28478. throw "step size should be less than 1.";
  28479. }
  28480. this.value += step;
  28481. this.ensureLimits();
  28482. this.raiseOnChange();
  28483. return this;
  28484. };
  28485. PathCursor.prototype.ensureLimits = function () {
  28486. while (this.value > 1) {
  28487. this.value -= 1;
  28488. }
  28489. while (this.value < 0) {
  28490. this.value += 1;
  28491. }
  28492. return this;
  28493. };
  28494. // used by animation engine
  28495. PathCursor.prototype.markAsDirty = function (propertyName) {
  28496. this.ensureLimits();
  28497. this.raiseOnChange();
  28498. return this;
  28499. };
  28500. PathCursor.prototype.raiseOnChange = function () {
  28501. var _this = this;
  28502. this._onchange.forEach(function (f) { return f(_this); });
  28503. return this;
  28504. };
  28505. PathCursor.prototype.onchange = function (f) {
  28506. this._onchange.push(f);
  28507. return this;
  28508. };
  28509. return PathCursor;
  28510. }());
  28511. BABYLON.PathCursor = PathCursor;
  28512. var Animation = (function () {
  28513. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28514. this.name = name;
  28515. this.targetProperty = targetProperty;
  28516. this.framePerSecond = framePerSecond;
  28517. this.dataType = dataType;
  28518. this.loopMode = loopMode;
  28519. this.enableBlending = enableBlending;
  28520. this._offsetsCache = {};
  28521. this._highLimitsCache = {};
  28522. this._stopped = false;
  28523. this._blendingFactor = 0;
  28524. // The set of event that will be linked to this animation
  28525. this._events = new Array();
  28526. this.allowMatricesInterpolation = false;
  28527. this.blendingSpeed = 0.01;
  28528. this._ranges = {};
  28529. this.targetPropertyPath = targetProperty.split(".");
  28530. this.dataType = dataType;
  28531. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28532. }
  28533. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28534. var dataType = undefined;
  28535. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28536. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28537. }
  28538. else if (from instanceof BABYLON.Quaternion) {
  28539. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28540. }
  28541. else if (from instanceof BABYLON.Vector3) {
  28542. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28543. }
  28544. else if (from instanceof BABYLON.Vector2) {
  28545. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28546. }
  28547. else if (from instanceof BABYLON.Color3) {
  28548. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28549. }
  28550. else if (from instanceof BABYLON.Size) {
  28551. dataType = Animation.ANIMATIONTYPE_SIZE;
  28552. }
  28553. if (dataType == undefined) {
  28554. return null;
  28555. }
  28556. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28557. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28558. animation.setKeys(keys);
  28559. if (easingFunction !== undefined) {
  28560. animation.setEasingFunction(easingFunction);
  28561. }
  28562. return animation;
  28563. };
  28564. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28565. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28566. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28567. };
  28568. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28569. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28570. node.animations.push(animation);
  28571. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28572. };
  28573. // Methods
  28574. /**
  28575. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28576. */
  28577. Animation.prototype.toString = function (fullDetails) {
  28578. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28579. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28580. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28581. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28582. if (fullDetails) {
  28583. ret += ", Ranges: {";
  28584. var first = true;
  28585. for (var name in this._ranges) {
  28586. if (first) {
  28587. ret += ", ";
  28588. first = false;
  28589. }
  28590. ret += name;
  28591. }
  28592. ret += "}";
  28593. }
  28594. return ret;
  28595. };
  28596. /**
  28597. * Add an event to this animation.
  28598. */
  28599. Animation.prototype.addEvent = function (event) {
  28600. this._events.push(event);
  28601. };
  28602. /**
  28603. * Remove all events found at the given frame
  28604. * @param frame
  28605. */
  28606. Animation.prototype.removeEvents = function (frame) {
  28607. for (var index = 0; index < this._events.length; index++) {
  28608. if (this._events[index].frame === frame) {
  28609. this._events.splice(index, 1);
  28610. index--;
  28611. }
  28612. }
  28613. };
  28614. Animation.prototype.createRange = function (name, from, to) {
  28615. // check name not already in use; could happen for bones after serialized
  28616. if (!this._ranges[name]) {
  28617. this._ranges[name] = new AnimationRange(name, from, to);
  28618. }
  28619. };
  28620. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28621. if (deleteFrames === void 0) { deleteFrames = true; }
  28622. if (this._ranges[name]) {
  28623. if (deleteFrames) {
  28624. var from = this._ranges[name].from;
  28625. var to = this._ranges[name].to;
  28626. // this loop MUST go high to low for multiple splices to work
  28627. for (var key = this._keys.length - 1; key >= 0; key--) {
  28628. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28629. this._keys.splice(key, 1);
  28630. }
  28631. }
  28632. }
  28633. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28634. }
  28635. };
  28636. Animation.prototype.getRange = function (name) {
  28637. return this._ranges[name];
  28638. };
  28639. Animation.prototype.reset = function () {
  28640. this._offsetsCache = {};
  28641. this._highLimitsCache = {};
  28642. this.currentFrame = 0;
  28643. this._blendingFactor = 0;
  28644. this._originalBlendValue = null;
  28645. };
  28646. Animation.prototype.isStopped = function () {
  28647. return this._stopped;
  28648. };
  28649. Animation.prototype.getKeys = function () {
  28650. return this._keys;
  28651. };
  28652. Animation.prototype.getHighestFrame = function () {
  28653. var ret = 0;
  28654. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28655. if (ret < this._keys[key].frame) {
  28656. ret = this._keys[key].frame;
  28657. }
  28658. }
  28659. return ret;
  28660. };
  28661. Animation.prototype.getEasingFunction = function () {
  28662. return this._easingFunction;
  28663. };
  28664. Animation.prototype.setEasingFunction = function (easingFunction) {
  28665. this._easingFunction = easingFunction;
  28666. };
  28667. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28668. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28669. };
  28670. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28671. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28672. };
  28673. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28674. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28675. };
  28676. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28677. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28678. };
  28679. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28680. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28681. };
  28682. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28683. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28684. };
  28685. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28686. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28687. };
  28688. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28689. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28690. };
  28691. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28692. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28693. };
  28694. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28695. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28696. };
  28697. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28698. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28699. };
  28700. Animation.prototype.clone = function () {
  28701. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28702. clone.enableBlending = this.enableBlending;
  28703. clone.blendingSpeed = this.blendingSpeed;
  28704. if (this._keys) {
  28705. clone.setKeys(this._keys);
  28706. }
  28707. if (this._ranges) {
  28708. clone._ranges = {};
  28709. for (var name in this._ranges) {
  28710. clone._ranges[name] = this._ranges[name].clone();
  28711. }
  28712. }
  28713. return clone;
  28714. };
  28715. Animation.prototype.setKeys = function (values) {
  28716. this._keys = values.slice(0);
  28717. this._offsetsCache = {};
  28718. this._highLimitsCache = {};
  28719. };
  28720. Animation.prototype._getKeyValue = function (value) {
  28721. if (typeof value === "function") {
  28722. return value();
  28723. }
  28724. return value;
  28725. };
  28726. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28727. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28728. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28729. }
  28730. this.currentFrame = currentFrame;
  28731. // Try to get a hash to find the right key
  28732. 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));
  28733. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28734. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28735. startKeyIndex--;
  28736. }
  28737. }
  28738. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28739. var endKey = this._keys[key + 1];
  28740. if (endKey.frame >= currentFrame) {
  28741. var startKey = this._keys[key];
  28742. var startValue = this._getKeyValue(startKey.value);
  28743. var endValue = this._getKeyValue(endKey.value);
  28744. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28745. var frameDelta = endKey.frame - startKey.frame;
  28746. // gradient : percent of currentFrame between the frame inf and the frame sup
  28747. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28748. // check for easingFunction and correction of gradient
  28749. if (this._easingFunction != null) {
  28750. gradient = this._easingFunction.ease(gradient);
  28751. }
  28752. switch (this.dataType) {
  28753. // Float
  28754. case Animation.ANIMATIONTYPE_FLOAT:
  28755. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28756. switch (loopMode) {
  28757. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28758. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28759. return floatValue;
  28760. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28761. return offsetValue * repeatCount + floatValue;
  28762. }
  28763. break;
  28764. // Quaternion
  28765. case Animation.ANIMATIONTYPE_QUATERNION:
  28766. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28767. switch (loopMode) {
  28768. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28769. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28770. return quatValue;
  28771. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28772. return quatValue.add(offsetValue.scale(repeatCount));
  28773. }
  28774. return quatValue;
  28775. // Vector3
  28776. case Animation.ANIMATIONTYPE_VECTOR3:
  28777. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28778. switch (loopMode) {
  28779. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28780. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28781. return vec3Value;
  28782. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28783. return vec3Value.add(offsetValue.scale(repeatCount));
  28784. }
  28785. // Vector2
  28786. case Animation.ANIMATIONTYPE_VECTOR2:
  28787. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28788. switch (loopMode) {
  28789. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28790. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28791. return vec2Value;
  28792. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28793. return vec2Value.add(offsetValue.scale(repeatCount));
  28794. }
  28795. // Size
  28796. case Animation.ANIMATIONTYPE_SIZE:
  28797. switch (loopMode) {
  28798. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28799. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28800. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28801. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28802. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28803. }
  28804. // Color3
  28805. case Animation.ANIMATIONTYPE_COLOR3:
  28806. switch (loopMode) {
  28807. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28808. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28809. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28810. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28811. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28812. }
  28813. // Matrix
  28814. case Animation.ANIMATIONTYPE_MATRIX:
  28815. switch (loopMode) {
  28816. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28817. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28818. if (this.allowMatricesInterpolation) {
  28819. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28820. }
  28821. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28822. return startValue;
  28823. }
  28824. default:
  28825. break;
  28826. }
  28827. break;
  28828. }
  28829. }
  28830. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28831. };
  28832. Animation.prototype.setValue = function (currentValue, blend) {
  28833. if (blend === void 0) { blend = false; }
  28834. // Set value
  28835. var path;
  28836. var destination;
  28837. if (this.targetPropertyPath.length > 1) {
  28838. var property = this._target[this.targetPropertyPath[0]];
  28839. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28840. property = property[this.targetPropertyPath[index]];
  28841. }
  28842. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28843. destination = property;
  28844. }
  28845. else {
  28846. path = this.targetPropertyPath[0];
  28847. destination = this._target;
  28848. }
  28849. // Blending
  28850. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28851. if (!this._originalBlendValue) {
  28852. if (destination[path].clone) {
  28853. this._originalBlendValue = destination[path].clone();
  28854. }
  28855. else {
  28856. this._originalBlendValue = destination[path];
  28857. }
  28858. }
  28859. if (this._originalBlendValue.prototype) {
  28860. if (this._originalBlendValue.prototype.Lerp) {
  28861. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28862. }
  28863. else {
  28864. destination[path] = currentValue;
  28865. }
  28866. }
  28867. else if (this._originalBlendValue.m) {
  28868. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28869. }
  28870. else {
  28871. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28872. }
  28873. this._blendingFactor += this.blendingSpeed;
  28874. }
  28875. else {
  28876. destination[path] = currentValue;
  28877. }
  28878. if (this._target.markAsDirty) {
  28879. this._target.markAsDirty(this.targetProperty);
  28880. }
  28881. };
  28882. Animation.prototype.goToFrame = function (frame) {
  28883. if (frame < this._keys[0].frame) {
  28884. frame = this._keys[0].frame;
  28885. }
  28886. else if (frame > this._keys[this._keys.length - 1].frame) {
  28887. frame = this._keys[this._keys.length - 1].frame;
  28888. }
  28889. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28890. this.setValue(currentValue);
  28891. };
  28892. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28893. if (blend === void 0) { blend = false; }
  28894. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28895. this._stopped = true;
  28896. return false;
  28897. }
  28898. var returnValue = true;
  28899. // Adding a start key at frame 0 if missing
  28900. if (this._keys[0].frame !== 0) {
  28901. var newKey = { frame: 0, value: this._keys[0].value };
  28902. this._keys.splice(0, 0, newKey);
  28903. }
  28904. // Check limits
  28905. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28906. from = this._keys[0].frame;
  28907. }
  28908. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28909. to = this._keys[this._keys.length - 1].frame;
  28910. }
  28911. //to and from cannot be the same key
  28912. if (from === to) {
  28913. from++;
  28914. }
  28915. // Compute ratio
  28916. var range = to - from;
  28917. var offsetValue;
  28918. // ratio represents the frame delta between from and to
  28919. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28920. var highLimitValue = 0;
  28921. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  28922. returnValue = false;
  28923. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28924. }
  28925. else {
  28926. // Get max value if required
  28927. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28928. var keyOffset = to.toString() + from.toString();
  28929. if (!this._offsetsCache[keyOffset]) {
  28930. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28931. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28932. switch (this.dataType) {
  28933. // Float
  28934. case Animation.ANIMATIONTYPE_FLOAT:
  28935. this._offsetsCache[keyOffset] = toValue - fromValue;
  28936. break;
  28937. // Quaternion
  28938. case Animation.ANIMATIONTYPE_QUATERNION:
  28939. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28940. break;
  28941. // Vector3
  28942. case Animation.ANIMATIONTYPE_VECTOR3:
  28943. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28944. // Vector2
  28945. case Animation.ANIMATIONTYPE_VECTOR2:
  28946. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28947. // Size
  28948. case Animation.ANIMATIONTYPE_SIZE:
  28949. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28950. // Color3
  28951. case Animation.ANIMATIONTYPE_COLOR3:
  28952. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28953. default:
  28954. break;
  28955. }
  28956. this._highLimitsCache[keyOffset] = toValue;
  28957. }
  28958. highLimitValue = this._highLimitsCache[keyOffset];
  28959. offsetValue = this._offsetsCache[keyOffset];
  28960. }
  28961. }
  28962. if (offsetValue === undefined) {
  28963. switch (this.dataType) {
  28964. // Float
  28965. case Animation.ANIMATIONTYPE_FLOAT:
  28966. offsetValue = 0;
  28967. break;
  28968. // Quaternion
  28969. case Animation.ANIMATIONTYPE_QUATERNION:
  28970. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28971. break;
  28972. // Vector3
  28973. case Animation.ANIMATIONTYPE_VECTOR3:
  28974. offsetValue = BABYLON.Vector3.Zero();
  28975. break;
  28976. // Vector2
  28977. case Animation.ANIMATIONTYPE_VECTOR2:
  28978. offsetValue = BABYLON.Vector2.Zero();
  28979. break;
  28980. // Size
  28981. case Animation.ANIMATIONTYPE_SIZE:
  28982. offsetValue = BABYLON.Size.Zero();
  28983. break;
  28984. // Color3
  28985. case Animation.ANIMATIONTYPE_COLOR3:
  28986. offsetValue = BABYLON.Color3.Black();
  28987. }
  28988. }
  28989. // Compute value
  28990. var repeatCount = (ratio / range) >> 0;
  28991. var currentFrame = returnValue ? from + ratio % range : to;
  28992. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28993. // Set value
  28994. this.setValue(currentValue);
  28995. // Check events
  28996. for (var index = 0; index < this._events.length; index++) {
  28997. if (currentFrame >= this._events[index].frame) {
  28998. var event = this._events[index];
  28999. if (!event.isDone) {
  29000. // If event should be done only once, remove it.
  29001. if (event.onlyOnce) {
  29002. this._events.splice(index, 1);
  29003. index--;
  29004. }
  29005. event.isDone = true;
  29006. event.action();
  29007. } // Don't do anything if the event has already be done.
  29008. }
  29009. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29010. // reset event, the animation is looping
  29011. this._events[index].isDone = false;
  29012. }
  29013. }
  29014. if (!returnValue) {
  29015. this._stopped = true;
  29016. }
  29017. return returnValue;
  29018. };
  29019. Animation.prototype.serialize = function () {
  29020. var serializationObject = {};
  29021. serializationObject.name = this.name;
  29022. serializationObject.property = this.targetProperty;
  29023. serializationObject.framePerSecond = this.framePerSecond;
  29024. serializationObject.dataType = this.dataType;
  29025. serializationObject.loopBehavior = this.loopMode;
  29026. serializationObject.enableBlending = this.enableBlending;
  29027. serializationObject.blendingSpeed = this.blendingSpeed;
  29028. var dataType = this.dataType;
  29029. serializationObject.keys = [];
  29030. var keys = this.getKeys();
  29031. for (var index = 0; index < keys.length; index++) {
  29032. var animationKey = keys[index];
  29033. var key = {};
  29034. key.frame = animationKey.frame;
  29035. switch (dataType) {
  29036. case Animation.ANIMATIONTYPE_FLOAT:
  29037. key.values = [animationKey.value];
  29038. break;
  29039. case Animation.ANIMATIONTYPE_QUATERNION:
  29040. case Animation.ANIMATIONTYPE_MATRIX:
  29041. case Animation.ANIMATIONTYPE_VECTOR3:
  29042. case Animation.ANIMATIONTYPE_COLOR3:
  29043. key.values = animationKey.value.asArray();
  29044. break;
  29045. }
  29046. serializationObject.keys.push(key);
  29047. }
  29048. serializationObject.ranges = [];
  29049. for (var name in this._ranges) {
  29050. var range = {};
  29051. range.name = name;
  29052. range.from = this._ranges[name].from;
  29053. range.to = this._ranges[name].to;
  29054. serializationObject.ranges.push(range);
  29055. }
  29056. return serializationObject;
  29057. };
  29058. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29059. get: function () {
  29060. return Animation._ANIMATIONTYPE_FLOAT;
  29061. },
  29062. enumerable: true,
  29063. configurable: true
  29064. });
  29065. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29066. get: function () {
  29067. return Animation._ANIMATIONTYPE_VECTOR3;
  29068. },
  29069. enumerable: true,
  29070. configurable: true
  29071. });
  29072. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29073. get: function () {
  29074. return Animation._ANIMATIONTYPE_VECTOR2;
  29075. },
  29076. enumerable: true,
  29077. configurable: true
  29078. });
  29079. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29080. get: function () {
  29081. return Animation._ANIMATIONTYPE_SIZE;
  29082. },
  29083. enumerable: true,
  29084. configurable: true
  29085. });
  29086. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29087. get: function () {
  29088. return Animation._ANIMATIONTYPE_QUATERNION;
  29089. },
  29090. enumerable: true,
  29091. configurable: true
  29092. });
  29093. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29094. get: function () {
  29095. return Animation._ANIMATIONTYPE_MATRIX;
  29096. },
  29097. enumerable: true,
  29098. configurable: true
  29099. });
  29100. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29101. get: function () {
  29102. return Animation._ANIMATIONTYPE_COLOR3;
  29103. },
  29104. enumerable: true,
  29105. configurable: true
  29106. });
  29107. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29108. get: function () {
  29109. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29110. },
  29111. enumerable: true,
  29112. configurable: true
  29113. });
  29114. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29115. get: function () {
  29116. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29117. },
  29118. enumerable: true,
  29119. configurable: true
  29120. });
  29121. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29122. get: function () {
  29123. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29124. },
  29125. enumerable: true,
  29126. configurable: true
  29127. });
  29128. Animation.Parse = function (parsedAnimation) {
  29129. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29130. var dataType = parsedAnimation.dataType;
  29131. var keys = [];
  29132. var data;
  29133. var index;
  29134. if (parsedAnimation.enableBlending) {
  29135. animation.enableBlending = parsedAnimation.enableBlending;
  29136. }
  29137. if (parsedAnimation.blendingSpeed) {
  29138. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  29139. }
  29140. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29141. var key = parsedAnimation.keys[index];
  29142. switch (dataType) {
  29143. case Animation.ANIMATIONTYPE_FLOAT:
  29144. data = key.values[0];
  29145. break;
  29146. case Animation.ANIMATIONTYPE_QUATERNION:
  29147. data = BABYLON.Quaternion.FromArray(key.values);
  29148. break;
  29149. case Animation.ANIMATIONTYPE_MATRIX:
  29150. data = BABYLON.Matrix.FromArray(key.values);
  29151. break;
  29152. case Animation.ANIMATIONTYPE_COLOR3:
  29153. data = BABYLON.Color3.FromArray(key.values);
  29154. break;
  29155. case Animation.ANIMATIONTYPE_VECTOR3:
  29156. default:
  29157. data = BABYLON.Vector3.FromArray(key.values);
  29158. break;
  29159. }
  29160. keys.push({
  29161. frame: key.frame,
  29162. value: data
  29163. });
  29164. }
  29165. animation.setKeys(keys);
  29166. if (parsedAnimation.ranges) {
  29167. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29168. data = parsedAnimation.ranges[index];
  29169. animation.createRange(data.name, data.from, data.to);
  29170. }
  29171. }
  29172. return animation;
  29173. };
  29174. Animation.AppendSerializedAnimations = function (source, destination) {
  29175. if (source.animations) {
  29176. destination.animations = [];
  29177. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29178. var animation = source.animations[animationIndex];
  29179. destination.animations.push(animation.serialize());
  29180. }
  29181. }
  29182. };
  29183. return Animation;
  29184. }());
  29185. // Statics
  29186. Animation._ANIMATIONTYPE_FLOAT = 0;
  29187. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29188. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29189. Animation._ANIMATIONTYPE_MATRIX = 3;
  29190. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29191. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29192. Animation._ANIMATIONTYPE_SIZE = 6;
  29193. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29194. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29195. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29196. BABYLON.Animation = Animation;
  29197. })(BABYLON || (BABYLON = {}));
  29198. //# sourceMappingURL=babylon.animation.js.map
  29199. var BABYLON;
  29200. (function (BABYLON) {
  29201. var Animatable = (function () {
  29202. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29203. if (fromFrame === void 0) { fromFrame = 0; }
  29204. if (toFrame === void 0) { toFrame = 100; }
  29205. if (loopAnimation === void 0) { loopAnimation = false; }
  29206. if (speedRatio === void 0) { speedRatio = 1.0; }
  29207. this.target = target;
  29208. this.fromFrame = fromFrame;
  29209. this.toFrame = toFrame;
  29210. this.loopAnimation = loopAnimation;
  29211. this.speedRatio = speedRatio;
  29212. this.onAnimationEnd = onAnimationEnd;
  29213. this._localDelayOffset = null;
  29214. this._pausedDelay = null;
  29215. this._animations = new Array();
  29216. this._paused = false;
  29217. this.animationStarted = false;
  29218. if (animations) {
  29219. this.appendAnimations(target, animations);
  29220. }
  29221. this._scene = scene;
  29222. scene._activeAnimatables.push(this);
  29223. }
  29224. // Methods
  29225. Animatable.prototype.getAnimations = function () {
  29226. return this._animations;
  29227. };
  29228. Animatable.prototype.appendAnimations = function (target, animations) {
  29229. for (var index = 0; index < animations.length; index++) {
  29230. var animation = animations[index];
  29231. animation._target = target;
  29232. this._animations.push(animation);
  29233. }
  29234. };
  29235. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29236. var animations = this._animations;
  29237. for (var index = 0; index < animations.length; index++) {
  29238. if (animations[index].targetProperty === property) {
  29239. return animations[index];
  29240. }
  29241. }
  29242. return null;
  29243. };
  29244. Animatable.prototype.reset = function () {
  29245. var animations = this._animations;
  29246. for (var index = 0; index < animations.length; index++) {
  29247. animations[index].reset();
  29248. }
  29249. this._localDelayOffset = null;
  29250. this._pausedDelay = null;
  29251. };
  29252. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29253. var animations = this._animations;
  29254. for (var index = 0; index < animations.length; index++) {
  29255. animations[index].enableBlending = true;
  29256. animations[index].blendingSpeed = blendingSpeed;
  29257. }
  29258. };
  29259. Animatable.prototype.disableBlending = function () {
  29260. var animations = this._animations;
  29261. for (var index = 0; index < animations.length; index++) {
  29262. animations[index].enableBlending = false;
  29263. }
  29264. };
  29265. Animatable.prototype.goToFrame = function (frame) {
  29266. var animations = this._animations;
  29267. if (animations[0]) {
  29268. var fps = animations[0].framePerSecond;
  29269. var currentFrame = animations[0].currentFrame;
  29270. var adjustTime = frame - currentFrame;
  29271. var delay = adjustTime * 1000 / fps;
  29272. this._localDelayOffset -= delay;
  29273. }
  29274. for (var index = 0; index < animations.length; index++) {
  29275. animations[index].goToFrame(frame);
  29276. }
  29277. };
  29278. Animatable.prototype.pause = function () {
  29279. if (this._paused) {
  29280. return;
  29281. }
  29282. this._paused = true;
  29283. };
  29284. Animatable.prototype.restart = function () {
  29285. this._paused = false;
  29286. };
  29287. Animatable.prototype.stop = function (animationName) {
  29288. if (animationName) {
  29289. var idx = this._scene._activeAnimatables.indexOf(this);
  29290. if (idx > -1) {
  29291. var animations = this._animations;
  29292. for (var index = animations.length - 1; index >= 0; index--) {
  29293. if (typeof animationName === "string" && animations[index].name != animationName) {
  29294. continue;
  29295. }
  29296. animations[index].reset();
  29297. animations.splice(index, 1);
  29298. }
  29299. if (animations.length == 0) {
  29300. this._scene._activeAnimatables.splice(idx, 1);
  29301. if (this.onAnimationEnd) {
  29302. this.onAnimationEnd();
  29303. }
  29304. }
  29305. }
  29306. }
  29307. else {
  29308. var index = this._scene._activeAnimatables.indexOf(this);
  29309. if (index > -1) {
  29310. this._scene._activeAnimatables.splice(index, 1);
  29311. var animations = this._animations;
  29312. for (var index = 0; index < animations.length; index++) {
  29313. animations[index].reset();
  29314. }
  29315. if (this.onAnimationEnd) {
  29316. this.onAnimationEnd();
  29317. }
  29318. }
  29319. }
  29320. };
  29321. Animatable.prototype._animate = function (delay) {
  29322. if (this._paused) {
  29323. this.animationStarted = false;
  29324. if (this._pausedDelay === null) {
  29325. this._pausedDelay = delay;
  29326. }
  29327. return true;
  29328. }
  29329. if (this._localDelayOffset === null) {
  29330. this._localDelayOffset = delay;
  29331. }
  29332. else if (this._pausedDelay !== null) {
  29333. this._localDelayOffset += delay - this._pausedDelay;
  29334. this._pausedDelay = null;
  29335. }
  29336. // Animating
  29337. var running = false;
  29338. var animations = this._animations;
  29339. var index;
  29340. for (index = 0; index < animations.length; index++) {
  29341. var animation = animations[index];
  29342. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29343. running = running || isRunning;
  29344. }
  29345. this.animationStarted = running;
  29346. if (!running) {
  29347. // Remove from active animatables
  29348. index = this._scene._activeAnimatables.indexOf(this);
  29349. this._scene._activeAnimatables.splice(index, 1);
  29350. }
  29351. if (!running && this.onAnimationEnd) {
  29352. this.onAnimationEnd();
  29353. this.onAnimationEnd = null;
  29354. }
  29355. return running;
  29356. };
  29357. return Animatable;
  29358. }());
  29359. BABYLON.Animatable = Animatable;
  29360. })(BABYLON || (BABYLON = {}));
  29361. //# sourceMappingURL=babylon.animatable.js.map
  29362. var BABYLON;
  29363. (function (BABYLON) {
  29364. var EasingFunction = (function () {
  29365. function EasingFunction() {
  29366. // Properties
  29367. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29368. }
  29369. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29370. get: function () {
  29371. return EasingFunction._EASINGMODE_EASEIN;
  29372. },
  29373. enumerable: true,
  29374. configurable: true
  29375. });
  29376. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29377. get: function () {
  29378. return EasingFunction._EASINGMODE_EASEOUT;
  29379. },
  29380. enumerable: true,
  29381. configurable: true
  29382. });
  29383. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29384. get: function () {
  29385. return EasingFunction._EASINGMODE_EASEINOUT;
  29386. },
  29387. enumerable: true,
  29388. configurable: true
  29389. });
  29390. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29391. var n = Math.min(Math.max(easingMode, 0), 2);
  29392. this._easingMode = n;
  29393. };
  29394. EasingFunction.prototype.getEasingMode = function () {
  29395. return this._easingMode;
  29396. };
  29397. EasingFunction.prototype.easeInCore = function (gradient) {
  29398. throw new Error('You must implement this method');
  29399. };
  29400. EasingFunction.prototype.ease = function (gradient) {
  29401. switch (this._easingMode) {
  29402. case EasingFunction.EASINGMODE_EASEIN:
  29403. return this.easeInCore(gradient);
  29404. case EasingFunction.EASINGMODE_EASEOUT:
  29405. return (1 - this.easeInCore(1 - gradient));
  29406. }
  29407. if (gradient >= 0.5) {
  29408. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29409. }
  29410. return (this.easeInCore(gradient * 2) * 0.5);
  29411. };
  29412. return EasingFunction;
  29413. }());
  29414. //Statics
  29415. EasingFunction._EASINGMODE_EASEIN = 0;
  29416. EasingFunction._EASINGMODE_EASEOUT = 1;
  29417. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29418. BABYLON.EasingFunction = EasingFunction;
  29419. var CircleEase = (function (_super) {
  29420. __extends(CircleEase, _super);
  29421. function CircleEase() {
  29422. return _super !== null && _super.apply(this, arguments) || this;
  29423. }
  29424. CircleEase.prototype.easeInCore = function (gradient) {
  29425. gradient = Math.max(0, Math.min(1, gradient));
  29426. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29427. };
  29428. return CircleEase;
  29429. }(EasingFunction));
  29430. BABYLON.CircleEase = CircleEase;
  29431. var BackEase = (function (_super) {
  29432. __extends(BackEase, _super);
  29433. function BackEase(amplitude) {
  29434. if (amplitude === void 0) { amplitude = 1; }
  29435. var _this = _super.call(this) || this;
  29436. _this.amplitude = amplitude;
  29437. return _this;
  29438. }
  29439. BackEase.prototype.easeInCore = function (gradient) {
  29440. var num = Math.max(0, this.amplitude);
  29441. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29442. };
  29443. return BackEase;
  29444. }(EasingFunction));
  29445. BABYLON.BackEase = BackEase;
  29446. var BounceEase = (function (_super) {
  29447. __extends(BounceEase, _super);
  29448. function BounceEase(bounces, bounciness) {
  29449. if (bounces === void 0) { bounces = 3; }
  29450. if (bounciness === void 0) { bounciness = 2; }
  29451. var _this = _super.call(this) || this;
  29452. _this.bounces = bounces;
  29453. _this.bounciness = bounciness;
  29454. return _this;
  29455. }
  29456. BounceEase.prototype.easeInCore = function (gradient) {
  29457. var y = Math.max(0.0, this.bounces);
  29458. var bounciness = this.bounciness;
  29459. if (bounciness <= 1.0) {
  29460. bounciness = 1.001;
  29461. }
  29462. var num9 = Math.pow(bounciness, y);
  29463. var num5 = 1.0 - bounciness;
  29464. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29465. var num15 = gradient * num4;
  29466. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29467. var num3 = Math.floor(num65);
  29468. var num13 = num3 + 1.0;
  29469. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29470. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29471. var num7 = (num8 + num12) * 0.5;
  29472. var num6 = gradient - num7;
  29473. var num2 = num7 - num8;
  29474. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29475. };
  29476. return BounceEase;
  29477. }(EasingFunction));
  29478. BABYLON.BounceEase = BounceEase;
  29479. var CubicEase = (function (_super) {
  29480. __extends(CubicEase, _super);
  29481. function CubicEase() {
  29482. return _super !== null && _super.apply(this, arguments) || this;
  29483. }
  29484. CubicEase.prototype.easeInCore = function (gradient) {
  29485. return (gradient * gradient * gradient);
  29486. };
  29487. return CubicEase;
  29488. }(EasingFunction));
  29489. BABYLON.CubicEase = CubicEase;
  29490. var ElasticEase = (function (_super) {
  29491. __extends(ElasticEase, _super);
  29492. function ElasticEase(oscillations, springiness) {
  29493. if (oscillations === void 0) { oscillations = 3; }
  29494. if (springiness === void 0) { springiness = 3; }
  29495. var _this = _super.call(this) || this;
  29496. _this.oscillations = oscillations;
  29497. _this.springiness = springiness;
  29498. return _this;
  29499. }
  29500. ElasticEase.prototype.easeInCore = function (gradient) {
  29501. var num2;
  29502. var num3 = Math.max(0.0, this.oscillations);
  29503. var num = Math.max(0.0, this.springiness);
  29504. if (num == 0) {
  29505. num2 = gradient;
  29506. }
  29507. else {
  29508. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29509. }
  29510. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29511. };
  29512. return ElasticEase;
  29513. }(EasingFunction));
  29514. BABYLON.ElasticEase = ElasticEase;
  29515. var ExponentialEase = (function (_super) {
  29516. __extends(ExponentialEase, _super);
  29517. function ExponentialEase(exponent) {
  29518. if (exponent === void 0) { exponent = 2; }
  29519. var _this = _super.call(this) || this;
  29520. _this.exponent = exponent;
  29521. return _this;
  29522. }
  29523. ExponentialEase.prototype.easeInCore = function (gradient) {
  29524. if (this.exponent <= 0) {
  29525. return gradient;
  29526. }
  29527. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29528. };
  29529. return ExponentialEase;
  29530. }(EasingFunction));
  29531. BABYLON.ExponentialEase = ExponentialEase;
  29532. var PowerEase = (function (_super) {
  29533. __extends(PowerEase, _super);
  29534. function PowerEase(power) {
  29535. if (power === void 0) { power = 2; }
  29536. var _this = _super.call(this) || this;
  29537. _this.power = power;
  29538. return _this;
  29539. }
  29540. PowerEase.prototype.easeInCore = function (gradient) {
  29541. var y = Math.max(0.0, this.power);
  29542. return Math.pow(gradient, y);
  29543. };
  29544. return PowerEase;
  29545. }(EasingFunction));
  29546. BABYLON.PowerEase = PowerEase;
  29547. var QuadraticEase = (function (_super) {
  29548. __extends(QuadraticEase, _super);
  29549. function QuadraticEase() {
  29550. return _super !== null && _super.apply(this, arguments) || this;
  29551. }
  29552. QuadraticEase.prototype.easeInCore = function (gradient) {
  29553. return (gradient * gradient);
  29554. };
  29555. return QuadraticEase;
  29556. }(EasingFunction));
  29557. BABYLON.QuadraticEase = QuadraticEase;
  29558. var QuarticEase = (function (_super) {
  29559. __extends(QuarticEase, _super);
  29560. function QuarticEase() {
  29561. return _super !== null && _super.apply(this, arguments) || this;
  29562. }
  29563. QuarticEase.prototype.easeInCore = function (gradient) {
  29564. return (gradient * gradient * gradient * gradient);
  29565. };
  29566. return QuarticEase;
  29567. }(EasingFunction));
  29568. BABYLON.QuarticEase = QuarticEase;
  29569. var QuinticEase = (function (_super) {
  29570. __extends(QuinticEase, _super);
  29571. function QuinticEase() {
  29572. return _super !== null && _super.apply(this, arguments) || this;
  29573. }
  29574. QuinticEase.prototype.easeInCore = function (gradient) {
  29575. return (gradient * gradient * gradient * gradient * gradient);
  29576. };
  29577. return QuinticEase;
  29578. }(EasingFunction));
  29579. BABYLON.QuinticEase = QuinticEase;
  29580. var SineEase = (function (_super) {
  29581. __extends(SineEase, _super);
  29582. function SineEase() {
  29583. return _super !== null && _super.apply(this, arguments) || this;
  29584. }
  29585. SineEase.prototype.easeInCore = function (gradient) {
  29586. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29587. };
  29588. return SineEase;
  29589. }(EasingFunction));
  29590. BABYLON.SineEase = SineEase;
  29591. var BezierCurveEase = (function (_super) {
  29592. __extends(BezierCurveEase, _super);
  29593. function BezierCurveEase(x1, y1, x2, y2) {
  29594. if (x1 === void 0) { x1 = 0; }
  29595. if (y1 === void 0) { y1 = 0; }
  29596. if (x2 === void 0) { x2 = 1; }
  29597. if (y2 === void 0) { y2 = 1; }
  29598. var _this = _super.call(this) || this;
  29599. _this.x1 = x1;
  29600. _this.y1 = y1;
  29601. _this.x2 = x2;
  29602. _this.y2 = y2;
  29603. return _this;
  29604. }
  29605. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29606. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29607. };
  29608. return BezierCurveEase;
  29609. }(EasingFunction));
  29610. BABYLON.BezierCurveEase = BezierCurveEase;
  29611. })(BABYLON || (BABYLON = {}));
  29612. //# sourceMappingURL=babylon.easing.js.map
  29613. var BABYLON;
  29614. (function (BABYLON) {
  29615. BABYLON.CameraInputTypes = {};
  29616. var CameraInputsManager = (function () {
  29617. function CameraInputsManager(camera) {
  29618. this.attached = {};
  29619. this.camera = camera;
  29620. this.checkInputs = function () { };
  29621. }
  29622. CameraInputsManager.prototype.add = function (input) {
  29623. var type = input.getSimpleName();
  29624. if (this.attached[type]) {
  29625. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29626. return;
  29627. }
  29628. this.attached[type] = input;
  29629. input.camera = this.camera;
  29630. //for checkInputs, we are dynamically creating a function
  29631. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29632. if (input.checkInputs) {
  29633. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29634. }
  29635. if (this.attachedElement) {
  29636. input.attachControl(this.attachedElement);
  29637. }
  29638. };
  29639. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29640. for (var cam in this.attached) {
  29641. var input = this.attached[cam];
  29642. if (input === inputToRemove) {
  29643. input.detachControl(this.attachedElement);
  29644. delete this.attached[cam];
  29645. this.rebuildInputCheck();
  29646. }
  29647. }
  29648. };
  29649. CameraInputsManager.prototype.removeByType = function (inputType) {
  29650. for (var cam in this.attached) {
  29651. var input = this.attached[cam];
  29652. if (input.getTypeName() === inputType) {
  29653. input.detachControl(this.attachedElement);
  29654. delete this.attached[cam];
  29655. this.rebuildInputCheck();
  29656. }
  29657. }
  29658. };
  29659. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29660. var current = this.checkInputs;
  29661. return function () {
  29662. current();
  29663. fn();
  29664. };
  29665. };
  29666. CameraInputsManager.prototype.attachInput = function (input) {
  29667. input.attachControl(this.attachedElement, this.noPreventDefault);
  29668. };
  29669. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29670. if (this.attachedElement) {
  29671. return;
  29672. }
  29673. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29674. this.attachedElement = element;
  29675. this.noPreventDefault = noPreventDefault;
  29676. for (var cam in this.attached) {
  29677. var input = this.attached[cam];
  29678. this.attached[cam].attachControl(element, noPreventDefault);
  29679. }
  29680. };
  29681. CameraInputsManager.prototype.detachElement = function (element) {
  29682. if (this.attachedElement !== element) {
  29683. return;
  29684. }
  29685. for (var cam in this.attached) {
  29686. var input = this.attached[cam];
  29687. this.attached[cam].detachControl(element);
  29688. }
  29689. this.attachedElement = null;
  29690. };
  29691. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29692. this.checkInputs = function () { };
  29693. for (var cam in this.attached) {
  29694. var input = this.attached[cam];
  29695. if (input.checkInputs) {
  29696. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29697. }
  29698. }
  29699. };
  29700. CameraInputsManager.prototype.clear = function () {
  29701. if (this.attachedElement) {
  29702. this.detachElement(this.attachedElement);
  29703. }
  29704. this.attached = {};
  29705. this.attachedElement = null;
  29706. this.checkInputs = function () { };
  29707. };
  29708. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29709. var inputs = {};
  29710. for (var cam in this.attached) {
  29711. var input = this.attached[cam];
  29712. var res = BABYLON.SerializationHelper.Serialize(input);
  29713. inputs[input.getTypeName()] = res;
  29714. }
  29715. serializedCamera.inputsmgr = inputs;
  29716. };
  29717. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29718. var parsedInputs = parsedCamera.inputsmgr;
  29719. if (parsedInputs) {
  29720. this.clear();
  29721. for (var n in parsedInputs) {
  29722. var construct = BABYLON.CameraInputTypes[n];
  29723. if (construct) {
  29724. var parsedinput = parsedInputs[n];
  29725. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29726. this.add(input);
  29727. }
  29728. }
  29729. }
  29730. else {
  29731. //2016-03-08 this part is for managing backward compatibility
  29732. for (var n in this.attached) {
  29733. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29734. if (construct) {
  29735. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29736. this.remove(this.attached[n]);
  29737. this.add(input);
  29738. }
  29739. }
  29740. }
  29741. };
  29742. return CameraInputsManager;
  29743. }());
  29744. BABYLON.CameraInputsManager = CameraInputsManager;
  29745. })(BABYLON || (BABYLON = {}));
  29746. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29747. /// <reference path="babylon.camera.ts" />
  29748. var BABYLON;
  29749. (function (BABYLON) {
  29750. var TargetCamera = (function (_super) {
  29751. __extends(TargetCamera, _super);
  29752. function TargetCamera(name, position, scene) {
  29753. var _this = _super.call(this, name, position, scene) || this;
  29754. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29755. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29756. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29757. _this.speed = 2.0;
  29758. _this.noRotationConstraint = false;
  29759. _this.lockedTarget = null;
  29760. _this._currentTarget = BABYLON.Vector3.Zero();
  29761. _this._viewMatrix = BABYLON.Matrix.Zero();
  29762. _this._camMatrix = BABYLON.Matrix.Zero();
  29763. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29764. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29765. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29766. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29767. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29768. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29769. _this._tempMatrix = BABYLON.Matrix.Zero();
  29770. return _this;
  29771. }
  29772. TargetCamera.prototype.getFrontPosition = function (distance) {
  29773. var direction = this.getTarget().subtract(this.position);
  29774. direction.normalize();
  29775. direction.scaleInPlace(distance);
  29776. return this.globalPosition.add(direction);
  29777. };
  29778. TargetCamera.prototype._getLockedTargetPosition = function () {
  29779. if (!this.lockedTarget) {
  29780. return null;
  29781. }
  29782. if (this.lockedTarget.absolutePosition) {
  29783. this.lockedTarget.computeWorldMatrix();
  29784. }
  29785. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29786. };
  29787. // Cache
  29788. TargetCamera.prototype._initCache = function () {
  29789. _super.prototype._initCache.call(this);
  29790. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29791. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29792. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29793. };
  29794. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29795. if (!ignoreParentClass) {
  29796. _super.prototype._updateCache.call(this);
  29797. }
  29798. var lockedTargetPosition = this._getLockedTargetPosition();
  29799. if (!lockedTargetPosition) {
  29800. this._cache.lockedTarget = null;
  29801. }
  29802. else {
  29803. if (!this._cache.lockedTarget) {
  29804. this._cache.lockedTarget = lockedTargetPosition.clone();
  29805. }
  29806. else {
  29807. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29808. }
  29809. }
  29810. this._cache.rotation.copyFrom(this.rotation);
  29811. if (this.rotationQuaternion)
  29812. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29813. };
  29814. // Synchronized
  29815. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29816. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29817. return false;
  29818. }
  29819. var lockedTargetPosition = this._getLockedTargetPosition();
  29820. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29821. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29822. };
  29823. // Methods
  29824. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29825. var engine = this.getEngine();
  29826. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29827. };
  29828. // Target
  29829. TargetCamera.prototype.setTarget = function (target) {
  29830. this.upVector.normalize();
  29831. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29832. this._camMatrix.invert();
  29833. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29834. var vDir = target.subtract(this.position);
  29835. if (vDir.x >= 0.0) {
  29836. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29837. }
  29838. else {
  29839. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29840. }
  29841. this.rotation.z = 0;
  29842. if (isNaN(this.rotation.x)) {
  29843. this.rotation.x = 0;
  29844. }
  29845. if (isNaN(this.rotation.y)) {
  29846. this.rotation.y = 0;
  29847. }
  29848. if (isNaN(this.rotation.z)) {
  29849. this.rotation.z = 0;
  29850. }
  29851. if (this.rotationQuaternion) {
  29852. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29853. }
  29854. };
  29855. /**
  29856. * Return the current target position of the camera. This value is expressed in local space.
  29857. */
  29858. TargetCamera.prototype.getTarget = function () {
  29859. return this._currentTarget;
  29860. };
  29861. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29862. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29863. };
  29864. TargetCamera.prototype._updatePosition = function () {
  29865. if (this.parent) {
  29866. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29867. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29868. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29869. return;
  29870. }
  29871. this.position.addInPlace(this.cameraDirection);
  29872. };
  29873. TargetCamera.prototype._checkInputs = function () {
  29874. var needToMove = this._decideIfNeedsToMove();
  29875. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29876. // Move
  29877. if (needToMove) {
  29878. this._updatePosition();
  29879. }
  29880. // Rotate
  29881. if (needToRotate) {
  29882. this.rotation.x += this.cameraRotation.x;
  29883. this.rotation.y += this.cameraRotation.y;
  29884. //rotate, if quaternion is set and rotation was used
  29885. if (this.rotationQuaternion) {
  29886. var len = this.rotation.lengthSquared();
  29887. if (len) {
  29888. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29889. }
  29890. }
  29891. if (!this.noRotationConstraint) {
  29892. var limit = (Math.PI / 2) * 0.95;
  29893. if (this.rotation.x > limit)
  29894. this.rotation.x = limit;
  29895. if (this.rotation.x < -limit)
  29896. this.rotation.x = -limit;
  29897. }
  29898. }
  29899. // Inertia
  29900. if (needToMove) {
  29901. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  29902. this.cameraDirection.x = 0;
  29903. }
  29904. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  29905. this.cameraDirection.y = 0;
  29906. }
  29907. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  29908. this.cameraDirection.z = 0;
  29909. }
  29910. this.cameraDirection.scaleInPlace(this.inertia);
  29911. }
  29912. if (needToRotate) {
  29913. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  29914. this.cameraRotation.x = 0;
  29915. }
  29916. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  29917. this.cameraRotation.y = 0;
  29918. }
  29919. this.cameraRotation.scaleInPlace(this.inertia);
  29920. }
  29921. _super.prototype._checkInputs.call(this);
  29922. };
  29923. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29924. if (this.rotationQuaternion) {
  29925. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29926. //update the up vector!
  29927. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29928. }
  29929. else {
  29930. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29931. }
  29932. };
  29933. TargetCamera.prototype._getViewMatrix = function () {
  29934. if (!this.lockedTarget) {
  29935. // Compute
  29936. this._updateCameraRotationMatrix();
  29937. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29938. // Computing target and final matrix
  29939. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29940. }
  29941. else {
  29942. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29943. }
  29944. if (this.getScene().useRightHandedSystem) {
  29945. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29946. }
  29947. else {
  29948. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29949. }
  29950. return this._viewMatrix;
  29951. };
  29952. /**
  29953. * @override
  29954. * Override Camera.createRigCamera
  29955. */
  29956. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29957. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29958. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29959. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29960. if (!this.rotationQuaternion) {
  29961. this.rotationQuaternion = new BABYLON.Quaternion();
  29962. }
  29963. rigCamera._cameraRigParams = {};
  29964. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29965. }
  29966. return rigCamera;
  29967. }
  29968. return null;
  29969. };
  29970. /**
  29971. * @override
  29972. * Override Camera._updateRigCameras
  29973. */
  29974. TargetCamera.prototype._updateRigCameras = function () {
  29975. var camLeft = this._rigCameras[0];
  29976. var camRight = this._rigCameras[1];
  29977. switch (this.cameraRigMode) {
  29978. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29979. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29980. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29981. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29982. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29983. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29984. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29985. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29986. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29987. camLeft.setTarget(this.getTarget());
  29988. camRight.setTarget(this.getTarget());
  29989. break;
  29990. case BABYLON.Camera.RIG_MODE_VR:
  29991. if (camLeft.rotationQuaternion) {
  29992. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29993. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29994. }
  29995. else {
  29996. camLeft.rotation.copyFrom(this.rotation);
  29997. camRight.rotation.copyFrom(this.rotation);
  29998. }
  29999. camLeft.position.copyFrom(this.position);
  30000. camRight.position.copyFrom(this.position);
  30001. break;
  30002. }
  30003. _super.prototype._updateRigCameras.call(this);
  30004. };
  30005. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30006. if (!this._rigCamTransformMatrix) {
  30007. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30008. }
  30009. var target = this.getTarget();
  30010. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30011. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30012. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30013. };
  30014. TargetCamera.prototype.getClassName = function () {
  30015. return "TargetCamera";
  30016. };
  30017. return TargetCamera;
  30018. }(BABYLON.Camera));
  30019. __decorate([
  30020. BABYLON.serializeAsVector3()
  30021. ], TargetCamera.prototype, "rotation", void 0);
  30022. __decorate([
  30023. BABYLON.serialize()
  30024. ], TargetCamera.prototype, "speed", void 0);
  30025. __decorate([
  30026. BABYLON.serializeAsMeshReference("lockedTargetId")
  30027. ], TargetCamera.prototype, "lockedTarget", void 0);
  30028. BABYLON.TargetCamera = TargetCamera;
  30029. })(BABYLON || (BABYLON = {}));
  30030. //# sourceMappingURL=babylon.targetCamera.js.map
  30031. var BABYLON;
  30032. (function (BABYLON) {
  30033. var ArcRotateCameraKeyboardMoveInput = (function () {
  30034. function ArcRotateCameraKeyboardMoveInput() {
  30035. this._keys = [];
  30036. this.keysUp = [38];
  30037. this.keysDown = [40];
  30038. this.keysLeft = [37];
  30039. this.keysRight = [39];
  30040. }
  30041. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30042. var _this = this;
  30043. element.tabIndex = 1;
  30044. this._onKeyDown = function (evt) {
  30045. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30046. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30047. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30048. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30049. var index = _this._keys.indexOf(evt.keyCode);
  30050. if (index === -1) {
  30051. _this._keys.push(evt.keyCode);
  30052. }
  30053. if (evt.preventDefault) {
  30054. if (!noPreventDefault) {
  30055. evt.preventDefault();
  30056. }
  30057. }
  30058. }
  30059. };
  30060. this._onKeyUp = function (evt) {
  30061. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30062. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30063. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30064. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30065. var index = _this._keys.indexOf(evt.keyCode);
  30066. if (index >= 0) {
  30067. _this._keys.splice(index, 1);
  30068. }
  30069. if (evt.preventDefault) {
  30070. if (!noPreventDefault) {
  30071. evt.preventDefault();
  30072. }
  30073. }
  30074. }
  30075. };
  30076. this._onLostFocus = function () {
  30077. _this._keys = [];
  30078. };
  30079. element.addEventListener("keydown", this._onKeyDown, false);
  30080. element.addEventListener("keyup", this._onKeyUp, false);
  30081. BABYLON.Tools.RegisterTopRootEvents([
  30082. { name: "blur", handler: this._onLostFocus }
  30083. ]);
  30084. };
  30085. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30086. if (element) {
  30087. element.removeEventListener("keydown", this._onKeyDown);
  30088. element.removeEventListener("keyup", this._onKeyUp);
  30089. }
  30090. BABYLON.Tools.UnregisterTopRootEvents([
  30091. { name: "blur", handler: this._onLostFocus }
  30092. ]);
  30093. this._keys = [];
  30094. this._onKeyDown = null;
  30095. this._onKeyUp = null;
  30096. this._onLostFocus = null;
  30097. };
  30098. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30099. if (this._onKeyDown) {
  30100. var camera = this.camera;
  30101. for (var index = 0; index < this._keys.length; index++) {
  30102. var keyCode = this._keys[index];
  30103. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30104. camera.inertialAlphaOffset -= 0.01;
  30105. }
  30106. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30107. camera.inertialBetaOffset -= 0.01;
  30108. }
  30109. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30110. camera.inertialAlphaOffset += 0.01;
  30111. }
  30112. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30113. camera.inertialBetaOffset += 0.01;
  30114. }
  30115. }
  30116. }
  30117. };
  30118. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30119. return "ArcRotateCameraKeyboardMoveInput";
  30120. };
  30121. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30122. return "keyboard";
  30123. };
  30124. return ArcRotateCameraKeyboardMoveInput;
  30125. }());
  30126. __decorate([
  30127. BABYLON.serialize()
  30128. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30129. __decorate([
  30130. BABYLON.serialize()
  30131. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30132. __decorate([
  30133. BABYLON.serialize()
  30134. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30135. __decorate([
  30136. BABYLON.serialize()
  30137. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30138. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30139. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30140. })(BABYLON || (BABYLON = {}));
  30141. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30142. var BABYLON;
  30143. (function (BABYLON) {
  30144. var ArcRotateCameraMouseWheelInput = (function () {
  30145. function ArcRotateCameraMouseWheelInput() {
  30146. this.wheelPrecision = 3.0;
  30147. }
  30148. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30149. var _this = this;
  30150. this._wheel = function (p, s) {
  30151. //sanity check - this should be a PointerWheel event.
  30152. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30153. return;
  30154. var event = p.event;
  30155. var delta = 0;
  30156. if (event.wheelDelta) {
  30157. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30158. }
  30159. else if (event.detail) {
  30160. delta = -event.detail / _this.wheelPrecision;
  30161. }
  30162. if (delta)
  30163. _this.camera.inertialRadiusOffset += delta;
  30164. if (event.preventDefault) {
  30165. if (!noPreventDefault) {
  30166. event.preventDefault();
  30167. }
  30168. }
  30169. };
  30170. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30171. };
  30172. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30173. if (this._observer && element) {
  30174. this.camera.getScene().onPointerObservable.remove(this._observer);
  30175. this._observer = null;
  30176. this._wheel = null;
  30177. }
  30178. };
  30179. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30180. return "ArcRotateCameraMouseWheelInput";
  30181. };
  30182. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30183. return "mousewheel";
  30184. };
  30185. return ArcRotateCameraMouseWheelInput;
  30186. }());
  30187. __decorate([
  30188. BABYLON.serialize()
  30189. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30190. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30191. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30192. })(BABYLON || (BABYLON = {}));
  30193. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30194. var BABYLON;
  30195. (function (BABYLON) {
  30196. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30197. var ArcRotateCameraPointersInput = (function () {
  30198. function ArcRotateCameraPointersInput() {
  30199. this.buttons = [0, 1, 2];
  30200. this.angularSensibilityX = 1000.0;
  30201. this.angularSensibilityY = 1000.0;
  30202. this.pinchPrecision = 6.0;
  30203. this.panningSensibility = 50.0;
  30204. this._isPanClick = false;
  30205. this.pinchInwards = true;
  30206. }
  30207. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30208. var _this = this;
  30209. var engine = this.camera.getEngine();
  30210. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30211. var pointA, pointB;
  30212. var previousPinchDistance = 0;
  30213. this._pointerInput = function (p, s) {
  30214. var evt = p.event;
  30215. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30216. return;
  30217. }
  30218. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30219. try {
  30220. evt.srcElement.setPointerCapture(evt.pointerId);
  30221. }
  30222. catch (e) {
  30223. //Nothing to do with the error. Execution will continue.
  30224. }
  30225. // Manage panning with pan button click
  30226. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30227. // manage pointers
  30228. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30229. if (pointA === undefined) {
  30230. pointA = cacheSoloPointer;
  30231. }
  30232. else if (pointB === undefined) {
  30233. pointB = cacheSoloPointer;
  30234. }
  30235. if (!noPreventDefault) {
  30236. evt.preventDefault();
  30237. element.focus();
  30238. }
  30239. }
  30240. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30241. try {
  30242. evt.srcElement.releasePointerCapture(evt.pointerId);
  30243. }
  30244. catch (e) {
  30245. //Nothing to do with the error.
  30246. }
  30247. cacheSoloPointer = null;
  30248. previousPinchDistance = 0;
  30249. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30250. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30251. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30252. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30253. pointA = pointB = undefined;
  30254. if (!noPreventDefault) {
  30255. evt.preventDefault();
  30256. }
  30257. }
  30258. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30259. if (!noPreventDefault) {
  30260. evt.preventDefault();
  30261. }
  30262. // One button down
  30263. if (pointA && pointB === undefined) {
  30264. if (_this.panningSensibility !== 0 &&
  30265. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30266. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30267. _this.camera
  30268. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30269. _this.camera
  30270. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30271. }
  30272. else {
  30273. var offsetX = evt.clientX - cacheSoloPointer.x;
  30274. var offsetY = evt.clientY - cacheSoloPointer.y;
  30275. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30276. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30277. }
  30278. cacheSoloPointer.x = evt.clientX;
  30279. cacheSoloPointer.y = evt.clientY;
  30280. }
  30281. else if (pointA && pointB) {
  30282. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30283. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30284. ed.x = evt.clientX;
  30285. ed.y = evt.clientY;
  30286. var direction = _this.pinchInwards ? 1 : -1;
  30287. var distX = pointA.x - pointB.x;
  30288. var distY = pointA.y - pointB.y;
  30289. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30290. if (previousPinchDistance === 0) {
  30291. previousPinchDistance = pinchSquaredDistance;
  30292. return;
  30293. }
  30294. if (pinchSquaredDistance !== previousPinchDistance) {
  30295. _this.camera
  30296. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30297. (_this.pinchPrecision *
  30298. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30299. direction);
  30300. previousPinchDistance = pinchSquaredDistance;
  30301. }
  30302. }
  30303. }
  30304. };
  30305. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30306. this._onContextMenu = function (evt) {
  30307. evt.preventDefault();
  30308. };
  30309. if (!this.camera._useCtrlForPanning) {
  30310. element.addEventListener("contextmenu", this._onContextMenu, false);
  30311. }
  30312. this._onLostFocus = function () {
  30313. //this._keys = [];
  30314. pointA = pointB = undefined;
  30315. previousPinchDistance = 0;
  30316. cacheSoloPointer = null;
  30317. };
  30318. this._onMouseMove = function (evt) {
  30319. if (!engine.isPointerLock) {
  30320. return;
  30321. }
  30322. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30323. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30324. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30325. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30326. if (!noPreventDefault) {
  30327. evt.preventDefault();
  30328. }
  30329. };
  30330. this._onGestureStart = function (e) {
  30331. if (window.MSGesture === undefined) {
  30332. return;
  30333. }
  30334. if (!_this._MSGestureHandler) {
  30335. _this._MSGestureHandler = new MSGesture();
  30336. _this._MSGestureHandler.target = element;
  30337. }
  30338. _this._MSGestureHandler.addPointer(e.pointerId);
  30339. };
  30340. this._onGesture = function (e) {
  30341. _this.camera.radius *= e.scale;
  30342. if (e.preventDefault) {
  30343. if (!noPreventDefault) {
  30344. e.stopPropagation();
  30345. e.preventDefault();
  30346. }
  30347. }
  30348. };
  30349. element.addEventListener("mousemove", this._onMouseMove, false);
  30350. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30351. element.addEventListener("MSGestureChange", this._onGesture, false);
  30352. BABYLON.Tools.RegisterTopRootEvents([
  30353. { name: "blur", handler: this._onLostFocus }
  30354. ]);
  30355. };
  30356. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30357. if (element && this._observer) {
  30358. this.camera.getScene().onPointerObservable.remove(this._observer);
  30359. this._observer = null;
  30360. element.removeEventListener("contextmenu", this._onContextMenu);
  30361. element.removeEventListener("mousemove", this._onMouseMove);
  30362. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30363. element.removeEventListener("MSGestureChange", this._onGesture);
  30364. this._isPanClick = false;
  30365. this.pinchInwards = true;
  30366. this._onMouseMove = null;
  30367. this._onGestureStart = null;
  30368. this._onGesture = null;
  30369. this._MSGestureHandler = null;
  30370. this._onLostFocus = null;
  30371. this._onContextMenu = null;
  30372. }
  30373. BABYLON.Tools.UnregisterTopRootEvents([
  30374. { name: "blur", handler: this._onLostFocus }
  30375. ]);
  30376. };
  30377. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30378. return "ArcRotateCameraPointersInput";
  30379. };
  30380. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30381. return "pointers";
  30382. };
  30383. return ArcRotateCameraPointersInput;
  30384. }());
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30400. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30401. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30402. })(BABYLON || (BABYLON = {}));
  30403. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30404. /// <reference path="babylon.targetCamera.ts" />
  30405. /// <reference path="..\Tools\babylon.tools.ts" />
  30406. var BABYLON;
  30407. (function (BABYLON) {
  30408. var ArcRotateCamera = (function (_super) {
  30409. __extends(ArcRotateCamera, _super);
  30410. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30411. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30412. _this.inertialAlphaOffset = 0;
  30413. _this.inertialBetaOffset = 0;
  30414. _this.inertialRadiusOffset = 0;
  30415. _this.lowerAlphaLimit = null;
  30416. _this.upperAlphaLimit = null;
  30417. _this.lowerBetaLimit = 0.01;
  30418. _this.upperBetaLimit = Math.PI;
  30419. _this.lowerRadiusLimit = null;
  30420. _this.upperRadiusLimit = null;
  30421. _this.inertialPanningX = 0;
  30422. _this.inertialPanningY = 0;
  30423. _this.panningInertia = 0.9;
  30424. //-- end properties for backward compatibility for inputs
  30425. _this.zoomOnFactor = 1;
  30426. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30427. _this.allowUpsideDown = true;
  30428. _this._viewMatrix = new BABYLON.Matrix();
  30429. // Panning
  30430. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30431. _this.checkCollisions = false;
  30432. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30433. _this._previousPosition = BABYLON.Vector3.Zero();
  30434. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30435. _this._newPosition = BABYLON.Vector3.Zero();
  30436. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30437. if (collidedMesh === void 0) { collidedMesh = null; }
  30438. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30439. newPosition.multiplyInPlace(_this._collider.radius);
  30440. }
  30441. if (!collidedMesh) {
  30442. _this._previousPosition.copyFrom(_this.position);
  30443. }
  30444. else {
  30445. _this.setPosition(newPosition);
  30446. if (_this.onCollide) {
  30447. _this.onCollide(collidedMesh);
  30448. }
  30449. }
  30450. // Recompute because of constraints
  30451. var cosa = Math.cos(_this.alpha);
  30452. var sina = Math.sin(_this.alpha);
  30453. var cosb = Math.cos(_this.beta);
  30454. var sinb = Math.sin(_this.beta);
  30455. if (sinb === 0) {
  30456. sinb = 0.0001;
  30457. }
  30458. var target = _this._getTargetPosition();
  30459. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30460. _this.position.copyFrom(_this._newPosition);
  30461. var up = _this.upVector;
  30462. if (_this.allowUpsideDown && _this.beta < 0) {
  30463. up = up.clone();
  30464. up = up.negate();
  30465. }
  30466. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30467. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30468. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30469. _this._collisionTriggered = false;
  30470. };
  30471. _this._target = BABYLON.Vector3.Zero();
  30472. if (target) {
  30473. _this.setTarget(target);
  30474. }
  30475. _this.alpha = alpha;
  30476. _this.beta = beta;
  30477. _this.radius = radius;
  30478. _this.getViewMatrix();
  30479. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30480. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30481. return _this;
  30482. }
  30483. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30484. get: function () {
  30485. return this._target;
  30486. },
  30487. set: function (value) {
  30488. this.setTarget(value);
  30489. },
  30490. enumerable: true,
  30491. configurable: true
  30492. });
  30493. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30494. //-- begin properties for backward compatibility for inputs
  30495. get: function () {
  30496. var pointers = this.inputs.attached["pointers"];
  30497. if (pointers)
  30498. return pointers.angularSensibilityX;
  30499. },
  30500. set: function (value) {
  30501. var pointers = this.inputs.attached["pointers"];
  30502. if (pointers) {
  30503. pointers.angularSensibilityX = value;
  30504. }
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30510. get: function () {
  30511. var pointers = this.inputs.attached["pointers"];
  30512. if (pointers)
  30513. return pointers.angularSensibilityY;
  30514. },
  30515. set: function (value) {
  30516. var pointers = this.inputs.attached["pointers"];
  30517. if (pointers) {
  30518. pointers.angularSensibilityY = value;
  30519. }
  30520. },
  30521. enumerable: true,
  30522. configurable: true
  30523. });
  30524. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30525. get: function () {
  30526. var pointers = this.inputs.attached["pointers"];
  30527. if (pointers)
  30528. return pointers.pinchPrecision;
  30529. },
  30530. set: function (value) {
  30531. var pointers = this.inputs.attached["pointers"];
  30532. if (pointers) {
  30533. pointers.pinchPrecision = value;
  30534. }
  30535. },
  30536. enumerable: true,
  30537. configurable: true
  30538. });
  30539. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30540. get: function () {
  30541. var pointers = this.inputs.attached["pointers"];
  30542. if (pointers)
  30543. return pointers.panningSensibility;
  30544. },
  30545. set: function (value) {
  30546. var pointers = this.inputs.attached["pointers"];
  30547. if (pointers) {
  30548. pointers.panningSensibility = value;
  30549. }
  30550. },
  30551. enumerable: true,
  30552. configurable: true
  30553. });
  30554. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30555. get: function () {
  30556. var keyboard = this.inputs.attached["keyboard"];
  30557. if (keyboard)
  30558. return keyboard.keysUp;
  30559. },
  30560. set: function (value) {
  30561. var keyboard = this.inputs.attached["keyboard"];
  30562. if (keyboard)
  30563. keyboard.keysUp = value;
  30564. },
  30565. enumerable: true,
  30566. configurable: true
  30567. });
  30568. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30569. get: function () {
  30570. var keyboard = this.inputs.attached["keyboard"];
  30571. if (keyboard)
  30572. return keyboard.keysDown;
  30573. },
  30574. set: function (value) {
  30575. var keyboard = this.inputs.attached["keyboard"];
  30576. if (keyboard)
  30577. keyboard.keysDown = value;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30583. get: function () {
  30584. var keyboard = this.inputs.attached["keyboard"];
  30585. if (keyboard)
  30586. return keyboard.keysLeft;
  30587. },
  30588. set: function (value) {
  30589. var keyboard = this.inputs.attached["keyboard"];
  30590. if (keyboard)
  30591. keyboard.keysLeft = value;
  30592. },
  30593. enumerable: true,
  30594. configurable: true
  30595. });
  30596. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30597. get: function () {
  30598. var keyboard = this.inputs.attached["keyboard"];
  30599. if (keyboard)
  30600. return keyboard.keysRight;
  30601. },
  30602. set: function (value) {
  30603. var keyboard = this.inputs.attached["keyboard"];
  30604. if (keyboard)
  30605. keyboard.keysRight = value;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30611. get: function () {
  30612. var mousewheel = this.inputs.attached["mousewheel"];
  30613. if (mousewheel)
  30614. return mousewheel.wheelPrecision;
  30615. },
  30616. set: function (value) {
  30617. var mousewheel = this.inputs.attached["mousewheel"];
  30618. if (mousewheel)
  30619. mousewheel.wheelPrecision = value;
  30620. },
  30621. enumerable: true,
  30622. configurable: true
  30623. });
  30624. // Cache
  30625. ArcRotateCamera.prototype._initCache = function () {
  30626. _super.prototype._initCache.call(this);
  30627. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30628. this._cache.alpha = undefined;
  30629. this._cache.beta = undefined;
  30630. this._cache.radius = undefined;
  30631. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30632. };
  30633. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30634. if (!ignoreParentClass) {
  30635. _super.prototype._updateCache.call(this);
  30636. }
  30637. this._cache._target.copyFrom(this._getTargetPosition());
  30638. this._cache.alpha = this.alpha;
  30639. this._cache.beta = this.beta;
  30640. this._cache.radius = this.radius;
  30641. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30642. };
  30643. ArcRotateCamera.prototype._getTargetPosition = function () {
  30644. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30645. var pos = this._targetHost.getAbsolutePosition();
  30646. if (this._targetBoundingCenter) {
  30647. pos.addToRef(this._targetBoundingCenter, this._target);
  30648. }
  30649. else {
  30650. this._target.copyFrom(pos);
  30651. }
  30652. }
  30653. var lockedTargetPosition = this._getLockedTargetPosition();
  30654. if (lockedTargetPosition) {
  30655. return lockedTargetPosition;
  30656. }
  30657. return this._target;
  30658. };
  30659. // Synchronized
  30660. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30661. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30662. return false;
  30663. return this._cache._target.equals(this._getTargetPosition())
  30664. && this._cache.alpha === this.alpha
  30665. && this._cache.beta === this.beta
  30666. && this._cache.radius === this.radius
  30667. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30668. };
  30669. // Methods
  30670. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30671. var _this = this;
  30672. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30673. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30674. this._useCtrlForPanning = useCtrlForPanning;
  30675. this._panningMouseButton = panningMouseButton;
  30676. this.inputs.attachElement(element, noPreventDefault);
  30677. this._reset = function () {
  30678. _this.inertialAlphaOffset = 0;
  30679. _this.inertialBetaOffset = 0;
  30680. _this.inertialRadiusOffset = 0;
  30681. };
  30682. };
  30683. ArcRotateCamera.prototype.detachControl = function (element) {
  30684. this.inputs.detachElement(element);
  30685. if (this._reset) {
  30686. this._reset();
  30687. }
  30688. };
  30689. ArcRotateCamera.prototype._checkInputs = function () {
  30690. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30691. if (this._collisionTriggered) {
  30692. return;
  30693. }
  30694. this.inputs.checkInputs();
  30695. // Inertia
  30696. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30697. if (this.getScene().useRightHandedSystem) {
  30698. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30699. }
  30700. else {
  30701. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30702. }
  30703. this.beta += this.inertialBetaOffset;
  30704. this.radius -= this.inertialRadiusOffset;
  30705. this.inertialAlphaOffset *= this.inertia;
  30706. this.inertialBetaOffset *= this.inertia;
  30707. this.inertialRadiusOffset *= this.inertia;
  30708. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30709. this.inertialAlphaOffset = 0;
  30710. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30711. this.inertialBetaOffset = 0;
  30712. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30713. this.inertialRadiusOffset = 0;
  30714. }
  30715. // Panning inertia
  30716. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30717. if (!this._localDirection) {
  30718. this._localDirection = BABYLON.Vector3.Zero();
  30719. this._transformedDirection = BABYLON.Vector3.Zero();
  30720. }
  30721. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30722. this._localDirection.multiplyInPlace(this.panningAxis);
  30723. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30724. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30725. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30726. if (!this.panningAxis.y) {
  30727. this._transformedDirection.y = 0;
  30728. }
  30729. if (!this._targetHost) {
  30730. this._target.addInPlace(this._transformedDirection);
  30731. }
  30732. this.inertialPanningX *= this.panningInertia;
  30733. this.inertialPanningY *= this.panningInertia;
  30734. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30735. this.inertialPanningX = 0;
  30736. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30737. this.inertialPanningY = 0;
  30738. }
  30739. // Limits
  30740. this._checkLimits();
  30741. _super.prototype._checkInputs.call(this);
  30742. };
  30743. ArcRotateCamera.prototype._checkLimits = function () {
  30744. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30745. if (this.allowUpsideDown && this.beta > Math.PI) {
  30746. this.beta = this.beta - (2 * Math.PI);
  30747. }
  30748. }
  30749. else {
  30750. if (this.beta < this.lowerBetaLimit) {
  30751. this.beta = this.lowerBetaLimit;
  30752. }
  30753. }
  30754. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30755. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30756. this.beta = this.beta + (2 * Math.PI);
  30757. }
  30758. }
  30759. else {
  30760. if (this.beta > this.upperBetaLimit) {
  30761. this.beta = this.upperBetaLimit;
  30762. }
  30763. }
  30764. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30765. this.alpha = this.lowerAlphaLimit;
  30766. }
  30767. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30768. this.alpha = this.upperAlphaLimit;
  30769. }
  30770. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30771. this.radius = this.lowerRadiusLimit;
  30772. }
  30773. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30774. this.radius = this.upperRadiusLimit;
  30775. }
  30776. };
  30777. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30778. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30779. this.radius = radiusv3.length();
  30780. // Alpha
  30781. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30782. if (radiusv3.z < 0) {
  30783. this.alpha = 2 * Math.PI - this.alpha;
  30784. }
  30785. // Beta
  30786. this.beta = Math.acos(radiusv3.y / this.radius);
  30787. this._checkLimits();
  30788. };
  30789. ArcRotateCamera.prototype.setPosition = function (position) {
  30790. if (this.position.equals(position)) {
  30791. return;
  30792. }
  30793. this.position.copyFrom(position);
  30794. this.rebuildAnglesAndRadius();
  30795. };
  30796. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30797. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30798. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30799. if (target.getBoundingInfo) {
  30800. if (toBoundingCenter) {
  30801. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30802. }
  30803. else {
  30804. this._targetBoundingCenter = null;
  30805. }
  30806. this._targetHost = target;
  30807. this._target = this._getTargetPosition();
  30808. }
  30809. else {
  30810. var newTarget = target;
  30811. var currentTarget = this._getTargetPosition();
  30812. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  30813. return;
  30814. }
  30815. this._target = newTarget;
  30816. this._targetBoundingCenter = null;
  30817. }
  30818. this.rebuildAnglesAndRadius();
  30819. };
  30820. ArcRotateCamera.prototype._getViewMatrix = function () {
  30821. // Compute
  30822. var cosa = Math.cos(this.alpha);
  30823. var sina = Math.sin(this.alpha);
  30824. var cosb = Math.cos(this.beta);
  30825. var sinb = Math.sin(this.beta);
  30826. if (sinb === 0) {
  30827. sinb = 0.0001;
  30828. }
  30829. var target = this._getTargetPosition();
  30830. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30831. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30832. if (!this._collider) {
  30833. this._collider = new BABYLON.Collider();
  30834. }
  30835. this._collider.radius = this.collisionRadius;
  30836. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30837. this._collisionTriggered = true;
  30838. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30839. }
  30840. else {
  30841. this.position.copyFrom(this._newPosition);
  30842. var up = this.upVector;
  30843. if (this.allowUpsideDown && sinb < 0) {
  30844. up = up.clone();
  30845. up = up.negate();
  30846. }
  30847. if (this.getScene().useRightHandedSystem) {
  30848. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30849. }
  30850. else {
  30851. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30852. }
  30853. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30854. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30855. }
  30856. this._currentTarget = target;
  30857. return this._viewMatrix;
  30858. };
  30859. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30860. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30861. meshes = meshes || this.getScene().meshes;
  30862. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30863. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30864. this.radius = distance * this.zoomOnFactor;
  30865. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30866. };
  30867. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30868. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30869. var meshesOrMinMaxVector;
  30870. var distance;
  30871. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30872. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30873. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30874. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30875. }
  30876. else {
  30877. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30878. distance = meshesOrMinMaxVectorAndDistance.distance;
  30879. }
  30880. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30881. if (!doNotUpdateMaxZ) {
  30882. this.maxZ = distance * 2;
  30883. }
  30884. };
  30885. /**
  30886. * @override
  30887. * Override Camera.createRigCamera
  30888. */
  30889. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30890. var alphaShift;
  30891. switch (this.cameraRigMode) {
  30892. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30893. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30894. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30895. case BABYLON.Camera.RIG_MODE_VR:
  30896. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30897. break;
  30898. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30899. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30900. break;
  30901. }
  30902. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  30903. rigCam._cameraRigParams = {};
  30904. return rigCam;
  30905. };
  30906. /**
  30907. * @override
  30908. * Override Camera._updateRigCameras
  30909. */
  30910. ArcRotateCamera.prototype._updateRigCameras = function () {
  30911. var camLeft = this._rigCameras[0];
  30912. var camRight = this._rigCameras[1];
  30913. camLeft.beta = camRight.beta = this.beta;
  30914. camLeft.radius = camRight.radius = this.radius;
  30915. switch (this.cameraRigMode) {
  30916. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30917. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30918. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30919. case BABYLON.Camera.RIG_MODE_VR:
  30920. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30921. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30922. break;
  30923. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30924. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30925. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30926. break;
  30927. }
  30928. _super.prototype._updateRigCameras.call(this);
  30929. };
  30930. ArcRotateCamera.prototype.dispose = function () {
  30931. this.inputs.clear();
  30932. _super.prototype.dispose.call(this);
  30933. };
  30934. ArcRotateCamera.prototype.getClassName = function () {
  30935. return "ArcRotateCamera";
  30936. };
  30937. return ArcRotateCamera;
  30938. }(BABYLON.TargetCamera));
  30939. __decorate([
  30940. BABYLON.serialize()
  30941. ], ArcRotateCamera.prototype, "alpha", void 0);
  30942. __decorate([
  30943. BABYLON.serialize()
  30944. ], ArcRotateCamera.prototype, "beta", void 0);
  30945. __decorate([
  30946. BABYLON.serialize()
  30947. ], ArcRotateCamera.prototype, "radius", void 0);
  30948. __decorate([
  30949. BABYLON.serializeAsVector3("target")
  30950. ], ArcRotateCamera.prototype, "_target", void 0);
  30951. __decorate([
  30952. BABYLON.serialize()
  30953. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30954. __decorate([
  30955. BABYLON.serialize()
  30956. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30957. __decorate([
  30958. BABYLON.serialize()
  30959. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30960. __decorate([
  30961. BABYLON.serialize()
  30962. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30963. __decorate([
  30964. BABYLON.serialize()
  30965. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30966. __decorate([
  30967. BABYLON.serialize()
  30968. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30969. __decorate([
  30970. BABYLON.serialize()
  30971. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30972. __decorate([
  30973. BABYLON.serialize()
  30974. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30975. __decorate([
  30976. BABYLON.serialize()
  30977. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30978. __decorate([
  30979. BABYLON.serialize()
  30980. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30981. __decorate([
  30982. BABYLON.serialize()
  30983. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30984. __decorate([
  30985. BABYLON.serialize()
  30986. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  30987. __decorate([
  30988. BABYLON.serialize()
  30989. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30990. __decorate([
  30991. BABYLON.serialize()
  30992. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30993. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30994. })(BABYLON || (BABYLON = {}));
  30995. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30996. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30997. var BABYLON;
  30998. (function (BABYLON) {
  30999. var ArcRotateCameraInputsManager = (function (_super) {
  31000. __extends(ArcRotateCameraInputsManager, _super);
  31001. function ArcRotateCameraInputsManager(camera) {
  31002. return _super.call(this, camera) || this;
  31003. }
  31004. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31005. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31006. return this;
  31007. };
  31008. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31009. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31010. return this;
  31011. };
  31012. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31013. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31014. return this;
  31015. };
  31016. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31017. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31018. return this;
  31019. };
  31020. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31021. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31022. return this;
  31023. };
  31024. return ArcRotateCameraInputsManager;
  31025. }(BABYLON.CameraInputsManager));
  31026. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31027. })(BABYLON || (BABYLON = {}));
  31028. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31029. var BABYLON;
  31030. (function (BABYLON) {
  31031. var CubeTexture = (function (_super) {
  31032. __extends(CubeTexture, _super);
  31033. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  31034. if (onLoad === void 0) { onLoad = null; }
  31035. if (onError === void 0) { onError = null; }
  31036. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31037. var _this = _super.call(this, scene) || this;
  31038. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  31039. _this.name = rootUrl;
  31040. _this.url = rootUrl;
  31041. _this._noMipmap = noMipmap;
  31042. _this.hasAlpha = false;
  31043. _this._format = format;
  31044. if (!rootUrl && !files) {
  31045. return _this;
  31046. }
  31047. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  31048. if (!files) {
  31049. if (!extensions) {
  31050. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  31051. }
  31052. files = [];
  31053. for (var index = 0; index < extensions.length; index++) {
  31054. files.push(rootUrl + extensions[index]);
  31055. }
  31056. _this._extensions = extensions;
  31057. }
  31058. _this._files = files;
  31059. if (!_this._texture) {
  31060. if (!scene.useDelayedTextureLoading) {
  31061. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  31062. }
  31063. else {
  31064. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31065. }
  31066. }
  31067. else if (onLoad) {
  31068. if (_this._texture.isReady) {
  31069. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  31070. }
  31071. else {
  31072. _this._texture.onLoadedCallbacks.push(onLoad);
  31073. }
  31074. }
  31075. _this.isCube = true;
  31076. _this._textureMatrix = BABYLON.Matrix.Identity();
  31077. return _this;
  31078. }
  31079. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  31080. return new CubeTexture("", scene, null, noMipmap, files);
  31081. };
  31082. // Methods
  31083. CubeTexture.prototype.delayLoad = function () {
  31084. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31085. return;
  31086. }
  31087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31088. this._texture = this._getFromCache(this.url, this._noMipmap);
  31089. if (!this._texture) {
  31090. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  31091. }
  31092. };
  31093. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  31094. return this._textureMatrix;
  31095. };
  31096. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  31097. var texture = BABYLON.SerializationHelper.Parse(function () {
  31098. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  31099. }, parsedTexture, scene);
  31100. // Animations
  31101. if (parsedTexture.animations) {
  31102. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31103. var parsedAnimation = parsedTexture.animations[animationIndex];
  31104. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31105. }
  31106. }
  31107. return texture;
  31108. };
  31109. CubeTexture.prototype.clone = function () {
  31110. var _this = this;
  31111. return BABYLON.SerializationHelper.Clone(function () {
  31112. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  31113. }, this);
  31114. };
  31115. return CubeTexture;
  31116. }(BABYLON.BaseTexture));
  31117. BABYLON.CubeTexture = CubeTexture;
  31118. })(BABYLON || (BABYLON = {}));
  31119. //# sourceMappingURL=babylon.cubeTexture.js.map
  31120. var BABYLON;
  31121. (function (BABYLON) {
  31122. var RenderTargetTexture = (function (_super) {
  31123. __extends(RenderTargetTexture, _super);
  31124. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  31125. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  31126. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31127. if (isCube === void 0) { isCube = false; }
  31128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31129. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31130. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  31131. if (isMulti === void 0) { isMulti = false; }
  31132. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  31133. _this.isCube = isCube;
  31134. /**
  31135. * Use this list to define the list of mesh you want to render.
  31136. */
  31137. _this.renderList = new Array();
  31138. _this.renderParticles = true;
  31139. _this.renderSprites = false;
  31140. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  31141. // Events
  31142. /**
  31143. * An event triggered when the texture is unbind.
  31144. * @type {BABYLON.Observable}
  31145. */
  31146. _this.onAfterUnbindObservable = new BABYLON.Observable();
  31147. /**
  31148. * An event triggered before rendering the texture
  31149. * @type {BABYLON.Observable}
  31150. */
  31151. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31152. /**
  31153. * An event triggered after rendering the texture
  31154. * @type {BABYLON.Observable}
  31155. */
  31156. _this.onAfterRenderObservable = new BABYLON.Observable();
  31157. /**
  31158. * An event triggered after the texture clear
  31159. * @type {BABYLON.Observable}
  31160. */
  31161. _this.onClearObservable = new BABYLON.Observable();
  31162. _this._currentRefreshId = -1;
  31163. _this._refreshRate = 1;
  31164. _this._samples = 1;
  31165. scene = _this.getScene();
  31166. _this.name = name;
  31167. _this.isRenderTarget = true;
  31168. _this._size = size;
  31169. _this._generateMipMaps = generateMipMaps;
  31170. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  31171. // Rendering groups
  31172. _this._renderingManager = new BABYLON.RenderingManager(scene);
  31173. if (isMulti) {
  31174. return _this;
  31175. }
  31176. _this._renderTargetOptions = {
  31177. generateMipMaps: generateMipMaps,
  31178. type: type,
  31179. samplingMode: samplingMode,
  31180. generateDepthBuffer: generateDepthBuffer,
  31181. generateStencilBuffer: generateStencilBuffer
  31182. };
  31183. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31184. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31185. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31186. }
  31187. if (isCube) {
  31188. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  31189. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  31190. _this._textureMatrix = BABYLON.Matrix.Identity();
  31191. }
  31192. else {
  31193. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  31194. }
  31195. return _this;
  31196. }
  31197. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  31198. get: function () {
  31199. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  31205. get: function () {
  31206. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  31207. },
  31208. enumerable: true,
  31209. configurable: true
  31210. });
  31211. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  31212. get: function () {
  31213. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  31219. set: function (callback) {
  31220. if (this._onAfterUnbindObserver) {
  31221. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  31222. }
  31223. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  31224. },
  31225. enumerable: true,
  31226. configurable: true
  31227. });
  31228. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  31229. set: function (callback) {
  31230. if (this._onBeforeRenderObserver) {
  31231. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31232. }
  31233. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  31239. set: function (callback) {
  31240. if (this._onAfterRenderObserver) {
  31241. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31242. }
  31243. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31244. },
  31245. enumerable: true,
  31246. configurable: true
  31247. });
  31248. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31249. set: function (callback) {
  31250. if (this._onClearObserver) {
  31251. this.onClearObservable.remove(this._onClearObserver);
  31252. }
  31253. this._onClearObserver = this.onClearObservable.add(callback);
  31254. },
  31255. enumerable: true,
  31256. configurable: true
  31257. });
  31258. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31259. get: function () {
  31260. return this._renderTargetOptions;
  31261. },
  31262. enumerable: true,
  31263. configurable: true
  31264. });
  31265. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31266. get: function () {
  31267. return this._samples;
  31268. },
  31269. set: function (value) {
  31270. if (this._samples === value) {
  31271. return;
  31272. }
  31273. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31274. },
  31275. enumerable: true,
  31276. configurable: true
  31277. });
  31278. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31279. this._currentRefreshId = -1;
  31280. };
  31281. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31282. get: function () {
  31283. return this._refreshRate;
  31284. },
  31285. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31286. set: function (value) {
  31287. this._refreshRate = value;
  31288. this.resetRefreshCounter();
  31289. },
  31290. enumerable: true,
  31291. configurable: true
  31292. });
  31293. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31294. if (!this._postProcessManager) {
  31295. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31296. this._postProcesses = new Array();
  31297. }
  31298. this._postProcesses.push(postProcess);
  31299. this._postProcesses[0].autoClear = false;
  31300. };
  31301. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31302. if (!this._postProcesses) {
  31303. return;
  31304. }
  31305. if (dispose) {
  31306. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31307. var postProcess = _a[_i];
  31308. postProcess.dispose();
  31309. postProcess = null;
  31310. }
  31311. }
  31312. this._postProcesses = [];
  31313. };
  31314. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31315. if (!this._postProcesses) {
  31316. return;
  31317. }
  31318. var index = this._postProcesses.indexOf(postProcess);
  31319. if (index === -1) {
  31320. return;
  31321. }
  31322. this._postProcesses.splice(index, 1);
  31323. if (this._postProcesses.length > 0) {
  31324. this._postProcesses[0].autoClear = false;
  31325. }
  31326. };
  31327. RenderTargetTexture.prototype._shouldRender = function () {
  31328. if (this._currentRefreshId === -1) {
  31329. this._currentRefreshId = 1;
  31330. return true;
  31331. }
  31332. if (this.refreshRate === this._currentRefreshId) {
  31333. this._currentRefreshId = 1;
  31334. return true;
  31335. }
  31336. this._currentRefreshId++;
  31337. return false;
  31338. };
  31339. RenderTargetTexture.prototype.isReady = function () {
  31340. if (!this.getScene().renderTargetsEnabled) {
  31341. return false;
  31342. }
  31343. return _super.prototype.isReady.call(this);
  31344. };
  31345. RenderTargetTexture.prototype.getRenderSize = function () {
  31346. return this._size;
  31347. };
  31348. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31349. get: function () {
  31350. return true;
  31351. },
  31352. enumerable: true,
  31353. configurable: true
  31354. });
  31355. RenderTargetTexture.prototype.scale = function (ratio) {
  31356. var newSize = this._size * ratio;
  31357. this.resize(newSize);
  31358. };
  31359. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31360. if (this.isCube) {
  31361. return this._textureMatrix;
  31362. }
  31363. return _super.prototype.getReflectionTextureMatrix.call(this);
  31364. };
  31365. RenderTargetTexture.prototype.resize = function (size) {
  31366. this.releaseInternalTexture();
  31367. if (this.isCube) {
  31368. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31369. }
  31370. else {
  31371. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31372. }
  31373. };
  31374. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31375. var scene = this.getScene();
  31376. var engine = scene.getEngine();
  31377. if (this.useCameraPostProcesses !== undefined) {
  31378. useCameraPostProcess = this.useCameraPostProcesses;
  31379. }
  31380. if (this._waitingRenderList) {
  31381. this.renderList = [];
  31382. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31383. var id = this._waitingRenderList[index];
  31384. this.renderList.push(scene.getMeshByID(id));
  31385. }
  31386. delete this._waitingRenderList;
  31387. }
  31388. // Is predicate defined?
  31389. if (this.renderListPredicate) {
  31390. this.renderList.splice(0); // Clear previous renderList
  31391. var sceneMeshes = this.getScene().meshes;
  31392. for (var index = 0; index < sceneMeshes.length; index++) {
  31393. var mesh = sceneMeshes[index];
  31394. if (this.renderListPredicate(mesh)) {
  31395. this.renderList.push(mesh);
  31396. }
  31397. }
  31398. }
  31399. if (this.renderList && this.renderList.length === 0) {
  31400. return;
  31401. }
  31402. // Set custom projection.
  31403. // Needs to be before binding to prevent changing the aspect ratio.
  31404. var camera;
  31405. if (this.activeCamera) {
  31406. camera = this.activeCamera;
  31407. engine.setViewport(this.activeCamera.viewport);
  31408. if (this.activeCamera !== scene.activeCamera) {
  31409. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31410. }
  31411. }
  31412. else {
  31413. camera = scene.activeCamera;
  31414. engine.setViewport(scene.activeCamera.viewport);
  31415. }
  31416. // Prepare renderingManager
  31417. this._renderingManager.reset();
  31418. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31419. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31420. var sceneRenderId = scene.getRenderId();
  31421. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31422. var mesh = currentRenderList[meshIndex];
  31423. if (mesh) {
  31424. if (!mesh.isReady()) {
  31425. // Reset _currentRefreshId
  31426. this.resetRefreshCounter();
  31427. continue;
  31428. }
  31429. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31430. var isMasked = void 0;
  31431. if (!this.renderList) {
  31432. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31433. }
  31434. else {
  31435. isMasked = false;
  31436. }
  31437. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31438. mesh._activate(sceneRenderId);
  31439. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31440. var subMesh = mesh.subMeshes[subIndex];
  31441. scene._activeIndices.addCount(subMesh.indexCount, false);
  31442. this._renderingManager.dispatch(subMesh);
  31443. }
  31444. }
  31445. }
  31446. }
  31447. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31448. var particleSystem = scene.particleSystems[particleIndex];
  31449. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31450. continue;
  31451. }
  31452. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31453. this._renderingManager.dispatchParticles(particleSystem);
  31454. }
  31455. }
  31456. if (this.isCube) {
  31457. for (var face = 0; face < 6; face++) {
  31458. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31459. scene.incrementRenderId();
  31460. scene.resetCachedMaterial();
  31461. }
  31462. }
  31463. else {
  31464. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31465. }
  31466. this.onAfterUnbindObservable.notifyObservers(this);
  31467. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31468. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31469. }
  31470. engine.setViewport(scene.activeCamera.viewport);
  31471. scene.resetCachedMaterial();
  31472. };
  31473. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31474. var _this = this;
  31475. var scene = this.getScene();
  31476. var engine = scene.getEngine();
  31477. // Bind
  31478. if (this._postProcessManager) {
  31479. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31480. }
  31481. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31482. if (this.isCube) {
  31483. engine.bindFramebuffer(this._texture, faceIndex);
  31484. }
  31485. else {
  31486. engine.bindFramebuffer(this._texture);
  31487. }
  31488. }
  31489. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31490. // Clear
  31491. if (this.onClearObservable.hasObservers()) {
  31492. this.onClearObservable.notifyObservers(engine);
  31493. }
  31494. else {
  31495. engine.clear(scene.clearColor, true, true, true);
  31496. }
  31497. if (!this._doNotChangeAspectRatio) {
  31498. scene.updateTransformMatrix(true);
  31499. }
  31500. // Render
  31501. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31502. if (this._postProcessManager) {
  31503. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31504. }
  31505. else if (useCameraPostProcess) {
  31506. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31507. }
  31508. if (!this._doNotChangeAspectRatio) {
  31509. scene.updateTransformMatrix(true);
  31510. }
  31511. // Dump ?
  31512. if (dumpForDebug) {
  31513. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31514. }
  31515. // Unbind
  31516. if (!this.isCube || faceIndex === 5) {
  31517. if (this.isCube) {
  31518. if (faceIndex === 5) {
  31519. engine.generateMipMapsForCubemap(this._texture);
  31520. }
  31521. }
  31522. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31523. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31524. });
  31525. }
  31526. else {
  31527. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31528. }
  31529. };
  31530. /**
  31531. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31532. * This allowed control for front to back rendering or reversly depending of the special needs.
  31533. *
  31534. * @param renderingGroupId The rendering group id corresponding to its index
  31535. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31536. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31537. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31538. */
  31539. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31540. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31541. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31542. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31543. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31544. };
  31545. /**
  31546. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31547. *
  31548. * @param renderingGroupId The rendering group id corresponding to its index
  31549. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31550. */
  31551. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31552. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31553. };
  31554. RenderTargetTexture.prototype.clone = function () {
  31555. var textureSize = this.getSize();
  31556. 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);
  31557. // Base texture
  31558. newTexture.hasAlpha = this.hasAlpha;
  31559. newTexture.level = this.level;
  31560. // RenderTarget Texture
  31561. newTexture.coordinatesMode = this.coordinatesMode;
  31562. newTexture.renderList = this.renderList.slice(0);
  31563. return newTexture;
  31564. };
  31565. RenderTargetTexture.prototype.serialize = function () {
  31566. if (!this.name) {
  31567. return null;
  31568. }
  31569. var serializationObject = _super.prototype.serialize.call(this);
  31570. serializationObject.renderTargetSize = this.getRenderSize();
  31571. serializationObject.renderList = [];
  31572. for (var index = 0; index < this.renderList.length; index++) {
  31573. serializationObject.renderList.push(this.renderList[index].id);
  31574. }
  31575. return serializationObject;
  31576. };
  31577. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  31578. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  31579. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  31580. };
  31581. RenderTargetTexture.prototype.dispose = function () {
  31582. if (this._postProcessManager) {
  31583. this._postProcessManager.dispose();
  31584. this._postProcessManager = null;
  31585. }
  31586. this.clearPostProcesses(true);
  31587. // Remove from custom render targets
  31588. var scene = this.getScene();
  31589. var index = scene.customRenderTargets.indexOf(this);
  31590. if (index >= 0) {
  31591. scene.customRenderTargets.splice(index, 1);
  31592. }
  31593. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  31594. var camera = _a[_i];
  31595. index = camera.customRenderTargets.indexOf(this);
  31596. if (index >= 0) {
  31597. camera.customRenderTargets.splice(index, 1);
  31598. }
  31599. }
  31600. _super.prototype.dispose.call(this);
  31601. };
  31602. return RenderTargetTexture;
  31603. }(BABYLON.Texture));
  31604. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31605. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31606. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31607. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31608. })(BABYLON || (BABYLON = {}));
  31609. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31610. var BABYLON;
  31611. (function (BABYLON) {
  31612. ;
  31613. var MultiRenderTarget = (function (_super) {
  31614. __extends(MultiRenderTarget, _super);
  31615. function MultiRenderTarget(name, size, count, scene, options) {
  31616. var _this = this;
  31617. options = options || {};
  31618. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31619. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31620. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31621. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31622. if (!_this.isSupported) {
  31623. _this.dispose();
  31624. return;
  31625. }
  31626. var types = [];
  31627. var samplingModes = [];
  31628. for (var i = 0; i < count; i++) {
  31629. if (options.types && options.types[i]) {
  31630. types.push(options.types[i]);
  31631. }
  31632. else {
  31633. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31634. }
  31635. if (options.samplingModes && options.samplingModes[i]) {
  31636. samplingModes.push(options.samplingModes[i]);
  31637. }
  31638. else {
  31639. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31640. }
  31641. }
  31642. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31643. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31644. _this._count = count;
  31645. _this._size = size;
  31646. _this._multiRenderTargetOptions = {
  31647. samplingModes: samplingModes,
  31648. generateMipMaps: generateMipMaps,
  31649. generateDepthBuffer: generateDepthBuffer,
  31650. generateStencilBuffer: generateStencilBuffer,
  31651. generateDepthTexture: generateDepthTexture,
  31652. types: types,
  31653. textureCount: count
  31654. };
  31655. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31656. _this._createInternalTextures();
  31657. return _this;
  31658. }
  31659. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31660. get: function () {
  31661. var engine = this.getScene().getEngine();
  31662. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31663. },
  31664. enumerable: true,
  31665. configurable: true
  31666. });
  31667. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31668. get: function () {
  31669. return this._textures;
  31670. },
  31671. enumerable: true,
  31672. configurable: true
  31673. });
  31674. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31675. get: function () {
  31676. return this._textures[this._textures.length - 1];
  31677. },
  31678. enumerable: true,
  31679. configurable: true
  31680. });
  31681. MultiRenderTarget.prototype._createInternalTextures = function () {
  31682. this._textures = [];
  31683. for (var i = 0; i < this._webGLTextures.length; i++) {
  31684. var texture = new BABYLON.Texture(null, this.getScene());
  31685. texture._texture = this._webGLTextures[i];
  31686. this._textures.push(texture);
  31687. }
  31688. // Keeps references to frame buffer and stencil/depth buffer
  31689. this._texture = this._webGLTextures[0];
  31690. };
  31691. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31692. get: function () {
  31693. return this._samples;
  31694. },
  31695. set: function (value) {
  31696. if (this._samples === value) {
  31697. return;
  31698. }
  31699. for (var i = 0; i < this._webGLTextures.length; i++) {
  31700. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31701. }
  31702. },
  31703. enumerable: true,
  31704. configurable: true
  31705. });
  31706. MultiRenderTarget.prototype.resize = function (size) {
  31707. this.releaseInternalTextures();
  31708. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31709. this._createInternalTextures();
  31710. };
  31711. MultiRenderTarget.prototype.dispose = function () {
  31712. this.releaseInternalTextures();
  31713. _super.prototype.dispose.call(this);
  31714. };
  31715. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31716. if (!this._webGLTextures) {
  31717. return;
  31718. }
  31719. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31720. if (this._webGLTextures[i] !== undefined) {
  31721. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31722. this._webGLTextures.splice(i, 1);
  31723. }
  31724. }
  31725. };
  31726. return MultiRenderTarget;
  31727. }(BABYLON.RenderTargetTexture));
  31728. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31729. })(BABYLON || (BABYLON = {}));
  31730. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31731. /// <reference path="babylon.renderTargetTexture.ts" />
  31732. var BABYLON;
  31733. (function (BABYLON) {
  31734. var MirrorTexture = (function (_super) {
  31735. __extends(MirrorTexture, _super);
  31736. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31737. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31738. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31739. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31740. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31741. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31742. _this._transformMatrix = BABYLON.Matrix.Zero();
  31743. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31744. _this._blurKernelX = 0;
  31745. _this._blurKernelY = 0;
  31746. _this._blurRatio = 1.0;
  31747. _this.onBeforeRenderObservable.add(function () {
  31748. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31749. _this._savedViewMatrix = scene.getViewMatrix();
  31750. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31751. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31752. scene.clipPlane = _this.mirrorPlane;
  31753. scene.getEngine().cullBackFaces = false;
  31754. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31755. });
  31756. _this.onAfterRenderObservable.add(function () {
  31757. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31758. scene.getEngine().cullBackFaces = true;
  31759. scene._mirroredCameraPosition = null;
  31760. delete scene.clipPlane;
  31761. });
  31762. return _this;
  31763. }
  31764. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31765. get: function () {
  31766. return this._blurRatio;
  31767. },
  31768. set: function (value) {
  31769. if (this._blurRatio === value) {
  31770. return;
  31771. }
  31772. this._blurRatio = value;
  31773. this._preparePostProcesses();
  31774. },
  31775. enumerable: true,
  31776. configurable: true
  31777. });
  31778. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  31779. set: function (value) {
  31780. this.blurKernelX = value;
  31781. this.blurKernelY = value;
  31782. },
  31783. enumerable: true,
  31784. configurable: true
  31785. });
  31786. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  31787. get: function () {
  31788. return this._blurKernelX;
  31789. },
  31790. set: function (value) {
  31791. if (this._blurKernelX === value) {
  31792. return;
  31793. }
  31794. this._blurKernelX = value;
  31795. this._preparePostProcesses();
  31796. },
  31797. enumerable: true,
  31798. configurable: true
  31799. });
  31800. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  31801. get: function () {
  31802. return this._blurKernelY;
  31803. },
  31804. set: function (value) {
  31805. if (this._blurKernelY === value) {
  31806. return;
  31807. }
  31808. this._blurKernelY = value;
  31809. this._preparePostProcesses();
  31810. },
  31811. enumerable: true,
  31812. configurable: true
  31813. });
  31814. MirrorTexture.prototype._preparePostProcesses = function () {
  31815. this.clearPostProcesses(true);
  31816. if (this._blurKernelX && this._blurKernelY) {
  31817. var engine = this.getScene().getEngine();
  31818. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  31819. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  31820. this._blurX.autoClear = false;
  31821. if (this._blurRatio === 1 && this.samples < 2) {
  31822. this._blurX.outputTexture = this._texture;
  31823. }
  31824. else {
  31825. this._blurX.alwaysForcePOT = true;
  31826. }
  31827. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  31828. this._blurY.autoClear = false;
  31829. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  31830. this.addPostProcess(this._blurX);
  31831. this.addPostProcess(this._blurY);
  31832. }
  31833. };
  31834. MirrorTexture.prototype.clone = function () {
  31835. var textureSize = this.getSize();
  31836. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  31837. // Base texture
  31838. newTexture.hasAlpha = this.hasAlpha;
  31839. newTexture.level = this.level;
  31840. // Mirror Texture
  31841. newTexture.mirrorPlane = this.mirrorPlane.clone();
  31842. newTexture.renderList = this.renderList.slice(0);
  31843. return newTexture;
  31844. };
  31845. MirrorTexture.prototype.serialize = function () {
  31846. if (!this.name) {
  31847. return null;
  31848. }
  31849. var serializationObject = _super.prototype.serialize.call(this);
  31850. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  31851. return serializationObject;
  31852. };
  31853. return MirrorTexture;
  31854. }(BABYLON.RenderTargetTexture));
  31855. BABYLON.MirrorTexture = MirrorTexture;
  31856. })(BABYLON || (BABYLON = {}));
  31857. //# sourceMappingURL=babylon.mirrorTexture.js.map
  31858. /// <reference path="babylon.renderTargetTexture.ts" />
  31859. var BABYLON;
  31860. (function (BABYLON) {
  31861. /**
  31862. * Creates a refraction texture used by refraction channel of the standard material.
  31863. * @param name the texture name
  31864. * @param size size of the underlying texture
  31865. * @param scene root scene
  31866. */
  31867. var RefractionTexture = (function (_super) {
  31868. __extends(RefractionTexture, _super);
  31869. function RefractionTexture(name, size, scene, generateMipMaps) {
  31870. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  31871. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  31872. _this.depth = 2.0;
  31873. _this.onBeforeRenderObservable.add(function () {
  31874. scene.clipPlane = _this.refractionPlane;
  31875. });
  31876. _this.onAfterRenderObservable.add(function () {
  31877. delete scene.clipPlane;
  31878. });
  31879. return _this;
  31880. }
  31881. RefractionTexture.prototype.clone = function () {
  31882. var textureSize = this.getSize();
  31883. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  31884. // Base texture
  31885. newTexture.hasAlpha = this.hasAlpha;
  31886. newTexture.level = this.level;
  31887. // Refraction Texture
  31888. newTexture.refractionPlane = this.refractionPlane.clone();
  31889. newTexture.renderList = this.renderList.slice(0);
  31890. newTexture.depth = this.depth;
  31891. return newTexture;
  31892. };
  31893. RefractionTexture.prototype.serialize = function () {
  31894. if (!this.name) {
  31895. return null;
  31896. }
  31897. var serializationObject = _super.prototype.serialize.call(this);
  31898. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  31899. serializationObject.depth = this.depth;
  31900. return serializationObject;
  31901. };
  31902. return RefractionTexture;
  31903. }(BABYLON.RenderTargetTexture));
  31904. BABYLON.RefractionTexture = RefractionTexture;
  31905. })(BABYLON || (BABYLON = {}));
  31906. //# sourceMappingURL=babylon.refractionTexture.js.map
  31907. /// <reference path="babylon.texture.ts" />
  31908. var BABYLON;
  31909. (function (BABYLON) {
  31910. var DynamicTexture = (function (_super) {
  31911. __extends(DynamicTexture, _super);
  31912. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  31913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31914. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31915. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  31916. _this.name = name;
  31917. var engine = _this.getScene().getEngine();
  31918. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31919. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31920. _this._generateMipMaps = generateMipMaps;
  31921. if (options.getContext) {
  31922. _this._canvas = options;
  31923. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31924. }
  31925. else {
  31926. _this._canvas = document.createElement("canvas");
  31927. if (options.width) {
  31928. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31929. }
  31930. else {
  31931. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  31932. }
  31933. }
  31934. var textureSize = _this.getSize();
  31935. _this._canvas.width = textureSize.width;
  31936. _this._canvas.height = textureSize.height;
  31937. _this._context = _this._canvas.getContext("2d");
  31938. return _this;
  31939. }
  31940. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  31941. get: function () {
  31942. return true;
  31943. },
  31944. enumerable: true,
  31945. configurable: true
  31946. });
  31947. DynamicTexture.prototype._recreate = function (textureSize) {
  31948. this._canvas.width = textureSize.width;
  31949. this._canvas.height = textureSize.height;
  31950. this.releaseInternalTexture();
  31951. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  31952. };
  31953. DynamicTexture.prototype.scale = function (ratio) {
  31954. var textureSize = this.getSize();
  31955. textureSize.width *= ratio;
  31956. textureSize.height *= ratio;
  31957. this._recreate(textureSize);
  31958. };
  31959. DynamicTexture.prototype.scaleTo = function (width, height) {
  31960. var textureSize = this.getSize();
  31961. textureSize.width = width;
  31962. textureSize.height = height;
  31963. this._recreate(textureSize);
  31964. };
  31965. DynamicTexture.prototype.getContext = function () {
  31966. return this._context;
  31967. };
  31968. DynamicTexture.prototype.clear = function () {
  31969. var size = this.getSize();
  31970. this._context.fillRect(0, 0, size.width, size.height);
  31971. };
  31972. DynamicTexture.prototype.update = function (invertY) {
  31973. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  31974. };
  31975. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  31976. if (update === void 0) { update = true; }
  31977. var size = this.getSize();
  31978. if (clearColor) {
  31979. this._context.fillStyle = clearColor;
  31980. this._context.fillRect(0, 0, size.width, size.height);
  31981. }
  31982. this._context.font = font;
  31983. if (x === null || x === undefined) {
  31984. var textSize = this._context.measureText(text);
  31985. x = (size.width - textSize.width) / 2;
  31986. }
  31987. if (y === null || y === undefined) {
  31988. var fontSize = parseInt((font.replace(/\D/g, '')));
  31989. ;
  31990. y = (size.height / 2) + (fontSize / 3.65);
  31991. }
  31992. this._context.fillStyle = color;
  31993. this._context.fillText(text, x, y);
  31994. if (update) {
  31995. this.update(invertY);
  31996. }
  31997. };
  31998. DynamicTexture.prototype.clone = function () {
  31999. var textureSize = this.getSize();
  32000. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  32001. // Base texture
  32002. newTexture.hasAlpha = this.hasAlpha;
  32003. newTexture.level = this.level;
  32004. // Dynamic Texture
  32005. newTexture.wrapU = this.wrapU;
  32006. newTexture.wrapV = this.wrapV;
  32007. return newTexture;
  32008. };
  32009. return DynamicTexture;
  32010. }(BABYLON.Texture));
  32011. BABYLON.DynamicTexture = DynamicTexture;
  32012. })(BABYLON || (BABYLON = {}));
  32013. //# sourceMappingURL=babylon.dynamicTexture.js.map
  32014. var BABYLON;
  32015. (function (BABYLON) {
  32016. var VideoTexture = (function (_super) {
  32017. __extends(VideoTexture, _super);
  32018. /**
  32019. * Creates a video texture.
  32020. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  32021. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  32022. * @param {BABYLON.Scene} scene is obviously the current scene.
  32023. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  32024. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  32025. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  32026. */
  32027. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  32028. if (generateMipMaps === void 0) { generateMipMaps = false; }
  32029. if (invertY === void 0) { invertY = false; }
  32030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32031. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32032. _this._autoLaunch = true;
  32033. var urls;
  32034. _this.name = name;
  32035. if (urlsOrVideo instanceof HTMLVideoElement) {
  32036. _this.video = urlsOrVideo;
  32037. }
  32038. else {
  32039. urls = urlsOrVideo;
  32040. _this.video = document.createElement("video");
  32041. _this.video.autoplay = false;
  32042. _this.video.loop = true;
  32043. }
  32044. _this._generateMipMaps = generateMipMaps;
  32045. _this._samplingMode = samplingMode;
  32046. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  32047. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32048. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32049. }
  32050. else {
  32051. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32052. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32053. _this._generateMipMaps = false;
  32054. }
  32055. if (urls) {
  32056. _this.video.addEventListener("canplay", function () {
  32057. _this._createTexture();
  32058. });
  32059. urls.forEach(function (url) {
  32060. var source = document.createElement("source");
  32061. source.src = url;
  32062. _this.video.appendChild(source);
  32063. });
  32064. }
  32065. else {
  32066. _this._createTexture();
  32067. }
  32068. _this._lastUpdate = BABYLON.Tools.Now;
  32069. return _this;
  32070. }
  32071. VideoTexture.prototype.__setTextureReady = function () {
  32072. this._texture.isReady = true;
  32073. };
  32074. VideoTexture.prototype._createTexture = function () {
  32075. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  32076. if (this._autoLaunch) {
  32077. this._autoLaunch = false;
  32078. this.video.play();
  32079. }
  32080. this._setTextureReady = this.__setTextureReady.bind(this);
  32081. this.video.addEventListener("playing", this._setTextureReady);
  32082. };
  32083. VideoTexture.prototype.update = function () {
  32084. var now = BABYLON.Tools.Now;
  32085. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  32086. return false;
  32087. }
  32088. this._lastUpdate = now;
  32089. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  32090. return true;
  32091. };
  32092. VideoTexture.prototype.dispose = function () {
  32093. _super.prototype.dispose.call(this);
  32094. this.video.removeEventListener("playing", this._setTextureReady);
  32095. };
  32096. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  32097. var video = document.createElement("video");
  32098. var constraintsDeviceId;
  32099. if (constraints && constraints.deviceId) {
  32100. constraintsDeviceId = {
  32101. exact: constraints.deviceId
  32102. };
  32103. }
  32104. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  32105. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  32106. if (navigator.getUserMedia) {
  32107. navigator.getUserMedia({
  32108. video: {
  32109. deviceId: constraintsDeviceId,
  32110. width: {
  32111. min: (constraints && constraints.minWidth) || 256,
  32112. max: (constraints && constraints.maxWidth) || 640
  32113. },
  32114. height: {
  32115. min: (constraints && constraints.minHeight) || 256,
  32116. max: (constraints && constraints.maxHeight) || 480
  32117. }
  32118. }
  32119. }, function (stream) {
  32120. if (video.mozSrcObject !== undefined) {
  32121. video.mozSrcObject = stream;
  32122. }
  32123. else {
  32124. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  32125. }
  32126. video.play();
  32127. if (onReady) {
  32128. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  32129. }
  32130. }, function (e) {
  32131. BABYLON.Tools.Error(e.name);
  32132. });
  32133. }
  32134. };
  32135. return VideoTexture;
  32136. }(BABYLON.Texture));
  32137. BABYLON.VideoTexture = VideoTexture;
  32138. })(BABYLON || (BABYLON = {}));
  32139. //# sourceMappingURL=babylon.videoTexture.js.map
  32140. var BABYLON;
  32141. (function (BABYLON) {
  32142. var RawTexture = (function (_super) {
  32143. __extends(RawTexture, _super);
  32144. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  32145. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32146. if (invertY === void 0) { invertY = false; }
  32147. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32148. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  32149. _this.format = format;
  32150. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  32151. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32152. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32153. return _this;
  32154. }
  32155. RawTexture.prototype.update = function (data) {
  32156. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  32157. };
  32158. // Statics
  32159. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32160. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32161. if (invertY === void 0) { invertY = false; }
  32162. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32163. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  32164. };
  32165. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32166. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32167. if (invertY === void 0) { invertY = false; }
  32168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32169. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32170. };
  32171. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32172. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32173. if (invertY === void 0) { invertY = false; }
  32174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32175. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  32176. };
  32177. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32178. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32179. if (invertY === void 0) { invertY = false; }
  32180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32181. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  32182. };
  32183. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  32184. if (generateMipMaps === void 0) { generateMipMaps = true; }
  32185. if (invertY === void 0) { invertY = false; }
  32186. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32187. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  32188. };
  32189. return RawTexture;
  32190. }(BABYLON.Texture));
  32191. BABYLON.RawTexture = RawTexture;
  32192. })(BABYLON || (BABYLON = {}));
  32193. //# sourceMappingURL=babylon.rawTexture.js.map
  32194. var BABYLON;
  32195. (function (BABYLON) {
  32196. var Internals;
  32197. (function (Internals) {
  32198. /*
  32199. * Based on jsTGALoader - Javascript loader for TGA file
  32200. * By Vincent Thibault
  32201. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  32202. */
  32203. var TGATools = (function () {
  32204. function TGATools() {
  32205. }
  32206. TGATools.GetTGAHeader = function (data) {
  32207. var offset = 0;
  32208. var header = {
  32209. id_length: data[offset++],
  32210. colormap_type: data[offset++],
  32211. image_type: data[offset++],
  32212. colormap_index: data[offset++] | data[offset++] << 8,
  32213. colormap_length: data[offset++] | data[offset++] << 8,
  32214. colormap_size: data[offset++],
  32215. origin: [
  32216. data[offset++] | data[offset++] << 8,
  32217. data[offset++] | data[offset++] << 8
  32218. ],
  32219. width: data[offset++] | data[offset++] << 8,
  32220. height: data[offset++] | data[offset++] << 8,
  32221. pixel_size: data[offset++],
  32222. flags: data[offset++]
  32223. };
  32224. return header;
  32225. };
  32226. TGATools.UploadContent = function (gl, data) {
  32227. // Not enough data to contain header ?
  32228. if (data.length < 19) {
  32229. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  32230. return;
  32231. }
  32232. // Read Header
  32233. var offset = 18;
  32234. var header = TGATools.GetTGAHeader(data);
  32235. // Assume it's a valid Targa file.
  32236. if (header.id_length + offset > data.length) {
  32237. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  32238. return;
  32239. }
  32240. // Skip not needed data
  32241. offset += header.id_length;
  32242. var use_rle = false;
  32243. var use_pal = false;
  32244. var use_rgb = false;
  32245. var use_grey = false;
  32246. // Get some informations.
  32247. switch (header.image_type) {
  32248. case TGATools._TYPE_RLE_INDEXED:
  32249. use_rle = true;
  32250. case TGATools._TYPE_INDEXED:
  32251. use_pal = true;
  32252. break;
  32253. case TGATools._TYPE_RLE_RGB:
  32254. use_rle = true;
  32255. case TGATools._TYPE_RGB:
  32256. use_rgb = true;
  32257. break;
  32258. case TGATools._TYPE_RLE_GREY:
  32259. use_rle = true;
  32260. case TGATools._TYPE_GREY:
  32261. use_grey = true;
  32262. break;
  32263. }
  32264. var pixel_data;
  32265. var numAlphaBits = header.flags & 0xf;
  32266. var pixel_size = header.pixel_size >> 3;
  32267. var pixel_total = header.width * header.height * pixel_size;
  32268. // Read palettes
  32269. var palettes;
  32270. if (use_pal) {
  32271. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32272. }
  32273. // Read LRE
  32274. if (use_rle) {
  32275. pixel_data = new Uint8Array(pixel_total);
  32276. var c, count, i;
  32277. var localOffset = 0;
  32278. var pixels = new Uint8Array(pixel_size);
  32279. while (offset < pixel_total && localOffset < pixel_total) {
  32280. c = data[offset++];
  32281. count = (c & 0x7f) + 1;
  32282. // RLE pixels
  32283. if (c & 0x80) {
  32284. // Bind pixel tmp array
  32285. for (i = 0; i < pixel_size; ++i) {
  32286. pixels[i] = data[offset++];
  32287. }
  32288. // Copy pixel array
  32289. for (i = 0; i < count; ++i) {
  32290. pixel_data.set(pixels, localOffset + i * pixel_size);
  32291. }
  32292. localOffset += pixel_size * count;
  32293. }
  32294. else {
  32295. count *= pixel_size;
  32296. for (i = 0; i < count; ++i) {
  32297. pixel_data[localOffset + i] = data[offset++];
  32298. }
  32299. localOffset += count;
  32300. }
  32301. }
  32302. }
  32303. else {
  32304. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32305. }
  32306. // Load to texture
  32307. var x_start, y_start, x_step, y_step, y_end, x_end;
  32308. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32309. default:
  32310. case TGATools._ORIGIN_UL:
  32311. x_start = 0;
  32312. x_step = 1;
  32313. x_end = header.width;
  32314. y_start = 0;
  32315. y_step = 1;
  32316. y_end = header.height;
  32317. break;
  32318. case TGATools._ORIGIN_BL:
  32319. x_start = 0;
  32320. x_step = 1;
  32321. x_end = header.width;
  32322. y_start = header.height - 1;
  32323. y_step = -1;
  32324. y_end = -1;
  32325. break;
  32326. case TGATools._ORIGIN_UR:
  32327. x_start = header.width - 1;
  32328. x_step = -1;
  32329. x_end = -1;
  32330. y_start = 0;
  32331. y_step = 1;
  32332. y_end = header.height;
  32333. break;
  32334. case TGATools._ORIGIN_BR:
  32335. x_start = header.width - 1;
  32336. x_step = -1;
  32337. x_end = -1;
  32338. y_start = header.height - 1;
  32339. y_step = -1;
  32340. y_end = -1;
  32341. break;
  32342. }
  32343. // Load the specify method
  32344. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32345. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32346. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32347. };
  32348. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32349. var image = pixel_data, colormap = palettes;
  32350. var width = header.width, height = header.height;
  32351. var color, i = 0, x, y;
  32352. var imageData = new Uint8Array(width * height * 4);
  32353. for (y = y_start; y !== y_end; y += y_step) {
  32354. for (x = x_start; x !== x_end; x += x_step, i++) {
  32355. color = image[i];
  32356. imageData[(x + width * y) * 4 + 3] = 255;
  32357. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32358. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32359. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32360. }
  32361. }
  32362. return imageData;
  32363. };
  32364. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32365. var image = pixel_data;
  32366. var width = header.width, height = header.height;
  32367. var color, i = 0, x, y;
  32368. var imageData = new Uint8Array(width * height * 4);
  32369. for (y = y_start; y !== y_end; y += y_step) {
  32370. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32371. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32372. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32373. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32374. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32375. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32376. }
  32377. }
  32378. return imageData;
  32379. };
  32380. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32381. var image = pixel_data;
  32382. var width = header.width, height = header.height;
  32383. var i = 0, x, y;
  32384. var imageData = new Uint8Array(width * height * 4);
  32385. for (y = y_start; y !== y_end; y += y_step) {
  32386. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32387. imageData[(x + width * y) * 4 + 3] = 255;
  32388. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32389. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32390. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32391. }
  32392. }
  32393. return imageData;
  32394. };
  32395. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32396. var image = pixel_data;
  32397. var width = header.width, height = header.height;
  32398. var i = 0, x, y;
  32399. var imageData = new Uint8Array(width * height * 4);
  32400. for (y = y_start; y !== y_end; y += y_step) {
  32401. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32402. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32403. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32404. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32405. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32406. }
  32407. }
  32408. return imageData;
  32409. };
  32410. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32411. var image = pixel_data;
  32412. var width = header.width, height = header.height;
  32413. var color, i = 0, x, y;
  32414. var imageData = new Uint8Array(width * height * 4);
  32415. for (y = y_start; y !== y_end; y += y_step) {
  32416. for (x = x_start; x !== x_end; x += x_step, i++) {
  32417. color = image[i];
  32418. imageData[(x + width * y) * 4 + 0] = color;
  32419. imageData[(x + width * y) * 4 + 1] = color;
  32420. imageData[(x + width * y) * 4 + 2] = color;
  32421. imageData[(x + width * y) * 4 + 3] = 255;
  32422. }
  32423. }
  32424. return imageData;
  32425. };
  32426. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32427. var image = pixel_data;
  32428. var width = header.width, height = header.height;
  32429. var i = 0, x, y;
  32430. var imageData = new Uint8Array(width * height * 4);
  32431. for (y = y_start; y !== y_end; y += y_step) {
  32432. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32433. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32434. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32435. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32436. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32437. }
  32438. }
  32439. return imageData;
  32440. };
  32441. return TGATools;
  32442. }());
  32443. TGATools._TYPE_NO_DATA = 0;
  32444. TGATools._TYPE_INDEXED = 1;
  32445. TGATools._TYPE_RGB = 2;
  32446. TGATools._TYPE_GREY = 3;
  32447. TGATools._TYPE_RLE_INDEXED = 9;
  32448. TGATools._TYPE_RLE_RGB = 10;
  32449. TGATools._TYPE_RLE_GREY = 11;
  32450. TGATools._ORIGIN_MASK = 0x30;
  32451. TGATools._ORIGIN_SHIFT = 0x04;
  32452. TGATools._ORIGIN_BL = 0x00;
  32453. TGATools._ORIGIN_BR = 0x01;
  32454. TGATools._ORIGIN_UL = 0x02;
  32455. TGATools._ORIGIN_UR = 0x03;
  32456. Internals.TGATools = TGATools;
  32457. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32458. })(BABYLON || (BABYLON = {}));
  32459. //# sourceMappingURL=babylon.tga.js.map
  32460. var BABYLON;
  32461. (function (BABYLON) {
  32462. var Internals;
  32463. (function (Internals) {
  32464. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32465. // All values and structures referenced from:
  32466. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32467. var DDS_MAGIC = 0x20534444;
  32468. 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;
  32469. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32470. 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;
  32471. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32472. function FourCCToInt32(value) {
  32473. return value.charCodeAt(0) +
  32474. (value.charCodeAt(1) << 8) +
  32475. (value.charCodeAt(2) << 16) +
  32476. (value.charCodeAt(3) << 24);
  32477. }
  32478. function Int32ToFourCC(value) {
  32479. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32480. }
  32481. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32482. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32483. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32484. var headerLengthInt = 31; // The header length in 32 bit ints
  32485. // Offsets into the header array
  32486. var off_magic = 0;
  32487. var off_size = 1;
  32488. var off_flags = 2;
  32489. var off_height = 3;
  32490. var off_width = 4;
  32491. var off_mipmapCount = 7;
  32492. var off_pfFlags = 20;
  32493. var off_pfFourCC = 21;
  32494. var off_RGBbpp = 22;
  32495. var off_RMask = 23;
  32496. var off_GMask = 24;
  32497. var off_BMask = 25;
  32498. var off_AMask = 26;
  32499. var off_caps1 = 27;
  32500. var off_caps2 = 28;
  32501. ;
  32502. var DDSTools = (function () {
  32503. function DDSTools() {
  32504. }
  32505. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32506. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32507. var mipmapCount = 1;
  32508. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32509. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32510. }
  32511. return {
  32512. width: header[off_width],
  32513. height: header[off_height],
  32514. mipmapCount: mipmapCount,
  32515. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32516. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32517. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32518. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32519. };
  32520. };
  32521. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32522. var byteArray = new Uint8Array(dataLength);
  32523. var srcData = new Uint8Array(arrayBuffer);
  32524. var index = 0;
  32525. for (var y = height - 1; y >= 0; y--) {
  32526. for (var x = 0; x < width; x++) {
  32527. var srcPos = dataOffset + (x + y * width) * 4;
  32528. byteArray[index + 2] = srcData[srcPos];
  32529. byteArray[index + 1] = srcData[srcPos + 1];
  32530. byteArray[index] = srcData[srcPos + 2];
  32531. byteArray[index + 3] = srcData[srcPos + 3];
  32532. index += 4;
  32533. }
  32534. }
  32535. return byteArray;
  32536. };
  32537. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32538. var byteArray = new Uint8Array(dataLength);
  32539. var srcData = new Uint8Array(arrayBuffer);
  32540. var index = 0;
  32541. for (var y = height - 1; y >= 0; y--) {
  32542. for (var x = 0; x < width; x++) {
  32543. var srcPos = dataOffset + (x + y * width) * 3;
  32544. byteArray[index + 2] = srcData[srcPos];
  32545. byteArray[index + 1] = srcData[srcPos + 1];
  32546. byteArray[index] = srcData[srcPos + 2];
  32547. index += 3;
  32548. }
  32549. }
  32550. return byteArray;
  32551. };
  32552. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32553. var byteArray = new Uint8Array(dataLength);
  32554. var srcData = new Uint8Array(arrayBuffer);
  32555. var index = 0;
  32556. for (var y = height - 1; y >= 0; y--) {
  32557. for (var x = 0; x < width; x++) {
  32558. var srcPos = dataOffset + (x + y * width);
  32559. byteArray[index] = srcData[srcPos];
  32560. index++;
  32561. }
  32562. }
  32563. return byteArray;
  32564. };
  32565. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32566. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32567. if (header[off_magic] != DDS_MAGIC) {
  32568. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32569. return;
  32570. }
  32571. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32572. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32573. return;
  32574. }
  32575. if (info.isFourCC) {
  32576. fourCC = header[off_pfFourCC];
  32577. switch (fourCC) {
  32578. case FOURCC_DXT1:
  32579. blockBytes = 8;
  32580. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32581. break;
  32582. case FOURCC_DXT3:
  32583. blockBytes = 16;
  32584. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32585. break;
  32586. case FOURCC_DXT5:
  32587. blockBytes = 16;
  32588. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32589. break;
  32590. default:
  32591. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32592. return;
  32593. }
  32594. }
  32595. mipmapCount = 1;
  32596. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32597. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32598. }
  32599. var bpp = header[off_RGBbpp];
  32600. for (var face = 0; face < faces; face++) {
  32601. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32602. width = header[off_width];
  32603. height = header[off_height];
  32604. dataOffset = header[off_size] + 4;
  32605. for (i = 0; i < mipmapCount; ++i) {
  32606. if (info.isRGB) {
  32607. if (bpp === 24) {
  32608. dataLength = width * height * 3;
  32609. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32610. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32611. }
  32612. else {
  32613. dataLength = width * height * 4;
  32614. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32615. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32616. }
  32617. }
  32618. else if (info.isLuminance) {
  32619. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32620. var unpaddedRowSize = width;
  32621. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32622. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32623. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32624. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32625. }
  32626. else {
  32627. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32628. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32629. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32630. }
  32631. dataOffset += dataLength;
  32632. width *= 0.5;
  32633. height *= 0.5;
  32634. width = Math.max(1.0, width);
  32635. height = Math.max(1.0, height);
  32636. }
  32637. }
  32638. };
  32639. return DDSTools;
  32640. }());
  32641. Internals.DDSTools = DDSTools;
  32642. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32643. })(BABYLON || (BABYLON = {}));
  32644. //# sourceMappingURL=babylon.dds.js.map
  32645. var BABYLON;
  32646. (function (BABYLON) {
  32647. var Internals;
  32648. (function (Internals) {
  32649. /**
  32650. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  32651. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  32652. */
  32653. var KhronosTextureContainer = (function () {
  32654. /**
  32655. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  32656. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  32657. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  32658. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  32659. */
  32660. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  32661. this.arrayBuffer = arrayBuffer;
  32662. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  32663. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  32664. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  32665. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  32666. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  32667. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  32668. BABYLON.Tools.Error("texture missing KTX identifier");
  32669. return;
  32670. }
  32671. // load the reset of the header in native 32 bit int
  32672. var header = new Int32Array(this.arrayBuffer, 12, 13);
  32673. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  32674. var oppositeEndianess = header[0] === 0x01020304;
  32675. // read all the header elements in order they exist in the file, without modification (sans endainness)
  32676. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  32677. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  32678. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  32679. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  32680. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  32681. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  32682. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  32683. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  32684. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  32685. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  32686. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  32687. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  32688. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  32689. if (this.glType !== 0) {
  32690. BABYLON.Tools.Error("only compressed formats currently supported");
  32691. return;
  32692. }
  32693. else {
  32694. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  32695. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  32696. }
  32697. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  32698. BABYLON.Tools.Error("only 2D textures currently supported");
  32699. return;
  32700. }
  32701. if (this.numberOfArrayElements !== 0) {
  32702. BABYLON.Tools.Error("texture arrays not currently supported");
  32703. return;
  32704. }
  32705. if (this.numberOfFaces !== facesExpected) {
  32706. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  32707. return;
  32708. }
  32709. // we now have a completely validated file, so could use existence of loadType as success
  32710. // would need to make this more elaborate & adjust checks above to support more than one load type
  32711. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  32712. }
  32713. // not as fast hardware based, but will probably never need to use
  32714. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  32715. return ((val & 0xFF) << 24)
  32716. | ((val & 0xFF00) << 8)
  32717. | ((val >> 8) & 0xFF00)
  32718. | ((val >> 24) & 0xFF);
  32719. };
  32720. /**
  32721. * It is assumed that the texture has already been created & is currently bound
  32722. */
  32723. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  32724. switch (this.loadType) {
  32725. case KhronosTextureContainer.COMPRESSED_2D:
  32726. this._upload2DCompressedLevels(gl, loadMipmaps);
  32727. break;
  32728. case KhronosTextureContainer.TEX_2D:
  32729. case KhronosTextureContainer.COMPRESSED_3D:
  32730. case KhronosTextureContainer.TEX_3D:
  32731. }
  32732. };
  32733. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  32734. // initialize width & height for level 1
  32735. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  32736. var width = this.pixelWidth;
  32737. var height = this.pixelHeight;
  32738. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  32739. for (var level = 0; level < mipmapCount; level++) {
  32740. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  32741. for (var face = 0; face < this.numberOfFaces; face++) {
  32742. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32743. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  32744. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  32745. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  32746. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  32747. }
  32748. width = Math.max(1.0, width * 0.5);
  32749. height = Math.max(1.0, height * 0.5);
  32750. }
  32751. };
  32752. return KhronosTextureContainer;
  32753. }());
  32754. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  32755. // load types
  32756. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  32757. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  32758. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  32759. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  32760. Internals.KhronosTextureContainer = KhronosTextureContainer;
  32761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32762. })(BABYLON || (BABYLON = {}));
  32763. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  32764. var BABYLON;
  32765. (function (BABYLON) {
  32766. var PostProcess = (function () {
  32767. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  32768. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32769. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32770. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  32771. if (blockCompilation === void 0) { blockCompilation = false; }
  32772. this.name = name;
  32773. this.width = -1;
  32774. this.height = -1;
  32775. this.autoClear = true;
  32776. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  32777. /*
  32778. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32779. Can only be used on a single postprocess or on the last one of a chain.
  32780. */
  32781. this.enablePixelPerfectMode = false;
  32782. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  32783. this.alwaysForcePOT = false;
  32784. this.samples = 1;
  32785. this._reusable = false;
  32786. this._textures = new BABYLON.SmartArray(2);
  32787. this._currentRenderTextureInd = 0;
  32788. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32789. this._texelSize = BABYLON.Vector2.Zero();
  32790. // Events
  32791. /**
  32792. * An event triggered when the postprocess is activated.
  32793. * @type {BABYLON.Observable}
  32794. */
  32795. this.onActivateObservable = new BABYLON.Observable();
  32796. /**
  32797. * An event triggered when the postprocess changes its size.
  32798. * @type {BABYLON.Observable}
  32799. */
  32800. this.onSizeChangedObservable = new BABYLON.Observable();
  32801. /**
  32802. * An event triggered when the postprocess applies its effect.
  32803. * @type {BABYLON.Observable}
  32804. */
  32805. this.onApplyObservable = new BABYLON.Observable();
  32806. /**
  32807. * An event triggered before rendering the postprocess
  32808. * @type {BABYLON.Observable}
  32809. */
  32810. this.onBeforeRenderObservable = new BABYLON.Observable();
  32811. /**
  32812. * An event triggered after rendering the postprocess
  32813. * @type {BABYLON.Observable}
  32814. */
  32815. this.onAfterRenderObservable = new BABYLON.Observable();
  32816. if (camera != null) {
  32817. this._camera = camera;
  32818. this._scene = camera.getScene();
  32819. camera.attachPostProcess(this);
  32820. this._engine = this._scene.getEngine();
  32821. }
  32822. else {
  32823. this._engine = engine;
  32824. }
  32825. this._options = options;
  32826. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32827. this._reusable = reusable || false;
  32828. this._textureType = textureType;
  32829. this._samplers = samplers || [];
  32830. this._samplers.push("textureSampler");
  32831. this._fragmentUrl = fragmentUrl;
  32832. this._vertexUrl = vertexUrl;
  32833. this._parameters = parameters || [];
  32834. this._parameters.push("scale");
  32835. this._indexParameters = indexParameters;
  32836. if (!blockCompilation) {
  32837. this.updateEffect(defines);
  32838. }
  32839. }
  32840. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32841. set: function (callback) {
  32842. if (this._onActivateObserver) {
  32843. this.onActivateObservable.remove(this._onActivateObserver);
  32844. }
  32845. this._onActivateObserver = this.onActivateObservable.add(callback);
  32846. },
  32847. enumerable: true,
  32848. configurable: true
  32849. });
  32850. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32851. set: function (callback) {
  32852. if (this._onSizeChangedObserver) {
  32853. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32854. }
  32855. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32856. },
  32857. enumerable: true,
  32858. configurable: true
  32859. });
  32860. Object.defineProperty(PostProcess.prototype, "onApply", {
  32861. set: function (callback) {
  32862. if (this._onApplyObserver) {
  32863. this.onApplyObservable.remove(this._onApplyObserver);
  32864. }
  32865. this._onApplyObserver = this.onApplyObservable.add(callback);
  32866. },
  32867. enumerable: true,
  32868. configurable: true
  32869. });
  32870. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32871. set: function (callback) {
  32872. if (this._onBeforeRenderObserver) {
  32873. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32874. }
  32875. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32876. },
  32877. enumerable: true,
  32878. configurable: true
  32879. });
  32880. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32881. set: function (callback) {
  32882. if (this._onAfterRenderObserver) {
  32883. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32884. }
  32885. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32886. },
  32887. enumerable: true,
  32888. configurable: true
  32889. });
  32890. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  32891. get: function () {
  32892. return this._textures.data[this._currentRenderTextureInd];
  32893. },
  32894. set: function (value) {
  32895. this._forcedOutputTexture = value;
  32896. },
  32897. enumerable: true,
  32898. configurable: true
  32899. });
  32900. PostProcess.prototype.getCamera = function () {
  32901. return this._camera;
  32902. };
  32903. Object.defineProperty(PostProcess.prototype, "texelSize", {
  32904. get: function () {
  32905. if (this._shareOutputWithPostProcess) {
  32906. return this._shareOutputWithPostProcess.texelSize;
  32907. }
  32908. if (this._forcedOutputTexture) {
  32909. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  32910. }
  32911. return this._texelSize;
  32912. },
  32913. enumerable: true,
  32914. configurable: true
  32915. });
  32916. PostProcess.prototype.getEngine = function () {
  32917. return this._engine;
  32918. };
  32919. PostProcess.prototype.getEffect = function () {
  32920. return this._effect;
  32921. };
  32922. PostProcess.prototype.shareOutputWith = function (postProcess) {
  32923. this._disposeTextures();
  32924. this._shareOutputWithPostProcess = postProcess;
  32925. return this;
  32926. };
  32927. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  32928. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  32929. };
  32930. PostProcess.prototype.isReusable = function () {
  32931. return this._reusable;
  32932. };
  32933. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32934. PostProcess.prototype.markTextureDirty = function () {
  32935. this.width = -1;
  32936. };
  32937. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  32938. var _this = this;
  32939. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  32940. camera = camera || this._camera;
  32941. var scene = camera.getScene();
  32942. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32943. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32944. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32945. var desiredWidth = this._options.width || requiredWidth;
  32946. var desiredHeight = this._options.height || requiredHeight;
  32947. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  32948. if (!this._options.width) {
  32949. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  32950. }
  32951. if (!this._options.height) {
  32952. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  32953. }
  32954. }
  32955. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32956. if (this._textures.length > 0) {
  32957. for (var i = 0; i < this._textures.length; i++) {
  32958. this._engine._releaseTexture(this._textures.data[i]);
  32959. }
  32960. this._textures.reset();
  32961. }
  32962. this.width = desiredWidth;
  32963. this.height = desiredHeight;
  32964. var textureSize = { width: this.width, height: this.height };
  32965. var textureOptions = {
  32966. generateMipMaps: false,
  32967. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  32968. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  32969. samplingMode: this.renderTargetSamplingMode,
  32970. type: this._textureType
  32971. };
  32972. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32973. if (this._reusable) {
  32974. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32975. }
  32976. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  32977. this.onSizeChangedObservable.notifyObservers(this);
  32978. }
  32979. this._textures.forEach(function (texture) {
  32980. if (texture.samples !== _this.samples) {
  32981. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  32982. }
  32983. });
  32984. }
  32985. var target;
  32986. if (this._shareOutputWithPostProcess) {
  32987. target = this._shareOutputWithPostProcess.outputTexture;
  32988. }
  32989. else if (this._forcedOutputTexture) {
  32990. target = this._forcedOutputTexture;
  32991. this.width = this._forcedOutputTexture._width;
  32992. this.height = this._forcedOutputTexture._height;
  32993. }
  32994. else {
  32995. target = this.outputTexture;
  32996. }
  32997. if (this.enablePixelPerfectMode) {
  32998. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32999. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  33000. }
  33001. else {
  33002. this._scaleRatio.copyFromFloats(1, 1);
  33003. this._engine.bindFramebuffer(target);
  33004. }
  33005. this.onActivateObservable.notifyObservers(camera);
  33006. // Clear
  33007. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  33008. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  33009. }
  33010. if (this._reusable) {
  33011. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  33012. }
  33013. };
  33014. Object.defineProperty(PostProcess.prototype, "isSupported", {
  33015. get: function () {
  33016. return this._effect.isSupported;
  33017. },
  33018. enumerable: true,
  33019. configurable: true
  33020. });
  33021. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  33022. get: function () {
  33023. if (this._shareOutputWithPostProcess) {
  33024. return this._shareOutputWithPostProcess.aspectRatio;
  33025. }
  33026. if (this._forcedOutputTexture) {
  33027. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  33028. }
  33029. return this.width / this.height;
  33030. },
  33031. enumerable: true,
  33032. configurable: true
  33033. });
  33034. PostProcess.prototype.apply = function () {
  33035. // Check
  33036. if (!this._effect || !this._effect.isReady())
  33037. return null;
  33038. // States
  33039. this._engine.enableEffect(this._effect);
  33040. this._engine.setState(false);
  33041. this._engine.setDepthBuffer(false);
  33042. this._engine.setDepthWrite(false);
  33043. // Alpha
  33044. this._engine.setAlphaMode(this.alphaMode);
  33045. if (this.alphaConstants) {
  33046. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  33047. }
  33048. // Texture
  33049. var source;
  33050. if (this._shareOutputWithPostProcess) {
  33051. source = this._shareOutputWithPostProcess.outputTexture;
  33052. }
  33053. else if (this._forcedOutputTexture) {
  33054. source = this._forcedOutputTexture;
  33055. }
  33056. else {
  33057. source = this.outputTexture;
  33058. }
  33059. this._effect._bindTexture("textureSampler", source);
  33060. // Parameters
  33061. this._effect.setVector2("scale", this._scaleRatio);
  33062. this.onApplyObservable.notifyObservers(this._effect);
  33063. return this._effect;
  33064. };
  33065. PostProcess.prototype._disposeTextures = function () {
  33066. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  33067. return;
  33068. }
  33069. if (this._textures.length > 0) {
  33070. for (var i = 0; i < this._textures.length; i++) {
  33071. this._engine._releaseTexture(this._textures.data[i]);
  33072. }
  33073. }
  33074. this._textures.dispose();
  33075. };
  33076. PostProcess.prototype.dispose = function (camera) {
  33077. camera = camera || this._camera;
  33078. this._disposeTextures();
  33079. if (!camera) {
  33080. return;
  33081. }
  33082. camera.detachPostProcess(this);
  33083. var index = camera._postProcesses.indexOf(this);
  33084. if (index === 0 && camera._postProcesses.length > 0) {
  33085. this._camera._postProcesses[0].markTextureDirty();
  33086. }
  33087. this.onActivateObservable.clear();
  33088. this.onAfterRenderObservable.clear();
  33089. this.onApplyObservable.clear();
  33090. this.onBeforeRenderObservable.clear();
  33091. this.onSizeChangedObservable.clear();
  33092. };
  33093. return PostProcess;
  33094. }());
  33095. BABYLON.PostProcess = PostProcess;
  33096. })(BABYLON || (BABYLON = {}));
  33097. //# sourceMappingURL=babylon.postProcess.js.map
  33098. var BABYLON;
  33099. (function (BABYLON) {
  33100. var PassPostProcess = (function (_super) {
  33101. __extends(PassPostProcess, _super);
  33102. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  33103. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  33104. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  33105. }
  33106. return PassPostProcess;
  33107. }(BABYLON.PostProcess));
  33108. BABYLON.PassPostProcess = PassPostProcess;
  33109. })(BABYLON || (BABYLON = {}));
  33110. //# sourceMappingURL=babylon.passPostProcess.js.map
  33111. var BABYLON;
  33112. (function (BABYLON) {
  33113. var ShadowGenerator = (function () {
  33114. /**
  33115. * Creates a ShadowGenerator object.
  33116. * A ShadowGenerator is the required tool to use the shadows.
  33117. * Each light casting shadows needs to use its own ShadowGenerator.
  33118. * Required parameters :
  33119. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  33120. * - `light`: the light object generating the shadows.
  33121. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  33122. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  33123. */
  33124. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  33125. // Members
  33126. this._bias = 0.00005;
  33127. this._blurBoxOffset = 1;
  33128. this._blurScale = 2;
  33129. this._blurKernel = 1;
  33130. this._useKernelBlur = false;
  33131. this._filter = ShadowGenerator.FILTER_NONE;
  33132. this._darkness = 0;
  33133. this._transparencyShadow = false;
  33134. this.forceBackFacesOnly = false;
  33135. this._lightDirection = BABYLON.Vector3.Zero();
  33136. this._viewMatrix = BABYLON.Matrix.Zero();
  33137. this._projectionMatrix = BABYLON.Matrix.Zero();
  33138. this._transformMatrix = BABYLON.Matrix.Zero();
  33139. this._worldViewProjection = BABYLON.Matrix.Zero();
  33140. this._currentFaceIndex = 0;
  33141. this._currentFaceIndexCache = 0;
  33142. this._isCube = false;
  33143. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  33144. this._mapSize = mapSize;
  33145. this._light = light;
  33146. this._scene = light.getScene();
  33147. light._shadowGenerator = this;
  33148. // Texture type fallback from float to int if not supported.
  33149. var caps = this._scene.getEngine().getCaps();
  33150. if (!useFullFloatFirst) {
  33151. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33152. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33153. }
  33154. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33155. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33156. }
  33157. else {
  33158. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33159. }
  33160. }
  33161. else {
  33162. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  33163. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  33164. }
  33165. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  33166. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  33167. }
  33168. else {
  33169. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  33170. }
  33171. }
  33172. this._initializeGenerator();
  33173. }
  33174. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  33175. // Static
  33176. get: function () {
  33177. return ShadowGenerator._FILTER_NONE;
  33178. },
  33179. enumerable: true,
  33180. configurable: true
  33181. });
  33182. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  33183. get: function () {
  33184. return ShadowGenerator._FILTER_POISSONSAMPLING;
  33185. },
  33186. enumerable: true,
  33187. configurable: true
  33188. });
  33189. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  33190. get: function () {
  33191. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  33192. },
  33193. enumerable: true,
  33194. configurable: true
  33195. });
  33196. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  33197. get: function () {
  33198. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  33204. get: function () {
  33205. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33206. },
  33207. enumerable: true,
  33208. configurable: true
  33209. });
  33210. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  33211. get: function () {
  33212. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33213. },
  33214. enumerable: true,
  33215. configurable: true
  33216. });
  33217. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  33218. get: function () {
  33219. return this._bias;
  33220. },
  33221. set: function (bias) {
  33222. this._bias = bias;
  33223. },
  33224. enumerable: true,
  33225. configurable: true
  33226. });
  33227. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  33228. get: function () {
  33229. return this._blurBoxOffset;
  33230. },
  33231. set: function (value) {
  33232. if (this._blurBoxOffset === value) {
  33233. return;
  33234. }
  33235. this._blurBoxOffset = value;
  33236. this._disposeBlurPostProcesses();
  33237. },
  33238. enumerable: true,
  33239. configurable: true
  33240. });
  33241. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  33242. get: function () {
  33243. return this._blurScale;
  33244. },
  33245. set: function (value) {
  33246. if (this._blurScale === value) {
  33247. return;
  33248. }
  33249. this._blurScale = value;
  33250. this._disposeBlurPostProcesses();
  33251. },
  33252. enumerable: true,
  33253. configurable: true
  33254. });
  33255. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  33256. get: function () {
  33257. return this._blurKernel;
  33258. },
  33259. set: function (value) {
  33260. if (this._blurKernel === value) {
  33261. return;
  33262. }
  33263. this._blurKernel = value;
  33264. this._disposeBlurPostProcesses();
  33265. },
  33266. enumerable: true,
  33267. configurable: true
  33268. });
  33269. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33270. get: function () {
  33271. return this._useKernelBlur;
  33272. },
  33273. set: function (value) {
  33274. if (this._useKernelBlur === value) {
  33275. return;
  33276. }
  33277. this._useKernelBlur = value;
  33278. this._disposeBlurPostProcesses();
  33279. },
  33280. enumerable: true,
  33281. configurable: true
  33282. });
  33283. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33284. get: function () {
  33285. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33286. },
  33287. set: function (value) {
  33288. this._depthScale = value;
  33289. },
  33290. enumerable: true,
  33291. configurable: true
  33292. });
  33293. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33294. get: function () {
  33295. return this._filter;
  33296. },
  33297. set: function (value) {
  33298. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33299. if (this._light.needCube()) {
  33300. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33301. this.useExponentialShadowMap = true;
  33302. return;
  33303. }
  33304. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33305. this.useCloseExponentialShadowMap = true;
  33306. return;
  33307. }
  33308. }
  33309. if (this._filter === value) {
  33310. return;
  33311. }
  33312. this._filter = value;
  33313. this._disposeBlurPostProcesses();
  33314. this._applyFilterValues();
  33315. this._light._markMeshesAsLightDirty();
  33316. },
  33317. enumerable: true,
  33318. configurable: true
  33319. });
  33320. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33321. get: function () {
  33322. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33323. },
  33324. set: function (value) {
  33325. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33326. },
  33327. enumerable: true,
  33328. configurable: true
  33329. });
  33330. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33331. get: function () {
  33332. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33333. return this.useExponentialShadowMap;
  33334. },
  33335. set: function (value) {
  33336. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33337. this.useExponentialShadowMap = value;
  33338. },
  33339. enumerable: true,
  33340. configurable: true
  33341. });
  33342. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33343. get: function () {
  33344. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33345. return this.useBlurExponentialShadowMap;
  33346. },
  33347. set: function (value) {
  33348. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33349. this.useBlurExponentialShadowMap = value;
  33350. },
  33351. enumerable: true,
  33352. configurable: true
  33353. });
  33354. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33355. get: function () {
  33356. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33357. },
  33358. set: function (value) {
  33359. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33360. },
  33361. enumerable: true,
  33362. configurable: true
  33363. });
  33364. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33365. get: function () {
  33366. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33367. },
  33368. set: function (value) {
  33369. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33370. },
  33371. enumerable: true,
  33372. configurable: true
  33373. });
  33374. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33375. get: function () {
  33376. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33377. },
  33378. set: function (value) {
  33379. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33380. },
  33381. enumerable: true,
  33382. configurable: true
  33383. });
  33384. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33385. get: function () {
  33386. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33387. },
  33388. set: function (value) {
  33389. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33390. },
  33391. enumerable: true,
  33392. configurable: true
  33393. });
  33394. /**
  33395. * Returns the darkness value (float).
  33396. */
  33397. ShadowGenerator.prototype.getDarkness = function () {
  33398. return this._darkness;
  33399. };
  33400. /**
  33401. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33402. * Returns the ShadowGenerator.
  33403. */
  33404. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33405. if (darkness >= 1.0)
  33406. this._darkness = 1.0;
  33407. else if (darkness <= 0.0)
  33408. this._darkness = 0.0;
  33409. else
  33410. this._darkness = darkness;
  33411. return this;
  33412. };
  33413. /**
  33414. * Sets the ability to have transparent shadow (boolean).
  33415. * Returns the ShadowGenerator.
  33416. */
  33417. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33418. this._transparencyShadow = hasShadow;
  33419. return this;
  33420. };
  33421. /**
  33422. * Returns a RenderTargetTexture object : the shadow map texture.
  33423. */
  33424. ShadowGenerator.prototype.getShadowMap = function () {
  33425. return this._shadowMap;
  33426. };
  33427. /**
  33428. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33429. */
  33430. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33431. if (this._shadowMap2) {
  33432. return this._shadowMap2;
  33433. }
  33434. return this._shadowMap;
  33435. };
  33436. /**
  33437. * Returns the associated light object.
  33438. */
  33439. ShadowGenerator.prototype.getLight = function () {
  33440. return this._light;
  33441. };
  33442. ShadowGenerator.prototype._initializeGenerator = function () {
  33443. this._light._markMeshesAsLightDirty();
  33444. this._initializeShadowMap();
  33445. };
  33446. ShadowGenerator.prototype._initializeShadowMap = function () {
  33447. var _this = this;
  33448. // Render target
  33449. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33450. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33451. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33452. this._shadowMap.anisotropicFilteringLevel = 1;
  33453. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33454. this._shadowMap.renderParticles = false;
  33455. // Record Face Index before render.
  33456. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33457. _this._currentFaceIndex = faceIndex;
  33458. });
  33459. // Custom render function.
  33460. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33461. // Blur if required afer render.
  33462. this._shadowMap.onAfterUnbindObservable.add(function () {
  33463. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33464. return;
  33465. }
  33466. if (!_this._blurPostProcesses) {
  33467. _this._initializeBlurRTTAndPostProcesses();
  33468. }
  33469. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33470. });
  33471. // Clear according to the chosen filter.
  33472. this._shadowMap.onClearObservable.add(function (engine) {
  33473. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33474. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33475. }
  33476. else {
  33477. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33478. }
  33479. });
  33480. };
  33481. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33482. var _this = this;
  33483. var engine = this._scene.getEngine();
  33484. var targetSize = this._mapSize / this.blurScale;
  33485. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33486. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33487. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33488. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33489. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33490. }
  33491. if (this.useKernelBlur) {
  33492. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33493. this._kernelBlurXPostprocess.width = targetSize;
  33494. this._kernelBlurXPostprocess.height = targetSize;
  33495. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33496. effect.setTexture("textureSampler", _this._shadowMap);
  33497. });
  33498. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  33499. this._kernelBlurXPostprocess.autoClear = false;
  33500. this._kernelBlurYPostprocess.autoClear = false;
  33501. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33502. this._kernelBlurXPostprocess.packedFloat = true;
  33503. this._kernelBlurYPostprocess.packedFloat = true;
  33504. }
  33505. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33506. }
  33507. else {
  33508. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  33509. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33510. effect.setFloat2("screenSize", targetSize, targetSize);
  33511. effect.setTexture("textureSampler", _this._shadowMap);
  33512. });
  33513. this._boxBlurPostprocess.autoClear = false;
  33514. this._blurPostProcesses = [this._boxBlurPostprocess];
  33515. }
  33516. };
  33517. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33518. var index;
  33519. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33520. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33521. }
  33522. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33523. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33524. }
  33525. if (this._transparencyShadow) {
  33526. for (index = 0; index < transparentSubMeshes.length; index++) {
  33527. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33528. }
  33529. }
  33530. };
  33531. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  33532. var _this = this;
  33533. var mesh = subMesh.getRenderingMesh();
  33534. var scene = this._scene;
  33535. var engine = scene.getEngine();
  33536. // Culling
  33537. engine.setState(subMesh.getMaterial().backFaceCulling);
  33538. // Managing instances
  33539. var batch = mesh._getInstancesRenderList(subMesh._id);
  33540. if (batch.mustReturn) {
  33541. return;
  33542. }
  33543. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33544. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  33545. engine.enableEffect(this._effect);
  33546. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33547. var material = subMesh.getMaterial();
  33548. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  33549. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  33550. this._effect.setVector3("lightPosition", this.getLight().position);
  33551. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  33552. // Alpha test
  33553. if (material && material.needAlphaTesting()) {
  33554. var alphaTexture = material.getAlphaTestTexture();
  33555. if (alphaTexture) {
  33556. this._effect.setTexture("diffuseSampler", alphaTexture);
  33557. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  33558. }
  33559. }
  33560. // Bones
  33561. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33562. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33563. }
  33564. if (this.forceBackFacesOnly) {
  33565. engine.setState(true, 0, false, true);
  33566. }
  33567. // Draw
  33568. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33569. if (this.forceBackFacesOnly) {
  33570. engine.setState(true, 0, false, false);
  33571. }
  33572. }
  33573. else {
  33574. // Need to reset refresh rate of the shadowMap
  33575. this._shadowMap.resetRefreshCounter();
  33576. }
  33577. };
  33578. ShadowGenerator.prototype._applyFilterValues = function () {
  33579. if (this.filter === ShadowGenerator.FILTER_NONE) {
  33580. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  33581. }
  33582. else {
  33583. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33584. }
  33585. };
  33586. /**
  33587. * Boolean : true when the ShadowGenerator is finally computed.
  33588. */
  33589. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  33590. var defines = [];
  33591. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33592. defines.push("#define FLOAT");
  33593. }
  33594. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33595. defines.push("#define ESM");
  33596. }
  33597. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33598. var mesh = subMesh.getMesh();
  33599. var material = subMesh.getMaterial();
  33600. // Alpha test
  33601. if (material && material.needAlphaTesting()) {
  33602. var alphaTexture = material.getAlphaTestTexture();
  33603. if (alphaTexture) {
  33604. defines.push("#define ALPHATEST");
  33605. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33606. attribs.push(BABYLON.VertexBuffer.UVKind);
  33607. defines.push("#define UV1");
  33608. }
  33609. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33610. if (alphaTexture.coordinatesIndex === 1) {
  33611. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33612. defines.push("#define UV2");
  33613. }
  33614. }
  33615. }
  33616. }
  33617. // Bones
  33618. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33619. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33620. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33621. if (mesh.numBoneInfluencers > 4) {
  33622. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33623. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33624. }
  33625. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33626. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33627. }
  33628. else {
  33629. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33630. }
  33631. // Instances
  33632. if (useInstances) {
  33633. defines.push("#define INSTANCES");
  33634. attribs.push("world0");
  33635. attribs.push("world1");
  33636. attribs.push("world2");
  33637. attribs.push("world3");
  33638. }
  33639. // Get correct effect
  33640. var join = defines.join("\n");
  33641. if (this._cachedDefines !== join) {
  33642. this._cachedDefines = join;
  33643. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  33644. }
  33645. return this._effect.isReady();
  33646. };
  33647. /**
  33648. * This creates the defines related to the standard BJS materials.
  33649. */
  33650. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  33651. var scene = this._scene;
  33652. var light = this._light;
  33653. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33654. return;
  33655. }
  33656. defines["SHADOW" + lightIndex] = true;
  33657. if (this.usePoissonSampling) {
  33658. defines["SHADOWPCF" + lightIndex] = true;
  33659. }
  33660. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33661. defines["SHADOWESM" + lightIndex] = true;
  33662. }
  33663. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  33664. defines["SHADOWCLOSEESM" + lightIndex] = true;
  33665. }
  33666. if (light.needCube()) {
  33667. defines["SHADOWCUBE" + lightIndex] = true;
  33668. }
  33669. };
  33670. /**
  33671. * This binds shadow lights related to the standard BJS materials.
  33672. * It implies the unifroms available on the materials are the standard BJS ones.
  33673. */
  33674. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  33675. var light = this._light;
  33676. var scene = this._scene;
  33677. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33678. return;
  33679. }
  33680. if (!light.needCube()) {
  33681. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  33682. }
  33683. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  33684. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  33685. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  33686. };
  33687. // Methods
  33688. /**
  33689. * Returns a Matrix object : the updated transformation matrix.
  33690. */
  33691. ShadowGenerator.prototype.getTransformMatrix = function () {
  33692. var scene = this._scene;
  33693. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  33694. return this._transformMatrix;
  33695. }
  33696. this._currentRenderID = scene.getRenderId();
  33697. this._currentFaceIndexCache = this._currentFaceIndex;
  33698. var lightPosition = this._light.position;
  33699. if (this._light.computeTransformedInformation()) {
  33700. lightPosition = this._light.transformedPosition;
  33701. }
  33702. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  33703. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  33704. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  33705. }
  33706. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  33707. this._cachedPosition = lightPosition.clone();
  33708. this._cachedDirection = this._lightDirection.clone();
  33709. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  33710. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  33711. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  33712. }
  33713. return this._transformMatrix;
  33714. };
  33715. ShadowGenerator.prototype.recreateShadowMap = function () {
  33716. // Track render list.
  33717. var renderList = this._shadowMap.renderList;
  33718. // Clean up existing data.
  33719. this._disposeRTTandPostProcesses();
  33720. // Reinitializes.
  33721. this._initializeGenerator();
  33722. // Reaffect the filter to ensure a correct fallback if necessary.
  33723. this.filter = this.filter;
  33724. // Reaffect the filter.
  33725. this._applyFilterValues();
  33726. // Reaffect Render List.
  33727. this._shadowMap.renderList = renderList;
  33728. };
  33729. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  33730. if (this._shadowMap2) {
  33731. this._shadowMap2.dispose();
  33732. this._shadowMap2 = null;
  33733. }
  33734. if (this._downSamplePostprocess) {
  33735. this._downSamplePostprocess.dispose();
  33736. this._downSamplePostprocess = null;
  33737. }
  33738. if (this._boxBlurPostprocess) {
  33739. this._boxBlurPostprocess.dispose();
  33740. this._boxBlurPostprocess = null;
  33741. }
  33742. if (this._kernelBlurXPostprocess) {
  33743. this._kernelBlurXPostprocess.dispose();
  33744. this._kernelBlurXPostprocess = null;
  33745. }
  33746. if (this._kernelBlurYPostprocess) {
  33747. this._kernelBlurYPostprocess.dispose();
  33748. this._kernelBlurYPostprocess = null;
  33749. }
  33750. this._blurPostProcesses = null;
  33751. };
  33752. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  33753. if (this._shadowMap) {
  33754. this._shadowMap.dispose();
  33755. this._shadowMap = null;
  33756. }
  33757. this._disposeBlurPostProcesses();
  33758. };
  33759. /**
  33760. * Disposes the ShadowGenerator.
  33761. * Returns nothing.
  33762. */
  33763. ShadowGenerator.prototype.dispose = function () {
  33764. this._disposeRTTandPostProcesses();
  33765. this._light._shadowGenerator = null;
  33766. this._light._markMeshesAsLightDirty();
  33767. };
  33768. /**
  33769. * Serializes the ShadowGenerator and returns a serializationObject.
  33770. */
  33771. ShadowGenerator.prototype.serialize = function () {
  33772. var serializationObject = {};
  33773. var shadowMap = this.getShadowMap();
  33774. serializationObject.lightId = this._light.id;
  33775. serializationObject.mapSize = shadowMap.getRenderSize();
  33776. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  33777. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  33778. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33779. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33780. serializationObject.usePoissonSampling = this.usePoissonSampling;
  33781. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  33782. serializationObject.depthScale = this.depthScale;
  33783. serializationObject.darkness = this.getDarkness();
  33784. serializationObject.blurBoxOffset = this.blurBoxOffset;
  33785. serializationObject.blurKernel = this.blurKernel;
  33786. serializationObject.blurScale = this.blurScale;
  33787. serializationObject.useKernelBlur = this.useKernelBlur;
  33788. serializationObject.transparencyShadow = this._transparencyShadow;
  33789. serializationObject.renderList = [];
  33790. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  33791. var mesh = shadowMap.renderList[meshIndex];
  33792. serializationObject.renderList.push(mesh.id);
  33793. }
  33794. return serializationObject;
  33795. };
  33796. /**
  33797. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  33798. */
  33799. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  33800. //casting to point light, as light is missing the position attr and typescript complains.
  33801. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  33802. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  33803. var shadowMap = shadowGenerator.getShadowMap();
  33804. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  33805. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  33806. meshes.forEach(function (mesh) {
  33807. shadowMap.renderList.push(mesh);
  33808. });
  33809. }
  33810. if (parsedShadowGenerator.usePoissonSampling) {
  33811. shadowGenerator.usePoissonSampling = true;
  33812. }
  33813. else if (parsedShadowGenerator.useExponentialShadowMap) {
  33814. shadowGenerator.useExponentialShadowMap = true;
  33815. }
  33816. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33817. shadowGenerator.useBlurExponentialShadowMap = true;
  33818. }
  33819. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  33820. shadowGenerator.useCloseExponentialShadowMap = true;
  33821. }
  33822. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33823. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  33824. }
  33825. else if (parsedShadowGenerator.useVarianceShadowMap) {
  33826. shadowGenerator.useExponentialShadowMap = true;
  33827. }
  33828. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  33829. shadowGenerator.useBlurExponentialShadowMap = true;
  33830. }
  33831. if (parsedShadowGenerator.depthScale) {
  33832. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  33833. }
  33834. if (parsedShadowGenerator.blurScale) {
  33835. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  33836. }
  33837. if (parsedShadowGenerator.blurBoxOffset) {
  33838. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  33839. }
  33840. if (parsedShadowGenerator.useKernelBlur) {
  33841. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  33842. }
  33843. if (parsedShadowGenerator.blurKernel) {
  33844. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  33845. }
  33846. if (parsedShadowGenerator.bias !== undefined) {
  33847. shadowGenerator.bias = parsedShadowGenerator.bias;
  33848. }
  33849. if (parsedShadowGenerator.darkness) {
  33850. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  33851. }
  33852. if (parsedShadowGenerator.transparencyShadow) {
  33853. shadowGenerator.setTransparencyShadow(true);
  33854. }
  33855. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  33856. return shadowGenerator;
  33857. };
  33858. return ShadowGenerator;
  33859. }());
  33860. ShadowGenerator._FILTER_NONE = 0;
  33861. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  33862. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  33863. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  33864. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  33865. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  33866. BABYLON.ShadowGenerator = ShadowGenerator;
  33867. })(BABYLON || (BABYLON = {}));
  33868. //# sourceMappingURL=babylon.shadowGenerator.js.map
  33869. var BABYLON;
  33870. (function (BABYLON) {
  33871. var ShadowLight = (function (_super) {
  33872. __extends(ShadowLight, _super);
  33873. function ShadowLight() {
  33874. var _this = _super !== null && _super.apply(this, arguments) || this;
  33875. _this._needProjectionMatrixCompute = true;
  33876. return _this;
  33877. }
  33878. Object.defineProperty(ShadowLight.prototype, "direction", {
  33879. get: function () {
  33880. return this._direction;
  33881. },
  33882. set: function (value) {
  33883. this._direction = value;
  33884. },
  33885. enumerable: true,
  33886. configurable: true
  33887. });
  33888. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33889. get: function () {
  33890. return this._shadowMinZ;
  33891. },
  33892. set: function (value) {
  33893. this._shadowMinZ = value;
  33894. this.forceProjectionMatrixCompute();
  33895. },
  33896. enumerable: true,
  33897. configurable: true
  33898. });
  33899. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33900. get: function () {
  33901. return this._shadowMaxZ;
  33902. },
  33903. set: function (value) {
  33904. this._shadowMaxZ = value;
  33905. this.forceProjectionMatrixCompute();
  33906. },
  33907. enumerable: true,
  33908. configurable: true
  33909. });
  33910. /**
  33911. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33912. */
  33913. ShadowLight.prototype.computeTransformedInformation = function () {
  33914. if (this.parent && this.parent.getWorldMatrix) {
  33915. if (!this.transformedPosition) {
  33916. this.transformedPosition = BABYLON.Vector3.Zero();
  33917. }
  33918. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33919. // In case the direction is present.
  33920. if (this.direction) {
  33921. if (!this.transformedDirection) {
  33922. this.transformedDirection = BABYLON.Vector3.Zero();
  33923. }
  33924. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33925. }
  33926. return true;
  33927. }
  33928. return false;
  33929. };
  33930. /**
  33931. * Return the depth scale used for the shadow map.
  33932. */
  33933. ShadowLight.prototype.getDepthScale = function () {
  33934. return 50.0;
  33935. };
  33936. /**
  33937. * Returns the light direction (Vector3) for any passed face index.
  33938. */
  33939. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33940. return this.transformedDirection ? this.transformedDirection : this.direction;
  33941. };
  33942. /**
  33943. * Returns the DirectionalLight absolute position in the World.
  33944. */
  33945. ShadowLight.prototype.getAbsolutePosition = function () {
  33946. return this.transformedPosition ? this.transformedPosition : this.position;
  33947. };
  33948. /**
  33949. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33950. * Returns the updated DirectionalLight direction (Vector3).
  33951. */
  33952. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33953. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33954. return this.direction;
  33955. };
  33956. /**
  33957. * Returns the light rotation (Vector3).
  33958. */
  33959. ShadowLight.prototype.getRotation = function () {
  33960. this.direction.normalize();
  33961. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33962. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33963. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33964. };
  33965. /**
  33966. * Boolean : false by default.
  33967. */
  33968. ShadowLight.prototype.needCube = function () {
  33969. return false;
  33970. };
  33971. /**
  33972. * Specifies wether or not the projection matrix should be recomputed this frame.
  33973. */
  33974. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33975. return this._needProjectionMatrixCompute;
  33976. };
  33977. /**
  33978. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33979. */
  33980. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33981. this._needProjectionMatrixCompute = true;
  33982. };
  33983. /**
  33984. * Get the world matrix of the sahdow lights.
  33985. */
  33986. ShadowLight.prototype._getWorldMatrix = function () {
  33987. if (!this._worldMatrix) {
  33988. this._worldMatrix = BABYLON.Matrix.Identity();
  33989. }
  33990. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33991. return this._worldMatrix;
  33992. };
  33993. /**
  33994. * Gets the minZ used for shadow according to both the scene and the light.
  33995. * @param activeCamera
  33996. */
  33997. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33998. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33999. };
  34000. /**
  34001. * Gets the maxZ used for shadow according to both the scene and the light.
  34002. * @param activeCamera
  34003. */
  34004. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  34005. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  34006. };
  34007. /**
  34008. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  34009. * Returns the light.
  34010. */
  34011. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34012. if (this.customProjectionMatrixBuilder) {
  34013. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  34014. }
  34015. else {
  34016. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34017. }
  34018. return this;
  34019. };
  34020. return ShadowLight;
  34021. }(BABYLON.Light));
  34022. __decorate([
  34023. BABYLON.serializeAsVector3()
  34024. ], ShadowLight.prototype, "position", void 0);
  34025. __decorate([
  34026. BABYLON.serializeAsVector3()
  34027. ], ShadowLight.prototype, "direction", null);
  34028. __decorate([
  34029. BABYLON.serialize()
  34030. ], ShadowLight.prototype, "shadowMinZ", null);
  34031. __decorate([
  34032. BABYLON.serialize()
  34033. ], ShadowLight.prototype, "shadowMaxZ", null);
  34034. BABYLON.ShadowLight = ShadowLight;
  34035. })(BABYLON || (BABYLON = {}));
  34036. //# sourceMappingURL=babylon.shadowLight.js.map
  34037. var BABYLON;
  34038. (function (BABYLON) {
  34039. var PointLight = (function (_super) {
  34040. __extends(PointLight, _super);
  34041. /**
  34042. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  34043. * A PointLight emits the light in every direction.
  34044. * It can cast shadows.
  34045. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  34046. * ```javascript
  34047. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  34048. * ```
  34049. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34050. */
  34051. function PointLight(name, position, scene) {
  34052. var _this = _super.call(this, name, scene) || this;
  34053. _this._shadowAngle = Math.PI / 2;
  34054. _this.position = position;
  34055. return _this;
  34056. }
  34057. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  34058. /**
  34059. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34060. * This specifies what angle the shadow will use to be created.
  34061. *
  34062. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34063. */
  34064. get: function () {
  34065. return this._shadowAngle;
  34066. },
  34067. /**
  34068. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34069. * This specifies what angle the shadow will use to be created.
  34070. *
  34071. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  34072. */
  34073. set: function (value) {
  34074. this._shadowAngle = value;
  34075. this.forceProjectionMatrixCompute();
  34076. },
  34077. enumerable: true,
  34078. configurable: true
  34079. });
  34080. Object.defineProperty(PointLight.prototype, "direction", {
  34081. get: function () {
  34082. return this._direction;
  34083. },
  34084. /**
  34085. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  34086. */
  34087. set: function (value) {
  34088. var previousNeedCube = this.needCube();
  34089. this._direction = value;
  34090. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  34091. this._shadowGenerator.recreateShadowMap();
  34092. }
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. /**
  34098. * Returns the string "PointLight"
  34099. */
  34100. PointLight.prototype.getClassName = function () {
  34101. return "PointLight";
  34102. };
  34103. /**
  34104. * Returns the integer 0.
  34105. */
  34106. PointLight.prototype.getTypeID = function () {
  34107. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  34108. };
  34109. /**
  34110. * Specifies wether or not the shadowmap should be a cube texture.
  34111. */
  34112. PointLight.prototype.needCube = function () {
  34113. return !this.direction;
  34114. };
  34115. /**
  34116. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  34117. */
  34118. PointLight.prototype.getShadowDirection = function (faceIndex) {
  34119. if (this.direction) {
  34120. return _super.prototype.getShadowDirection.call(this, faceIndex);
  34121. }
  34122. else {
  34123. switch (faceIndex) {
  34124. case 0:
  34125. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  34126. case 1:
  34127. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  34128. case 2:
  34129. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  34130. case 3:
  34131. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  34132. case 4:
  34133. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  34134. case 5:
  34135. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  34136. }
  34137. }
  34138. return BABYLON.Vector3.Zero();
  34139. };
  34140. /**
  34141. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  34142. * - fov = PI / 2
  34143. * - aspect ratio : 1.0
  34144. * - z-near and far equal to the active camera minZ and maxZ.
  34145. * Returns the PointLight.
  34146. */
  34147. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34148. var activeCamera = this.getScene().activeCamera;
  34149. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34150. };
  34151. PointLight.prototype._buildUniformLayout = function () {
  34152. this._uniformBuffer.addUniform("vLightData", 4);
  34153. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34154. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34155. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34156. this._uniformBuffer.addUniform("depthValues", 2);
  34157. this._uniformBuffer.create();
  34158. };
  34159. /**
  34160. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  34161. * Returns the PointLight.
  34162. */
  34163. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  34164. if (this.computeTransformedInformation()) {
  34165. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  34166. return this;
  34167. }
  34168. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  34169. return this;
  34170. };
  34171. return PointLight;
  34172. }(BABYLON.ShadowLight));
  34173. __decorate([
  34174. BABYLON.serialize()
  34175. ], PointLight.prototype, "shadowAngle", null);
  34176. BABYLON.PointLight = PointLight;
  34177. })(BABYLON || (BABYLON = {}));
  34178. //# sourceMappingURL=babylon.pointLight.js.map
  34179. /// <reference path="babylon.light.ts" />
  34180. var BABYLON;
  34181. (function (BABYLON) {
  34182. var DirectionalLight = (function (_super) {
  34183. __extends(DirectionalLight, _super);
  34184. /**
  34185. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  34186. * The directional light is emitted from everywhere in the given direction.
  34187. * It can cast shawdows.
  34188. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34189. */
  34190. function DirectionalLight(name, direction, scene) {
  34191. var _this = _super.call(this, name, scene) || this;
  34192. _this._shadowFrustumSize = 0;
  34193. _this._shadowOrthoScale = 0.5;
  34194. _this.autoUpdateExtends = true;
  34195. // Cache
  34196. _this._orthoLeft = Number.MAX_VALUE;
  34197. _this._orthoRight = Number.MIN_VALUE;
  34198. _this._orthoTop = Number.MIN_VALUE;
  34199. _this._orthoBottom = Number.MAX_VALUE;
  34200. _this.position = direction.scale(-1.0);
  34201. _this.direction = direction;
  34202. return _this;
  34203. }
  34204. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  34205. /**
  34206. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  34207. */
  34208. get: function () {
  34209. return this._shadowFrustumSize;
  34210. },
  34211. /**
  34212. * Specifies a fix frustum size for the shadow generation.
  34213. */
  34214. set: function (value) {
  34215. this._shadowFrustumSize = value;
  34216. this.forceProjectionMatrixCompute();
  34217. },
  34218. enumerable: true,
  34219. configurable: true
  34220. });
  34221. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  34222. get: function () {
  34223. return this._shadowOrthoScale;
  34224. },
  34225. set: function (value) {
  34226. this._shadowOrthoScale = value;
  34227. this.forceProjectionMatrixCompute();
  34228. },
  34229. enumerable: true,
  34230. configurable: true
  34231. });
  34232. /**
  34233. * Returns the string "DirectionalLight".
  34234. */
  34235. DirectionalLight.prototype.getClassName = function () {
  34236. return "DirectionalLight";
  34237. };
  34238. /**
  34239. * Returns the integer 1.
  34240. */
  34241. DirectionalLight.prototype.getTypeID = function () {
  34242. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  34243. };
  34244. /**
  34245. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  34246. * Returns the DirectionalLight Shadow projection matrix.
  34247. */
  34248. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34249. if (this.shadowFrustumSize > 0) {
  34250. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  34251. }
  34252. else {
  34253. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  34254. }
  34255. };
  34256. /**
  34257. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  34258. * Returns the DirectionalLight Shadow projection matrix.
  34259. */
  34260. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  34261. var activeCamera = this.getScene().activeCamera;
  34262. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  34263. };
  34264. /**
  34265. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  34266. * Returns the DirectionalLight Shadow projection matrix.
  34267. */
  34268. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34269. var activeCamera = this.getScene().activeCamera;
  34270. // Check extends
  34271. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34272. var tempVector3 = BABYLON.Vector3.Zero();
  34273. this._orthoLeft = Number.MAX_VALUE;
  34274. this._orthoRight = Number.MIN_VALUE;
  34275. this._orthoTop = Number.MIN_VALUE;
  34276. this._orthoBottom = Number.MAX_VALUE;
  34277. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34278. var mesh = renderList[meshIndex];
  34279. if (!mesh) {
  34280. continue;
  34281. }
  34282. var boundingInfo = mesh.getBoundingInfo();
  34283. if (!boundingInfo) {
  34284. continue;
  34285. }
  34286. var boundingBox = boundingInfo.boundingBox;
  34287. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34288. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34289. if (tempVector3.x < this._orthoLeft)
  34290. this._orthoLeft = tempVector3.x;
  34291. if (tempVector3.y < this._orthoBottom)
  34292. this._orthoBottom = tempVector3.y;
  34293. if (tempVector3.x > this._orthoRight)
  34294. this._orthoRight = tempVector3.x;
  34295. if (tempVector3.y > this._orthoTop)
  34296. this._orthoTop = tempVector3.y;
  34297. }
  34298. }
  34299. }
  34300. var xOffset = this._orthoRight - this._orthoLeft;
  34301. var yOffset = this._orthoTop - this._orthoBottom;
  34302. 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);
  34303. };
  34304. DirectionalLight.prototype._buildUniformLayout = function () {
  34305. this._uniformBuffer.addUniform("vLightData", 4);
  34306. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34307. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34308. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34309. this._uniformBuffer.addUniform("depthValues", 2);
  34310. this._uniformBuffer.create();
  34311. };
  34312. /**
  34313. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34314. * Returns the DirectionalLight.
  34315. */
  34316. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34317. if (this.computeTransformedInformation()) {
  34318. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34319. return this;
  34320. }
  34321. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34322. return this;
  34323. };
  34324. /**
  34325. * Gets the minZ used for shadow according to both the scene and the light.
  34326. *
  34327. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34328. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34329. * @param activeCamera
  34330. */
  34331. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34332. return 1;
  34333. };
  34334. /**
  34335. * Gets the maxZ used for shadow according to both the scene and the light.
  34336. *
  34337. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34338. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34339. * @param activeCamera
  34340. */
  34341. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34342. return 1;
  34343. };
  34344. return DirectionalLight;
  34345. }(BABYLON.ShadowLight));
  34346. __decorate([
  34347. BABYLON.serialize()
  34348. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34349. __decorate([
  34350. BABYLON.serialize()
  34351. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34352. __decorate([
  34353. BABYLON.serialize()
  34354. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34355. BABYLON.DirectionalLight = DirectionalLight;
  34356. })(BABYLON || (BABYLON = {}));
  34357. //# sourceMappingURL=babylon.directionalLight.js.map
  34358. var BABYLON;
  34359. (function (BABYLON) {
  34360. var SpotLight = (function (_super) {
  34361. __extends(SpotLight, _super);
  34362. /**
  34363. * Creates a SpotLight object in the scene with the passed parameters :
  34364. * - `position` (Vector3) is the initial SpotLight position,
  34365. * - `direction` (Vector3) is the initial SpotLight direction,
  34366. * - `angle` (float, in radians) is the spot light cone angle,
  34367. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34368. * A spot light is a simply light oriented cone.
  34369. * It can cast shadows.
  34370. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34371. */
  34372. function SpotLight(name, position, direction, angle, exponent, scene) {
  34373. var _this = _super.call(this, name, scene) || this;
  34374. _this.position = position;
  34375. _this.direction = direction;
  34376. _this.angle = angle;
  34377. _this.exponent = exponent;
  34378. return _this;
  34379. }
  34380. Object.defineProperty(SpotLight.prototype, "angle", {
  34381. get: function () {
  34382. return this._angle;
  34383. },
  34384. set: function (value) {
  34385. this._angle = value;
  34386. this.forceProjectionMatrixCompute();
  34387. },
  34388. enumerable: true,
  34389. configurable: true
  34390. });
  34391. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34392. get: function () {
  34393. return this._shadowAngleScale;
  34394. },
  34395. /**
  34396. * Allows scaling the angle of the light for shadow generation only.
  34397. */
  34398. set: function (value) {
  34399. this._shadowAngleScale = value;
  34400. this.forceProjectionMatrixCompute();
  34401. },
  34402. enumerable: true,
  34403. configurable: true
  34404. });
  34405. /**
  34406. * Returns the string "SpotLight".
  34407. */
  34408. SpotLight.prototype.getClassName = function () {
  34409. return "SpotLight";
  34410. };
  34411. /**
  34412. * Returns the integer 2.
  34413. */
  34414. SpotLight.prototype.getTypeID = function () {
  34415. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34416. };
  34417. /**
  34418. * 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.
  34419. * Returns the SpotLight.
  34420. */
  34421. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34422. var activeCamera = this.getScene().activeCamera;
  34423. this._shadowAngleScale = this._shadowAngleScale || 1;
  34424. var angle = this._shadowAngleScale * this._angle;
  34425. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34426. };
  34427. SpotLight.prototype._buildUniformLayout = function () {
  34428. this._uniformBuffer.addUniform("vLightData", 4);
  34429. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34430. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34431. this._uniformBuffer.addUniform("vLightDirection", 3);
  34432. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34433. this._uniformBuffer.addUniform("depthValues", 2);
  34434. this._uniformBuffer.create();
  34435. };
  34436. /**
  34437. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34438. * Return the SpotLight.
  34439. */
  34440. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34441. var normalizeDirection;
  34442. if (this.computeTransformedInformation()) {
  34443. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34444. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34445. }
  34446. else {
  34447. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34448. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34449. }
  34450. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34451. return this;
  34452. };
  34453. return SpotLight;
  34454. }(BABYLON.ShadowLight));
  34455. __decorate([
  34456. BABYLON.serialize()
  34457. ], SpotLight.prototype, "angle", null);
  34458. __decorate([
  34459. BABYLON.serialize()
  34460. /**
  34461. * Allows scaling the angle of the light for shadow generation only.
  34462. */
  34463. ], SpotLight.prototype, "shadowAngleScale", null);
  34464. __decorate([
  34465. BABYLON.serialize()
  34466. ], SpotLight.prototype, "exponent", void 0);
  34467. BABYLON.SpotLight = SpotLight;
  34468. })(BABYLON || (BABYLON = {}));
  34469. //# sourceMappingURL=babylon.spotLight.js.map
  34470. var BABYLON;
  34471. (function (BABYLON) {
  34472. var MultiMaterial = (function (_super) {
  34473. __extends(MultiMaterial, _super);
  34474. function MultiMaterial(name, scene) {
  34475. var _this = _super.call(this, name, scene, true) || this;
  34476. scene.multiMaterials.push(_this);
  34477. _this.subMaterials = new Array();
  34478. return _this;
  34479. }
  34480. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  34481. get: function () {
  34482. return this._subMaterials;
  34483. },
  34484. set: function (value) {
  34485. this._subMaterials = value;
  34486. this._hookArray(value);
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. MultiMaterial.prototype._hookArray = function (array) {
  34492. var _this = this;
  34493. var oldPush = array.push;
  34494. array.push = function () {
  34495. var items = [];
  34496. for (var _i = 0; _i < arguments.length; _i++) {
  34497. items[_i] = arguments[_i];
  34498. }
  34499. var result = oldPush.apply(array, items);
  34500. _this._markAllSubMeshesAsTexturesDirty();
  34501. return result;
  34502. };
  34503. var oldSplice = array.splice;
  34504. array.splice = function (index, deleteCount) {
  34505. var deleted = oldSplice.apply(array, [index, deleteCount]);
  34506. _this._markAllSubMeshesAsTexturesDirty();
  34507. return deleted;
  34508. };
  34509. };
  34510. // Properties
  34511. MultiMaterial.prototype.getSubMaterial = function (index) {
  34512. if (index < 0 || index >= this.subMaterials.length) {
  34513. return this.getScene().defaultMaterial;
  34514. }
  34515. return this.subMaterials[index];
  34516. };
  34517. MultiMaterial.prototype.getActiveTextures = function () {
  34518. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  34519. var _a;
  34520. };
  34521. // Methods
  34522. MultiMaterial.prototype.getClassName = function () {
  34523. return "MultiMaterial";
  34524. };
  34525. MultiMaterial.prototype.isReady = function (mesh) {
  34526. for (var index = 0; index < this.subMaterials.length; index++) {
  34527. var subMaterial = this.subMaterials[index];
  34528. if (subMaterial) {
  34529. if (!this.subMaterials[index].isReady(mesh)) {
  34530. return false;
  34531. }
  34532. }
  34533. }
  34534. return true;
  34535. };
  34536. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  34537. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  34538. for (var index = 0; index < this.subMaterials.length; index++) {
  34539. var subMaterial = null;
  34540. if (cloneChildren) {
  34541. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  34542. }
  34543. else {
  34544. subMaterial = this.subMaterials[index];
  34545. }
  34546. newMultiMaterial.subMaterials.push(subMaterial);
  34547. }
  34548. return newMultiMaterial;
  34549. };
  34550. MultiMaterial.prototype.serialize = function () {
  34551. var serializationObject = {};
  34552. serializationObject.name = this.name;
  34553. serializationObject.id = this.id;
  34554. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34555. serializationObject.materials = [];
  34556. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  34557. var subMat = this.subMaterials[matIndex];
  34558. if (subMat) {
  34559. serializationObject.materials.push(subMat.id);
  34560. }
  34561. else {
  34562. serializationObject.materials.push(null);
  34563. }
  34564. }
  34565. return serializationObject;
  34566. };
  34567. return MultiMaterial;
  34568. }(BABYLON.Material));
  34569. BABYLON.MultiMaterial = MultiMaterial;
  34570. })(BABYLON || (BABYLON = {}));
  34571. //# sourceMappingURL=babylon.multiMaterial.js.map
  34572. var BABYLON;
  34573. (function (BABYLON) {
  34574. var PBRMaterialDefines = (function (_super) {
  34575. __extends(PBRMaterialDefines, _super);
  34576. function PBRMaterialDefines() {
  34577. var _this = _super.call(this) || this;
  34578. _this.PBR = true;
  34579. _this.ALBEDO = false;
  34580. _this.AMBIENT = false;
  34581. _this.AMBIENTINGRAYSCALE = false;
  34582. _this.OPACITY = false;
  34583. _this.OPACITYRGB = false;
  34584. _this.REFLECTION = false;
  34585. _this.EMISSIVE = false;
  34586. _this.REFLECTIVITY = false;
  34587. _this.BUMP = false;
  34588. _this.PARALLAX = false;
  34589. _this.PARALLAXOCCLUSION = false;
  34590. _this.SPECULAROVERALPHA = false;
  34591. _this.CLIPPLANE = false;
  34592. _this.ALPHATEST = false;
  34593. _this.ALPHABLEND = false;
  34594. _this.ALPHAFROMALBEDO = false;
  34595. _this.POINTSIZE = false;
  34596. _this.FOG = false;
  34597. _this.SPECULARTERM = false;
  34598. _this.NORMAL = false;
  34599. _this.TANGENT = false;
  34600. _this.UV1 = false;
  34601. _this.UV2 = false;
  34602. _this.VERTEXCOLOR = false;
  34603. _this.VERTEXALPHA = false;
  34604. _this.NUM_BONE_INFLUENCERS = 0;
  34605. _this.BonesPerMesh = 0;
  34606. _this.INSTANCES = false;
  34607. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34608. _this.MICROSURFACEAUTOMATIC = false;
  34609. _this.LIGHTMAP = false;
  34610. _this.USELIGHTMAPASSHADOWMAP = false;
  34611. _this.REFLECTIONMAP_3D = false;
  34612. _this.REFLECTIONMAP_SPHERICAL = false;
  34613. _this.REFLECTIONMAP_PLANAR = false;
  34614. _this.REFLECTIONMAP_CUBIC = false;
  34615. _this.REFLECTIONMAP_PROJECTION = false;
  34616. _this.REFLECTIONMAP_SKYBOX = false;
  34617. _this.REFLECTIONMAP_EXPLICIT = false;
  34618. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34619. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34620. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34621. _this.INVERTCUBICMAP = false;
  34622. _this.LOGARITHMICDEPTH = false;
  34623. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34624. _this.REFRACTION = false;
  34625. _this.REFRACTIONMAP_3D = false;
  34626. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34627. _this.REFRACTIONMAPINLINEARSPACE = false;
  34628. _this.LODBASEDMICROSFURACE = false;
  34629. _this.USEPHYSICALLIGHTFALLOFF = false;
  34630. _this.RADIANCEOVERALPHA = false;
  34631. _this.USEPMREMREFLECTION = false;
  34632. _this.USEPMREMREFRACTION = false;
  34633. _this.INVERTNORMALMAPX = false;
  34634. _this.INVERTNORMALMAPY = false;
  34635. _this.TWOSIDEDLIGHTING = false;
  34636. _this.SHADOWFLOAT = false;
  34637. _this.NORMALXYSCALE = true;
  34638. _this.USERIGHTHANDEDSYSTEM = false;
  34639. _this.METALLICWORKFLOW = false;
  34640. _this.METALLICMAP = false;
  34641. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34642. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34643. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34644. _this.AOSTOREINMETALMAPRED = false;
  34645. _this.MICROSURFACEMAP = false;
  34646. _this.MORPHTARGETS = false;
  34647. _this.MORPHTARGETS_NORMAL = false;
  34648. _this.MORPHTARGETS_TANGENT = false;
  34649. _this.NUM_MORPH_INFLUENCERS = 0;
  34650. _this.ALPHATESTVALUE = 0.5;
  34651. _this.PREMULTIPLYALPHA = false;
  34652. _this.ALPHAFRESNEL = false;
  34653. _this.IMAGEPROCESSING = false;
  34654. _this.VIGNETTE = false;
  34655. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34656. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34657. _this.TONEMAPPING = false;
  34658. _this.CONTRAST = false;
  34659. _this.COLORCURVES = false;
  34660. _this.COLORGRADING = false;
  34661. _this.SAMPLER3DGREENDEPTH = false;
  34662. _this.SAMPLER3DBGRMAP = false;
  34663. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34664. _this.EXPOSURE = false;
  34665. _this.rebuild();
  34666. return _this;
  34667. }
  34668. PBRMaterialDefines.prototype.reset = function () {
  34669. _super.prototype.reset.call(this);
  34670. this.ALPHATESTVALUE = 0.5;
  34671. this.PBR = true;
  34672. };
  34673. return PBRMaterialDefines;
  34674. }(BABYLON.MaterialDefines));
  34675. /**
  34676. * The Physically based material base class of BJS.
  34677. *
  34678. * This offers the main features of a standard PBR material.
  34679. * For more information, please refer to the documentation :
  34680. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34681. */
  34682. var PBRBaseMaterial = (function (_super) {
  34683. __extends(PBRBaseMaterial, _super);
  34684. /**
  34685. * Instantiates a new PBRMaterial instance.
  34686. *
  34687. * @param name The material name
  34688. * @param scene The scene the material will be use in.
  34689. */
  34690. function PBRBaseMaterial(name, scene) {
  34691. var _this = _super.call(this, name, scene) || this;
  34692. /**
  34693. * Intensity of the direct lights e.g. the four lights available in your scene.
  34694. * This impacts both the direct diffuse and specular highlights.
  34695. */
  34696. _this._directIntensity = 1.0;
  34697. /**
  34698. * Intensity of the emissive part of the material.
  34699. * This helps controlling the emissive effect without modifying the emissive color.
  34700. */
  34701. _this._emissiveIntensity = 1.0;
  34702. /**
  34703. * Intensity of the environment e.g. how much the environment will light the object
  34704. * either through harmonics for rough material or through the refelction for shiny ones.
  34705. */
  34706. _this._environmentIntensity = 1.0;
  34707. /**
  34708. * This is a special control allowing the reduction of the specular highlights coming from the
  34709. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34710. */
  34711. _this._specularIntensity = 1.0;
  34712. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34713. /**
  34714. * Debug Control allowing disabling the bump map on this material.
  34715. */
  34716. _this._disableBumpMap = false;
  34717. /**
  34718. * AKA Occlusion Texture Intensity in other nomenclature.
  34719. */
  34720. _this._ambientTextureStrength = 1.0;
  34721. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  34722. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34723. /**
  34724. * AKA Diffuse Color in other nomenclature.
  34725. */
  34726. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34727. /**
  34728. * AKA Specular Color in other nomenclature.
  34729. */
  34730. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34731. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34732. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34733. /**
  34734. * AKA Glossiness in other nomenclature.
  34735. */
  34736. _this._microSurface = 0.9;
  34737. /**
  34738. * source material index of refraction (IOR)' / 'destination material IOR.
  34739. */
  34740. _this._indexOfRefraction = 0.66;
  34741. /**
  34742. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34743. */
  34744. _this._invertRefractionY = false;
  34745. /**
  34746. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34747. * Materials half opaque for instance using refraction could benefit from this control.
  34748. */
  34749. _this._linkRefractionWithTransparency = false;
  34750. _this._useLightmapAsShadowmap = false;
  34751. /**
  34752. * Specifies that the alpha is coming form the albedo channel alpha channel.
  34753. */
  34754. _this._useAlphaFromAlbedoTexture = false;
  34755. /**
  34756. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34757. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34758. */
  34759. _this._useSpecularOverAlpha = true;
  34760. /**
  34761. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34762. */
  34763. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34764. /**
  34765. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34766. */
  34767. _this._useRoughnessFromMetallicTextureAlpha = true;
  34768. /**
  34769. * Specifies if the metallic texture contains the roughness information in its green channel.
  34770. */
  34771. _this._useRoughnessFromMetallicTextureGreen = false;
  34772. /**
  34773. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34774. */
  34775. _this._useMetallnessFromMetallicTextureBlue = false;
  34776. /**
  34777. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34778. */
  34779. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34780. /**
  34781. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34782. */
  34783. _this._useAmbientInGrayScale = false;
  34784. /**
  34785. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34786. * The material will try to infer what glossiness each pixel should be.
  34787. */
  34788. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34789. /**
  34790. * BJS is using an harcoded light falloff based on a manually sets up range.
  34791. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34792. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34793. */
  34794. _this._usePhysicalLightFalloff = true;
  34795. /**
  34796. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34797. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34798. */
  34799. _this._useRadianceOverAlpha = true;
  34800. /**
  34801. * Allows using the bump map in parallax mode.
  34802. */
  34803. _this._useParallax = false;
  34804. /**
  34805. * Allows using the bump map in parallax occlusion mode.
  34806. */
  34807. _this._useParallaxOcclusion = false;
  34808. /**
  34809. * Controls the scale bias of the parallax mode.
  34810. */
  34811. _this._parallaxScaleBias = 0.05;
  34812. /**
  34813. * If sets to true, disables all the lights affecting the material.
  34814. */
  34815. _this._disableLighting = false;
  34816. /**
  34817. * Number of Simultaneous lights allowed on the material.
  34818. */
  34819. _this._maxSimultaneousLights = 4;
  34820. /**
  34821. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34822. */
  34823. _this._invertNormalMapX = false;
  34824. /**
  34825. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34826. */
  34827. _this._invertNormalMapY = false;
  34828. /**
  34829. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34830. */
  34831. _this._twoSidedLighting = false;
  34832. /**
  34833. * Defines the alpha limits in alpha test mode.
  34834. */
  34835. _this._alphaCutOff = 0.4;
  34836. /**
  34837. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34838. */
  34839. _this._forceAlphaTest = false;
  34840. /**
  34841. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  34842. * in your scene composition.
  34843. */
  34844. _this._premultiplyAlpha = false;
  34845. /**
  34846. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  34847. * And/Or occlude the blended part.
  34848. */
  34849. _this._useAlphaFresnel = false;
  34850. _this._renderTargets = new BABYLON.SmartArray(16);
  34851. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34852. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34853. _this._tempColor = new BABYLON.Color3();
  34854. // Setup the default processing configuration to the scene.
  34855. _this._attachImageProcessingConfiguration(null);
  34856. _this.getRenderTargetTextures = function () {
  34857. _this._renderTargets.reset();
  34858. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34859. _this._renderTargets.push(_this._reflectionTexture);
  34860. }
  34861. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34862. _this._renderTargets.push(_this._refractionTexture);
  34863. }
  34864. return _this._renderTargets;
  34865. };
  34866. return _this;
  34867. }
  34868. /**
  34869. * Attaches a new image processing configuration to the PBR Material.
  34870. * @param configuration
  34871. */
  34872. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34873. var _this = this;
  34874. if (configuration === this._imageProcessingConfiguration) {
  34875. return;
  34876. }
  34877. // Detaches observer.
  34878. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34879. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34880. }
  34881. // Pick the scene configuration if needed.
  34882. if (!configuration) {
  34883. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34884. }
  34885. else {
  34886. this._imageProcessingConfiguration = configuration;
  34887. }
  34888. // Attaches observer.
  34889. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34890. _this._markAllSubMeshesAsImageProcessingDirty();
  34891. });
  34892. };
  34893. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34894. get: function () {
  34895. return this._useLogarithmicDepth;
  34896. },
  34897. set: function (value) {
  34898. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34899. },
  34900. enumerable: true,
  34901. configurable: true
  34902. });
  34903. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34904. if (this._linkRefractionWithTransparency) {
  34905. return false;
  34906. }
  34907. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  34908. };
  34909. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34910. if (this._forceAlphaTest) {
  34911. return true;
  34912. }
  34913. if (this._linkRefractionWithTransparency) {
  34914. return false;
  34915. }
  34916. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34917. };
  34918. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34919. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34920. };
  34921. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34922. return this._albedoTexture;
  34923. };
  34924. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34925. if (this.isFrozen) {
  34926. if (this._wasPreviouslyReady) {
  34927. return true;
  34928. }
  34929. }
  34930. if (!subMesh._materialDefines) {
  34931. subMesh._materialDefines = new PBRMaterialDefines();
  34932. }
  34933. var scene = this.getScene();
  34934. var defines = subMesh._materialDefines;
  34935. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34936. if (defines._renderId === scene.getRenderId()) {
  34937. return true;
  34938. }
  34939. }
  34940. var engine = scene.getEngine();
  34941. // Lights
  34942. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34943. defines._needNormals = true;
  34944. // Textures
  34945. if (defines._areTexturesDirty) {
  34946. defines._needUVs = false;
  34947. if (scene.texturesEnabled) {
  34948. if (scene.getEngine().getCaps().textureLOD) {
  34949. defines.LODBASEDMICROSFURACE = true;
  34950. }
  34951. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34952. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34953. return false;
  34954. }
  34955. defines._needUVs = true;
  34956. defines.ALBEDO = true;
  34957. }
  34958. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34959. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34960. return false;
  34961. }
  34962. defines._needUVs = true;
  34963. defines.AMBIENT = true;
  34964. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34965. }
  34966. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34967. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34968. return false;
  34969. }
  34970. defines._needUVs = true;
  34971. defines.OPACITY = true;
  34972. if (this._opacityTexture.getAlphaFromRGB) {
  34973. defines.OPACITYRGB = true;
  34974. }
  34975. }
  34976. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  34977. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34978. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34979. return false;
  34980. }
  34981. defines.REFLECTION = true;
  34982. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34983. defines.INVERTCUBICMAP = true;
  34984. }
  34985. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34986. switch (reflectionTexture.coordinatesMode) {
  34987. case BABYLON.Texture.CUBIC_MODE:
  34988. case BABYLON.Texture.INVCUBIC_MODE:
  34989. defines.REFLECTIONMAP_CUBIC = true;
  34990. break;
  34991. case BABYLON.Texture.EXPLICIT_MODE:
  34992. defines.REFLECTIONMAP_EXPLICIT = true;
  34993. break;
  34994. case BABYLON.Texture.PLANAR_MODE:
  34995. defines.REFLECTIONMAP_PLANAR = true;
  34996. break;
  34997. case BABYLON.Texture.PROJECTION_MODE:
  34998. defines.REFLECTIONMAP_PROJECTION = true;
  34999. break;
  35000. case BABYLON.Texture.SKYBOX_MODE:
  35001. defines.REFLECTIONMAP_SKYBOX = true;
  35002. break;
  35003. case BABYLON.Texture.SPHERICAL_MODE:
  35004. defines.REFLECTIONMAP_SPHERICAL = true;
  35005. break;
  35006. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35007. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35008. break;
  35009. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35010. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35011. break;
  35012. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35013. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35014. break;
  35015. }
  35016. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  35017. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35018. if (reflectionTexture.isPMREM) {
  35019. defines.USEPMREMREFLECTION = true;
  35020. }
  35021. }
  35022. }
  35023. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35024. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35025. return false;
  35026. }
  35027. defines._needUVs = true;
  35028. defines.LIGHTMAP = true;
  35029. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35030. }
  35031. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35032. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35033. return false;
  35034. }
  35035. defines._needUVs = true;
  35036. defines.EMISSIVE = true;
  35037. }
  35038. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35039. if (this._metallicTexture) {
  35040. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35041. return false;
  35042. }
  35043. defines._needUVs = true;
  35044. defines.METALLICWORKFLOW = true;
  35045. defines.METALLICMAP = true;
  35046. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35047. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35048. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35049. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35050. }
  35051. else if (this._reflectivityTexture) {
  35052. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35053. return false;
  35054. }
  35055. defines._needUVs = true;
  35056. defines.REFLECTIVITY = true;
  35057. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35058. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35059. }
  35060. if (this._microSurfaceTexture) {
  35061. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35062. return false;
  35063. }
  35064. defines._needUVs = true;
  35065. defines.MICROSURFACEMAP = true;
  35066. }
  35067. }
  35068. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35069. // Bump texure can not be none blocking.
  35070. if (!this._bumpTexture.isReady()) {
  35071. return false;
  35072. }
  35073. defines._needUVs = true;
  35074. defines.BUMP = true;
  35075. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35076. defines.PARALLAX = true;
  35077. if (this._useParallaxOcclusion) {
  35078. defines.PARALLAXOCCLUSION = true;
  35079. }
  35080. }
  35081. if (this._invertNormalMapX) {
  35082. defines.INVERTNORMALMAPX = true;
  35083. }
  35084. if (this._invertNormalMapY) {
  35085. defines.INVERTNORMALMAPY = true;
  35086. }
  35087. if (scene._mirroredCameraPosition) {
  35088. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  35089. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  35090. }
  35091. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  35092. }
  35093. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35094. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35095. return false;
  35096. }
  35097. defines._needUVs = true;
  35098. defines.REFRACTION = true;
  35099. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35100. if (this._linkRefractionWithTransparency) {
  35101. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35102. }
  35103. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  35104. defines.REFRACTIONMAPINLINEARSPACE = true;
  35105. if (this._refractionTexture.isPMREM) {
  35106. defines.USEPMREMREFRACTION = true;
  35107. }
  35108. }
  35109. }
  35110. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35111. defines.ALPHAFROMALBEDO = true;
  35112. }
  35113. }
  35114. if (this._useSpecularOverAlpha) {
  35115. defines.SPECULAROVERALPHA = true;
  35116. }
  35117. if (this._usePhysicalLightFalloff) {
  35118. defines.USEPHYSICALLIGHTFALLOFF = true;
  35119. }
  35120. if (this._useRadianceOverAlpha) {
  35121. defines.RADIANCEOVERALPHA = true;
  35122. }
  35123. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35124. defines.METALLICWORKFLOW = true;
  35125. }
  35126. if (!this.backFaceCulling && this._twoSidedLighting) {
  35127. defines.TWOSIDEDLIGHTING = true;
  35128. }
  35129. defines.ALPHATESTVALUE = this._alphaCutOff;
  35130. defines.PREMULTIPLYALPHA = this._premultiplyAlpha;
  35131. defines.ALPHABLEND = this.needAlphaBlending();
  35132. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35133. }
  35134. if (defines._areImageProcessingDirty) {
  35135. if (!this._imageProcessingConfiguration.isReady()) {
  35136. return false;
  35137. }
  35138. this._imageProcessingConfiguration.prepareDefines(defines);
  35139. }
  35140. // Misc.
  35141. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35142. // Values that need to be evaluated on every frame
  35143. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  35144. // Attribs
  35145. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  35146. if (mesh) {
  35147. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35148. mesh.createNormals(true);
  35149. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35150. }
  35151. }
  35152. }
  35153. // Get correct effect
  35154. if (defines.isDirty) {
  35155. defines.markAsProcessed();
  35156. scene.resetCachedMaterial();
  35157. // Fallbacks
  35158. var fallbacks = new BABYLON.EffectFallbacks();
  35159. if (defines.REFLECTION) {
  35160. fallbacks.addFallback(0, "REFLECTION");
  35161. }
  35162. if (defines.REFRACTION) {
  35163. fallbacks.addFallback(0, "REFRACTION");
  35164. }
  35165. if (defines.REFLECTIVITY) {
  35166. fallbacks.addFallback(0, "REFLECTIVITY");
  35167. }
  35168. if (defines.BUMP) {
  35169. fallbacks.addFallback(0, "BUMP");
  35170. }
  35171. if (defines.PARALLAX) {
  35172. fallbacks.addFallback(1, "PARALLAX");
  35173. }
  35174. if (defines.PARALLAXOCCLUSION) {
  35175. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35176. }
  35177. if (defines.SPECULAROVERALPHA) {
  35178. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35179. }
  35180. if (defines.FOG) {
  35181. fallbacks.addFallback(1, "FOG");
  35182. }
  35183. if (defines.POINTSIZE) {
  35184. fallbacks.addFallback(0, "POINTSIZE");
  35185. }
  35186. if (defines.LOGARITHMICDEPTH) {
  35187. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35188. }
  35189. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35190. if (defines.SPECULARTERM) {
  35191. fallbacks.addFallback(0, "SPECULARTERM");
  35192. }
  35193. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35194. fallbacks.addCPUSkinningFallback(0, mesh);
  35195. }
  35196. //Attributes
  35197. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35198. if (defines.NORMAL) {
  35199. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35200. }
  35201. if (defines.TANGENT) {
  35202. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35203. }
  35204. if (defines.UV1) {
  35205. attribs.push(BABYLON.VertexBuffer.UVKind);
  35206. }
  35207. if (defines.UV2) {
  35208. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35209. }
  35210. if (defines.VERTEXCOLOR) {
  35211. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35212. }
  35213. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35214. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35215. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35216. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35217. "vFogInfos", "vFogColor", "pointSize",
  35218. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35219. "mBones",
  35220. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35221. "vLightingIntensity",
  35222. "logarithmicDepthConstant",
  35223. "vSphericalX", "vSphericalY", "vSphericalZ",
  35224. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35225. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35226. "vMicrosurfaceTextureLods"
  35227. ];
  35228. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35229. var uniformBuffers = ["Material", "Scene"];
  35230. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35231. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35232. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35233. uniformsNames: uniforms,
  35234. uniformBuffersNames: uniformBuffers,
  35235. samplers: samplers,
  35236. defines: defines,
  35237. maxSimultaneousLights: this._maxSimultaneousLights
  35238. });
  35239. var onCompiled = function (effect) {
  35240. if (this.onCompiled) {
  35241. this.onCompiled(effect);
  35242. }
  35243. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35244. }.bind(this);
  35245. var join = defines.toString();
  35246. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35247. attributes: attribs,
  35248. uniformsNames: uniforms,
  35249. uniformBuffersNames: uniformBuffers,
  35250. samplers: samplers,
  35251. defines: join,
  35252. fallbacks: fallbacks,
  35253. onCompiled: onCompiled,
  35254. onError: this.onError,
  35255. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35256. }, engine), defines);
  35257. this.buildUniformLayout();
  35258. }
  35259. if (!subMesh.effect.isReady()) {
  35260. return false;
  35261. }
  35262. defines._renderId = scene.getRenderId();
  35263. this._wasPreviouslyReady = true;
  35264. return true;
  35265. };
  35266. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35267. // Order is important !
  35268. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35269. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35270. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35271. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35272. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35273. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35274. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35275. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35276. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35277. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35278. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35279. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35280. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35281. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35282. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35283. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35284. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35285. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35286. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35287. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35288. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35289. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35290. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35291. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  35292. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35293. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35294. this._uniformBuffer.addUniform("pointSize", 1);
  35295. this._uniformBuffer.create();
  35296. };
  35297. PBRBaseMaterial.prototype.unbind = function () {
  35298. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35299. this._uniformBuffer.setTexture("reflection2DSampler", null);
  35300. }
  35301. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35302. this._uniformBuffer.setTexture("refraction2DSampler", null);
  35303. }
  35304. _super.prototype.unbind.call(this);
  35305. };
  35306. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35307. this._activeEffect.setMatrix("world", world);
  35308. };
  35309. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35310. var scene = this.getScene();
  35311. var defines = subMesh._materialDefines;
  35312. if (!defines) {
  35313. return;
  35314. }
  35315. var effect = subMesh.effect;
  35316. this._activeEffect = effect;
  35317. // Matrices
  35318. this.bindOnlyWorldMatrix(world);
  35319. // Bones
  35320. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35321. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35322. this._uniformBuffer.bindToEffect(effect, "Material");
  35323. this.bindViewProjection(effect);
  35324. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35325. // Texture uniforms
  35326. if (scene.texturesEnabled) {
  35327. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35328. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35329. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  35330. }
  35331. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35332. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35333. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35334. }
  35335. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35336. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35337. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35338. }
  35339. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35340. ;
  35341. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35342. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  35343. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35344. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35345. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35346. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  35347. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  35348. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  35349. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  35350. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  35351. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  35352. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  35353. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  35354. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  35355. }
  35356. }
  35357. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35358. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35359. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35360. }
  35361. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35362. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35363. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35364. }
  35365. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35366. if (this._metallicTexture) {
  35367. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35368. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  35369. }
  35370. else if (this._reflectivityTexture) {
  35371. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35372. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  35373. }
  35374. if (this._microSurfaceTexture) {
  35375. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35376. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  35377. }
  35378. }
  35379. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35380. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35381. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35382. }
  35383. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35384. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  35385. var depth = 1.0;
  35386. if (!this._refractionTexture.isCube) {
  35387. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35388. if (this._refractionTexture.depth) {
  35389. depth = this._refractionTexture.depth;
  35390. }
  35391. }
  35392. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35393. }
  35394. if ((reflectionTexture || this._refractionTexture)) {
  35395. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  35396. }
  35397. }
  35398. // Point size
  35399. if (this.pointsCloud) {
  35400. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35401. }
  35402. // Colors
  35403. if (defines.METALLICWORKFLOW) {
  35404. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35405. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35406. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35407. }
  35408. else {
  35409. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35410. }
  35411. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35412. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35413. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35414. // Misc
  35415. this._lightingInfos.x = this._directIntensity;
  35416. this._lightingInfos.y = this._emissiveIntensity;
  35417. this._lightingInfos.z = this._environmentIntensity;
  35418. this._lightingInfos.w = this._specularIntensity;
  35419. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35420. }
  35421. // Textures
  35422. if (scene.texturesEnabled) {
  35423. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35424. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35425. }
  35426. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35427. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35428. }
  35429. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35430. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35431. }
  35432. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35433. if (reflectionTexture.isCube) {
  35434. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  35435. }
  35436. else {
  35437. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  35438. }
  35439. }
  35440. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35441. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35442. }
  35443. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35444. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35445. }
  35446. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35447. if (this._metallicTexture) {
  35448. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35449. }
  35450. else if (this._reflectivityTexture) {
  35451. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35452. }
  35453. if (this._microSurfaceTexture) {
  35454. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35455. }
  35456. }
  35457. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35458. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35459. }
  35460. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35461. if (this._refractionTexture.isCube) {
  35462. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  35463. }
  35464. else {
  35465. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  35466. }
  35467. }
  35468. }
  35469. // Clip plane
  35470. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35471. // Colors
  35472. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35473. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35474. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35475. }
  35476. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35477. // Lights
  35478. if (scene.lightsEnabled && !this._disableLighting) {
  35479. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35480. }
  35481. // View
  35482. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35483. this.bindView(effect);
  35484. }
  35485. // Fog
  35486. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35487. // Morph targets
  35488. if (defines.NUM_MORPH_INFLUENCERS) {
  35489. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35490. }
  35491. // image processing
  35492. this._imageProcessingConfiguration.bind(this._activeEffect);
  35493. // Log. depth
  35494. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35495. }
  35496. this._uniformBuffer.update();
  35497. this._afterBind(mesh);
  35498. scene = null;
  35499. };
  35500. PBRBaseMaterial.prototype.getAnimatables = function () {
  35501. var results = [];
  35502. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35503. results.push(this._albedoTexture);
  35504. }
  35505. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35506. results.push(this._ambientTexture);
  35507. }
  35508. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35509. results.push(this._opacityTexture);
  35510. }
  35511. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35512. results.push(this._reflectionTexture);
  35513. }
  35514. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35515. results.push(this._emissiveTexture);
  35516. }
  35517. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35518. results.push(this._metallicTexture);
  35519. }
  35520. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35521. results.push(this._reflectivityTexture);
  35522. }
  35523. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35524. results.push(this._bumpTexture);
  35525. }
  35526. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35527. results.push(this._lightmapTexture);
  35528. }
  35529. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35530. results.push(this._refractionTexture);
  35531. }
  35532. return results;
  35533. };
  35534. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35535. if (forceDisposeTextures) {
  35536. if (this._albedoTexture) {
  35537. this._albedoTexture.dispose();
  35538. }
  35539. if (this._ambientTexture) {
  35540. this._ambientTexture.dispose();
  35541. }
  35542. if (this._opacityTexture) {
  35543. this._opacityTexture.dispose();
  35544. }
  35545. if (this._reflectionTexture) {
  35546. this._reflectionTexture.dispose();
  35547. }
  35548. if (this._emissiveTexture) {
  35549. this._emissiveTexture.dispose();
  35550. }
  35551. if (this._metallicTexture) {
  35552. this._metallicTexture.dispose();
  35553. }
  35554. if (this._reflectivityTexture) {
  35555. this._reflectivityTexture.dispose();
  35556. }
  35557. if (this._bumpTexture) {
  35558. this._bumpTexture.dispose();
  35559. }
  35560. if (this._lightmapTexture) {
  35561. this._lightmapTexture.dispose();
  35562. }
  35563. if (this._refractionTexture) {
  35564. this._refractionTexture.dispose();
  35565. }
  35566. }
  35567. this._renderTargets.dispose();
  35568. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35569. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35570. }
  35571. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35572. };
  35573. return PBRBaseMaterial;
  35574. }(BABYLON.PushMaterial));
  35575. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35576. __decorate([
  35577. BABYLON.serializeAsImageProcessingConfiguration()
  35578. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35579. __decorate([
  35580. BABYLON.serialize()
  35581. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35582. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35583. })(BABYLON || (BABYLON = {}));
  35584. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35585. var BABYLON;
  35586. (function (BABYLON) {
  35587. var Internals;
  35588. (function (Internals) {
  35589. /**
  35590. * The Physically based simple base material of BJS.
  35591. *
  35592. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35593. * It is used as the base class for both the specGloss and metalRough conventions.
  35594. */
  35595. var PBRBaseSimpleMaterial = (function (_super) {
  35596. __extends(PBRBaseSimpleMaterial, _super);
  35597. /**
  35598. * Instantiates a new PBRMaterial instance.
  35599. *
  35600. * @param name The material name
  35601. * @param scene The scene the material will be use in.
  35602. */
  35603. function PBRBaseSimpleMaterial(name, scene) {
  35604. var _this = _super.call(this, name, scene) || this;
  35605. /**
  35606. * Number of Simultaneous lights allowed on the material.
  35607. */
  35608. _this.maxSimultaneousLights = 4;
  35609. /**
  35610. * If sets to true, disables all the lights affecting the material.
  35611. */
  35612. _this.disableLighting = false;
  35613. /**
  35614. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35615. */
  35616. _this.invertNormalMapX = false;
  35617. /**
  35618. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35619. */
  35620. _this.invertNormalMapY = false;
  35621. /**
  35622. * Emissivie color used to self-illuminate the model.
  35623. */
  35624. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35625. /**
  35626. * Occlusion Channel Strenght.
  35627. */
  35628. _this.occlusionStrength = 1.0;
  35629. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35630. _this._useAmbientInGrayScale = true;
  35631. return _this;
  35632. }
  35633. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35634. /**
  35635. * Gets the current transparency mode.
  35636. */
  35637. get: function () {
  35638. return this._transparencyMode;
  35639. },
  35640. /**
  35641. * Sets the transparency mode of the material.
  35642. */
  35643. set: function (value) {
  35644. if (this._transparencyMode === value) {
  35645. return;
  35646. }
  35647. this._transparencyMode = value;
  35648. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35649. this._forceAlphaTest = true;
  35650. }
  35651. else {
  35652. this._forceAlphaTest = false;
  35653. }
  35654. this._markAllSubMeshesAsTexturesDirty();
  35655. },
  35656. enumerable: true,
  35657. configurable: true
  35658. });
  35659. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35660. /**
  35661. * Gets the current double sided mode.
  35662. */
  35663. get: function () {
  35664. return this._twoSidedLighting;
  35665. },
  35666. /**
  35667. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35668. */
  35669. set: function (value) {
  35670. if (this._twoSidedLighting === value) {
  35671. return;
  35672. }
  35673. this._twoSidedLighting = value;
  35674. this.backFaceCulling = !value;
  35675. this._markAllSubMeshesAsTexturesDirty();
  35676. },
  35677. enumerable: true,
  35678. configurable: true
  35679. });
  35680. /**
  35681. * Specifies wether or not the alpha value of the albedo texture should be used.
  35682. */
  35683. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35684. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35685. };
  35686. /**
  35687. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35688. */
  35689. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35690. if (this._linkRefractionWithTransparency) {
  35691. return false;
  35692. }
  35693. return (this.alpha < 1.0) ||
  35694. (this._shouldUseAlphaFromAlbedoTexture() &&
  35695. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35696. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35697. };
  35698. /**
  35699. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35700. */
  35701. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35702. if (this._linkRefractionWithTransparency) {
  35703. return false;
  35704. }
  35705. return this._shouldUseAlphaFromAlbedoTexture() &&
  35706. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35707. };
  35708. return PBRBaseSimpleMaterial;
  35709. }(BABYLON.PBRBaseMaterial));
  35710. __decorate([
  35711. BABYLON.serialize(),
  35712. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35713. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35714. __decorate([
  35715. BABYLON.serialize(),
  35716. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35717. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35718. __decorate([
  35719. BABYLON.serializeAsTexture(),
  35720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35721. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35722. __decorate([
  35723. BABYLON.serialize(),
  35724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35725. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35726. __decorate([
  35727. BABYLON.serialize(),
  35728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35729. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35730. __decorate([
  35731. BABYLON.serializeAsTexture(),
  35732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35733. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35734. __decorate([
  35735. BABYLON.serializeAsColor3("emissive"),
  35736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35737. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35738. __decorate([
  35739. BABYLON.serializeAsTexture(),
  35740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35741. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35742. __decorate([
  35743. BABYLON.serialize(),
  35744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35745. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35746. __decorate([
  35747. BABYLON.serializeAsTexture(),
  35748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35749. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35750. __decorate([
  35751. BABYLON.serialize(),
  35752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35753. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35754. __decorate([
  35755. BABYLON.serialize()
  35756. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35757. __decorate([
  35758. BABYLON.serialize()
  35759. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35760. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35761. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35762. })(BABYLON || (BABYLON = {}));
  35763. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35764. var BABYLON;
  35765. (function (BABYLON) {
  35766. /**
  35767. * The Physically based material of BJS.
  35768. *
  35769. * This offers the main features of a standard PBR material.
  35770. * For more information, please refer to the documentation :
  35771. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35772. */
  35773. var PBRMaterial = (function (_super) {
  35774. __extends(PBRMaterial, _super);
  35775. /**
  35776. * Instantiates a new PBRMaterial instance.
  35777. *
  35778. * @param name The material name
  35779. * @param scene The scene the material will be use in.
  35780. */
  35781. function PBRMaterial(name, scene) {
  35782. var _this = _super.call(this, name, scene) || this;
  35783. /**
  35784. * Intensity of the direct lights e.g. the four lights available in your scene.
  35785. * This impacts both the direct diffuse and specular highlights.
  35786. */
  35787. _this.directIntensity = 1.0;
  35788. /**
  35789. * Intensity of the emissive part of the material.
  35790. * This helps controlling the emissive effect without modifying the emissive color.
  35791. */
  35792. _this.emissiveIntensity = 1.0;
  35793. /**
  35794. * Intensity of the environment e.g. how much the environment will light the object
  35795. * either through harmonics for rough material or through the refelction for shiny ones.
  35796. */
  35797. _this.environmentIntensity = 1.0;
  35798. /**
  35799. * This is a special control allowing the reduction of the specular highlights coming from the
  35800. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35801. */
  35802. _this.specularIntensity = 1.0;
  35803. /**
  35804. * Debug Control allowing disabling the bump map on this material.
  35805. */
  35806. _this.disableBumpMap = false;
  35807. /**
  35808. * AKA Occlusion Texture Intensity in other nomenclature.
  35809. */
  35810. _this.ambientTextureStrength = 1.0;
  35811. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35812. /**
  35813. * AKA Diffuse Color in other nomenclature.
  35814. */
  35815. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35816. /**
  35817. * AKA Specular Color in other nomenclature.
  35818. */
  35819. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35820. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35821. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35822. /**
  35823. * AKA Glossiness in other nomenclature.
  35824. */
  35825. _this.microSurface = 0.9;
  35826. /**
  35827. * source material index of refraction (IOR)' / 'destination material IOR.
  35828. */
  35829. _this.indexOfRefraction = 0.66;
  35830. /**
  35831. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35832. */
  35833. _this.invertRefractionY = false;
  35834. /**
  35835. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35836. * Materials half opaque for instance using refraction could benefit from this control.
  35837. */
  35838. _this.linkRefractionWithTransparency = false;
  35839. _this.useLightmapAsShadowmap = false;
  35840. /**
  35841. * Specifies that the alpha is coming form the albedo channel alpha channel.
  35842. */
  35843. _this.useAlphaFromAlbedoTexture = false;
  35844. /**
  35845. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35846. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35847. */
  35848. _this.useSpecularOverAlpha = true;
  35849. /**
  35850. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35851. */
  35852. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35853. /**
  35854. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35855. */
  35856. _this.useRoughnessFromMetallicTextureAlpha = true;
  35857. /**
  35858. * Specifies if the metallic texture contains the roughness information in its green channel.
  35859. */
  35860. _this.useRoughnessFromMetallicTextureGreen = false;
  35861. /**
  35862. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35863. */
  35864. _this.useMetallnessFromMetallicTextureBlue = false;
  35865. /**
  35866. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35867. */
  35868. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35869. /**
  35870. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35871. */
  35872. _this.useAmbientInGrayScale = false;
  35873. /**
  35874. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35875. * The material will try to infer what glossiness each pixel should be.
  35876. */
  35877. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35878. /**
  35879. * BJS is using an harcoded light falloff based on a manually sets up range.
  35880. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35881. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35882. */
  35883. _this.usePhysicalLightFalloff = true;
  35884. /**
  35885. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35886. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35887. */
  35888. _this.useRadianceOverAlpha = true;
  35889. /**
  35890. * Allows using the bump map in parallax mode.
  35891. */
  35892. _this.useParallax = false;
  35893. /**
  35894. * Allows using the bump map in parallax occlusion mode.
  35895. */
  35896. _this.useParallaxOcclusion = false;
  35897. /**
  35898. * Controls the scale bias of the parallax mode.
  35899. */
  35900. _this.parallaxScaleBias = 0.05;
  35901. /**
  35902. * If sets to true, disables all the lights affecting the material.
  35903. */
  35904. _this.disableLighting = false;
  35905. /**
  35906. * Number of Simultaneous lights allowed on the material.
  35907. */
  35908. _this.maxSimultaneousLights = 4;
  35909. /**
  35910. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35911. */
  35912. _this.invertNormalMapX = false;
  35913. /**
  35914. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35915. */
  35916. _this.invertNormalMapY = false;
  35917. /**
  35918. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35919. */
  35920. _this.twoSidedLighting = false;
  35921. /**
  35922. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  35923. * in your scene composition.
  35924. */
  35925. _this.premultiplyAlpha = false;
  35926. /**
  35927. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35928. * And/Or occlude the blended part.
  35929. */
  35930. _this.useAlphaFresnel = false;
  35931. return _this;
  35932. }
  35933. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35934. /**
  35935. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35936. */
  35937. get: function () {
  35938. return this._PBRMATERIAL_OPAQUE;
  35939. },
  35940. enumerable: true,
  35941. configurable: true
  35942. });
  35943. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35944. /**
  35945. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35946. */
  35947. get: function () {
  35948. return this._PBRMATERIAL_ALPHATEST;
  35949. },
  35950. enumerable: true,
  35951. configurable: true
  35952. });
  35953. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35954. /**
  35955. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35956. */
  35957. get: function () {
  35958. return this._PBRMATERIAL_ALPHABLEND;
  35959. },
  35960. enumerable: true,
  35961. configurable: true
  35962. });
  35963. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35964. /**
  35965. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35966. * They are also discarded below the alpha cutoff threshold to improve performances.
  35967. */
  35968. get: function () {
  35969. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35970. },
  35971. enumerable: true,
  35972. configurable: true
  35973. });
  35974. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  35975. /**
  35976. * Gets the image processing configuration used either in this material.
  35977. */
  35978. get: function () {
  35979. return this._imageProcessingConfiguration;
  35980. },
  35981. /**
  35982. * Sets the Default image processing configuration used either in the this material.
  35983. *
  35984. * If sets to null, the scene one is in use.
  35985. */
  35986. set: function (value) {
  35987. this._attachImageProcessingConfiguration(value);
  35988. // Ensure the effect will be rebuilt.
  35989. this._markAllSubMeshesAsTexturesDirty();
  35990. },
  35991. enumerable: true,
  35992. configurable: true
  35993. });
  35994. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  35995. /**
  35996. * Gets wether the color curves effect is enabled.
  35997. */
  35998. get: function () {
  35999. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36000. },
  36001. /**
  36002. * Sets wether the color curves effect is enabled.
  36003. */
  36004. set: function (value) {
  36005. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36006. },
  36007. enumerable: true,
  36008. configurable: true
  36009. });
  36010. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36011. /**
  36012. * Gets wether the color grading effect is enabled.
  36013. */
  36014. get: function () {
  36015. return this.imageProcessingConfiguration.colorGradingEnabled;
  36016. },
  36017. /**
  36018. * Gets wether the color grading effect is enabled.
  36019. */
  36020. set: function (value) {
  36021. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36022. },
  36023. enumerable: true,
  36024. configurable: true
  36025. });
  36026. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36027. /**
  36028. * Gets wether tonemapping is enabled or not.
  36029. */
  36030. get: function () {
  36031. return this._imageProcessingConfiguration.toneMappingEnabled;
  36032. },
  36033. /**
  36034. * Sets wether tonemapping is enabled or not
  36035. */
  36036. set: function (value) {
  36037. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36038. },
  36039. enumerable: true,
  36040. configurable: true
  36041. });
  36042. ;
  36043. ;
  36044. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36045. /**
  36046. * The camera exposure used on this material.
  36047. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36048. * This corresponds to a photographic exposure.
  36049. */
  36050. get: function () {
  36051. return this._imageProcessingConfiguration.exposure;
  36052. },
  36053. /**
  36054. * The camera exposure used on this material.
  36055. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36056. * This corresponds to a photographic exposure.
  36057. */
  36058. set: function (value) {
  36059. this._imageProcessingConfiguration.exposure = value;
  36060. },
  36061. enumerable: true,
  36062. configurable: true
  36063. });
  36064. ;
  36065. ;
  36066. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36067. /**
  36068. * Gets The camera contrast used on this material.
  36069. */
  36070. get: function () {
  36071. return this._imageProcessingConfiguration.contrast;
  36072. },
  36073. /**
  36074. * Sets The camera contrast used on this material.
  36075. */
  36076. set: function (value) {
  36077. this._imageProcessingConfiguration.contrast = value;
  36078. },
  36079. enumerable: true,
  36080. configurable: true
  36081. });
  36082. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36083. /**
  36084. * Gets the Color Grading 2D Lookup Texture.
  36085. */
  36086. get: function () {
  36087. return this._imageProcessingConfiguration.colorGradingTexture;
  36088. },
  36089. /**
  36090. * Sets the Color Grading 2D Lookup Texture.
  36091. */
  36092. set: function (value) {
  36093. this._imageProcessingConfiguration.colorGradingTexture = value;
  36094. },
  36095. enumerable: true,
  36096. configurable: true
  36097. });
  36098. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36099. /**
  36100. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36101. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36102. * 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;
  36103. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36104. */
  36105. get: function () {
  36106. return this._imageProcessingConfiguration.colorCurves;
  36107. },
  36108. /**
  36109. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36110. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36111. * 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;
  36112. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36113. */
  36114. set: function (value) {
  36115. this._imageProcessingConfiguration.colorCurves = value;
  36116. },
  36117. enumerable: true,
  36118. configurable: true
  36119. });
  36120. PBRMaterial.prototype.getClassName = function () {
  36121. return "PBRMaterial";
  36122. };
  36123. PBRMaterial.prototype.getActiveTextures = function () {
  36124. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36125. if (this._albedoTexture) {
  36126. activeTextures.push(this._albedoTexture);
  36127. }
  36128. if (this._ambientTexture) {
  36129. activeTextures.push(this._ambientTexture);
  36130. }
  36131. if (this._opacityTexture) {
  36132. activeTextures.push(this._opacityTexture);
  36133. }
  36134. if (this._reflectionTexture) {
  36135. activeTextures.push(this._reflectionTexture);
  36136. }
  36137. if (this._emissiveTexture) {
  36138. activeTextures.push(this._emissiveTexture);
  36139. }
  36140. if (this._reflectionTexture) {
  36141. activeTextures.push(this._reflectionTexture);
  36142. }
  36143. if (this._metallicTexture) {
  36144. activeTextures.push(this._metallicTexture);
  36145. }
  36146. if (this._microSurfaceTexture) {
  36147. activeTextures.push(this._microSurfaceTexture);
  36148. }
  36149. if (this._bumpTexture) {
  36150. activeTextures.push(this._bumpTexture);
  36151. }
  36152. if (this._lightmapTexture) {
  36153. activeTextures.push(this._lightmapTexture);
  36154. }
  36155. if (this._refractionTexture) {
  36156. activeTextures.push(this._refractionTexture);
  36157. }
  36158. return activeTextures;
  36159. };
  36160. PBRMaterial.prototype.clone = function (name) {
  36161. var _this = this;
  36162. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36163. };
  36164. PBRMaterial.prototype.serialize = function () {
  36165. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36166. serializationObject.customType = "BABYLON.PBRMaterial";
  36167. return serializationObject;
  36168. };
  36169. // Statics
  36170. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36171. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36172. };
  36173. return PBRMaterial;
  36174. }(BABYLON.PBRBaseMaterial));
  36175. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36176. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36177. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36178. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36179. __decorate([
  36180. BABYLON.serialize(),
  36181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36182. ], PBRMaterial.prototype, "directIntensity", void 0);
  36183. __decorate([
  36184. BABYLON.serialize(),
  36185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36186. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36187. __decorate([
  36188. BABYLON.serialize(),
  36189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36190. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36191. __decorate([
  36192. BABYLON.serialize(),
  36193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36194. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36195. __decorate([
  36196. BABYLON.serialize(),
  36197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36198. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36199. __decorate([
  36200. BABYLON.serializeAsTexture(),
  36201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36202. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36203. __decorate([
  36204. BABYLON.serializeAsTexture(),
  36205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36206. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36207. __decorate([
  36208. BABYLON.serialize(),
  36209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36210. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36211. __decorate([
  36212. BABYLON.serializeAsTexture(),
  36213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36214. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36215. __decorate([
  36216. BABYLON.serializeAsTexture(),
  36217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36218. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36219. __decorate([
  36220. BABYLON.serializeAsTexture(),
  36221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36222. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36223. __decorate([
  36224. BABYLON.serializeAsTexture(),
  36225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36226. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36227. __decorate([
  36228. BABYLON.serializeAsTexture(),
  36229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36230. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36231. __decorate([
  36232. BABYLON.serialize(),
  36233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36234. ], PBRMaterial.prototype, "metallic", void 0);
  36235. __decorate([
  36236. BABYLON.serialize(),
  36237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36238. ], PBRMaterial.prototype, "roughness", void 0);
  36239. __decorate([
  36240. BABYLON.serializeAsTexture(),
  36241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36242. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36243. __decorate([
  36244. BABYLON.serializeAsTexture(),
  36245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36246. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36247. __decorate([
  36248. BABYLON.serializeAsTexture(),
  36249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36250. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36251. __decorate([
  36252. BABYLON.serializeAsTexture(),
  36253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36254. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36255. __decorate([
  36256. BABYLON.serializeAsColor3("ambient"),
  36257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36258. ], PBRMaterial.prototype, "ambientColor", void 0);
  36259. __decorate([
  36260. BABYLON.serializeAsColor3("albedo"),
  36261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36262. ], PBRMaterial.prototype, "albedoColor", void 0);
  36263. __decorate([
  36264. BABYLON.serializeAsColor3("reflectivity"),
  36265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36266. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36267. __decorate([
  36268. BABYLON.serializeAsColor3("reflection"),
  36269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36270. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36271. __decorate([
  36272. BABYLON.serializeAsColor3("emissive"),
  36273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36274. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36275. __decorate([
  36276. BABYLON.serialize(),
  36277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36278. ], PBRMaterial.prototype, "microSurface", void 0);
  36279. __decorate([
  36280. BABYLON.serialize(),
  36281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36282. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36283. __decorate([
  36284. BABYLON.serialize(),
  36285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36286. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36287. __decorate([
  36288. BABYLON.serialize(),
  36289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36290. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36291. __decorate([
  36292. BABYLON.serialize(),
  36293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36294. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36295. __decorate([
  36296. BABYLON.serialize(),
  36297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36298. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36299. __decorate([
  36300. BABYLON.serialize(),
  36301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36302. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36303. __decorate([
  36304. BABYLON.serialize(),
  36305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36306. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36307. __decorate([
  36308. BABYLON.serialize(),
  36309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36310. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36311. __decorate([
  36312. BABYLON.serialize(),
  36313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36314. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36315. __decorate([
  36316. BABYLON.serialize(),
  36317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36318. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36319. __decorate([
  36320. BABYLON.serialize(),
  36321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36322. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36323. __decorate([
  36324. BABYLON.serialize(),
  36325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36326. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36327. __decorate([
  36328. BABYLON.serialize(),
  36329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36330. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36331. __decorate([
  36332. BABYLON.serialize(),
  36333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36334. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36335. __decorate([
  36336. BABYLON.serialize(),
  36337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36338. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36339. __decorate([
  36340. BABYLON.serialize(),
  36341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36342. ], PBRMaterial.prototype, "useParallax", void 0);
  36343. __decorate([
  36344. BABYLON.serialize(),
  36345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36346. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36347. __decorate([
  36348. BABYLON.serialize(),
  36349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36350. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36351. __decorate([
  36352. BABYLON.serialize(),
  36353. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36354. ], PBRMaterial.prototype, "disableLighting", void 0);
  36355. __decorate([
  36356. BABYLON.serialize(),
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36358. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36359. __decorate([
  36360. BABYLON.serialize(),
  36361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36362. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36363. __decorate([
  36364. BABYLON.serialize(),
  36365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36366. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36367. __decorate([
  36368. BABYLON.serialize(),
  36369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36370. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36371. __decorate([
  36372. BABYLON.serialize(),
  36373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36374. ], PBRMaterial.prototype, "premultiplyAlpha", void 0);
  36375. __decorate([
  36376. BABYLON.serialize(),
  36377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36378. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36379. BABYLON.PBRMaterial = PBRMaterial;
  36380. })(BABYLON || (BABYLON = {}));
  36381. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36382. var BABYLON;
  36383. (function (BABYLON) {
  36384. /**
  36385. * The PBR material of BJS following the metal roughness convention.
  36386. *
  36387. * This fits to the define PBR convention in the GLTF definition:
  36388. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36389. */
  36390. var PBRMetallicRoughnessMaterial = (function (_super) {
  36391. __extends(PBRMetallicRoughnessMaterial, _super);
  36392. /**
  36393. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36394. *
  36395. * @param name The material name
  36396. * @param scene The scene the material will be use in.
  36397. */
  36398. function PBRMetallicRoughnessMaterial(name, scene) {
  36399. var _this = _super.call(this, name, scene) || this;
  36400. _this._useRoughnessFromMetallicTextureGreen = true;
  36401. _this._useMetallnessFromMetallicTextureBlue = true;
  36402. return _this;
  36403. }
  36404. /**
  36405. * Return the currrent class name of the material.
  36406. */
  36407. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36408. return "PBRMetallicRoughnessMaterial";
  36409. };
  36410. /**
  36411. * Return the active textures of the material.
  36412. */
  36413. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36414. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36415. if (this.baseTexture) {
  36416. activeTextures.push(this.baseTexture);
  36417. }
  36418. if (this.metallicRoughnessTexture) {
  36419. activeTextures.push(this.metallicRoughnessTexture);
  36420. }
  36421. return activeTextures;
  36422. };
  36423. /**
  36424. * Serialize the material to a parsable JSON object.
  36425. */
  36426. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36427. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36428. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36429. return serializationObject;
  36430. };
  36431. /**
  36432. * Parses a JSON object correponding to the serialize function.
  36433. */
  36434. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36435. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36436. };
  36437. return PBRMetallicRoughnessMaterial;
  36438. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36439. __decorate([
  36440. BABYLON.serializeAsTexture(),
  36441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36442. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36443. __decorate([
  36444. BABYLON.serializeAsTexture(),
  36445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36446. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36447. __decorate([
  36448. BABYLON.serialize(),
  36449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36450. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36451. __decorate([
  36452. BABYLON.serialize(),
  36453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36454. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36455. __decorate([
  36456. BABYLON.serializeAsTexture(),
  36457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36458. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36459. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36460. })(BABYLON || (BABYLON = {}));
  36461. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36462. var BABYLON;
  36463. (function (BABYLON) {
  36464. /**
  36465. * The PBR material of BJS following the specular glossiness convention.
  36466. *
  36467. * This fits to the define PBR convention in the GLTF definition:
  36468. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36469. */
  36470. var PBRSpecularGlossinessMaterial = (function (_super) {
  36471. __extends(PBRSpecularGlossinessMaterial, _super);
  36472. /**
  36473. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36474. *
  36475. * @param name The material name
  36476. * @param scene The scene the material will be use in.
  36477. */
  36478. function PBRSpecularGlossinessMaterial(name, scene) {
  36479. var _this = _super.call(this, name, scene) || this;
  36480. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36481. return _this;
  36482. }
  36483. /**
  36484. * Return the currrent class name of the material.
  36485. */
  36486. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36487. return "PBRSpecularGlossinessMaterial";
  36488. };
  36489. /**
  36490. * Return the active textures of the material.
  36491. */
  36492. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36493. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36494. if (this.diffuseTexture) {
  36495. activeTextures.push(this.diffuseTexture);
  36496. }
  36497. if (this.specularGlossinessTexture) {
  36498. activeTextures.push(this.specularGlossinessTexture);
  36499. }
  36500. return activeTextures;
  36501. };
  36502. /**
  36503. * Serialize the material to a parsable JSON object.
  36504. */
  36505. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36506. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36507. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36508. return serializationObject;
  36509. };
  36510. /**
  36511. * Parses a JSON object correponding to the serialize function.
  36512. */
  36513. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36514. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36515. };
  36516. return PBRSpecularGlossinessMaterial;
  36517. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36518. __decorate([
  36519. BABYLON.serializeAsColor3(),
  36520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36521. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36522. __decorate([
  36523. BABYLON.serializeAsTexture(),
  36524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36525. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36526. __decorate([
  36527. BABYLON.serializeAsColor3(),
  36528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36529. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36530. __decorate([
  36531. BABYLON.serialize(),
  36532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36533. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36534. __decorate([
  36535. BABYLON.serializeAsTexture(),
  36536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36537. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36538. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36539. })(BABYLON || (BABYLON = {}));
  36540. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36541. var BABYLON;
  36542. (function (BABYLON) {
  36543. var ShaderMaterial = (function (_super) {
  36544. __extends(ShaderMaterial, _super);
  36545. function ShaderMaterial(name, scene, shaderPath, options) {
  36546. var _this = _super.call(this, name, scene) || this;
  36547. _this._textures = {};
  36548. _this._textureArrays = {};
  36549. _this._floats = {};
  36550. _this._floatsArrays = {};
  36551. _this._colors3 = {};
  36552. _this._colors4 = {};
  36553. _this._vectors2 = {};
  36554. _this._vectors3 = {};
  36555. _this._vectors4 = {};
  36556. _this._matrices = {};
  36557. _this._matrices3x3 = {};
  36558. _this._matrices2x2 = {};
  36559. _this._vectors3Arrays = {};
  36560. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  36561. _this._shaderPath = shaderPath;
  36562. options.needAlphaBlending = options.needAlphaBlending || false;
  36563. options.needAlphaTesting = options.needAlphaTesting || false;
  36564. options.attributes = options.attributes || ["position", "normal", "uv"];
  36565. options.uniforms = options.uniforms || ["worldViewProjection"];
  36566. options.uniformBuffers = options.uniformBuffers || [];
  36567. options.samplers = options.samplers || [];
  36568. options.defines = options.defines || [];
  36569. _this._options = options;
  36570. return _this;
  36571. }
  36572. ShaderMaterial.prototype.getClassName = function () {
  36573. return "ShaderMaterial";
  36574. };
  36575. ShaderMaterial.prototype.needAlphaBlending = function () {
  36576. return this._options.needAlphaBlending;
  36577. };
  36578. ShaderMaterial.prototype.needAlphaTesting = function () {
  36579. return this._options.needAlphaTesting;
  36580. };
  36581. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  36582. if (this._options.uniforms.indexOf(uniformName) === -1) {
  36583. this._options.uniforms.push(uniformName);
  36584. }
  36585. };
  36586. ShaderMaterial.prototype.setTexture = function (name, texture) {
  36587. if (this._options.samplers.indexOf(name) === -1) {
  36588. this._options.samplers.push(name);
  36589. }
  36590. this._textures[name] = texture;
  36591. return this;
  36592. };
  36593. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  36594. if (this._options.samplers.indexOf(name) === -1) {
  36595. this._options.samplers.push(name);
  36596. }
  36597. this._checkUniform(name);
  36598. this._textureArrays[name] = textures;
  36599. return this;
  36600. };
  36601. ShaderMaterial.prototype.setFloat = function (name, value) {
  36602. this._checkUniform(name);
  36603. this._floats[name] = value;
  36604. return this;
  36605. };
  36606. ShaderMaterial.prototype.setFloats = function (name, value) {
  36607. this._checkUniform(name);
  36608. this._floatsArrays[name] = value;
  36609. return this;
  36610. };
  36611. ShaderMaterial.prototype.setColor3 = function (name, value) {
  36612. this._checkUniform(name);
  36613. this._colors3[name] = value;
  36614. return this;
  36615. };
  36616. ShaderMaterial.prototype.setColor4 = function (name, value) {
  36617. this._checkUniform(name);
  36618. this._colors4[name] = value;
  36619. return this;
  36620. };
  36621. ShaderMaterial.prototype.setVector2 = function (name, value) {
  36622. this._checkUniform(name);
  36623. this._vectors2[name] = value;
  36624. return this;
  36625. };
  36626. ShaderMaterial.prototype.setVector3 = function (name, value) {
  36627. this._checkUniform(name);
  36628. this._vectors3[name] = value;
  36629. return this;
  36630. };
  36631. ShaderMaterial.prototype.setVector4 = function (name, value) {
  36632. this._checkUniform(name);
  36633. this._vectors4[name] = value;
  36634. return this;
  36635. };
  36636. ShaderMaterial.prototype.setMatrix = function (name, value) {
  36637. this._checkUniform(name);
  36638. this._matrices[name] = value;
  36639. return this;
  36640. };
  36641. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  36642. this._checkUniform(name);
  36643. this._matrices3x3[name] = value;
  36644. return this;
  36645. };
  36646. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  36647. this._checkUniform(name);
  36648. this._matrices2x2[name] = value;
  36649. return this;
  36650. };
  36651. ShaderMaterial.prototype.setArray3 = function (name, value) {
  36652. this._checkUniform(name);
  36653. this._vectors3Arrays[name] = value;
  36654. return this;
  36655. };
  36656. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  36657. if (!mesh) {
  36658. return true;
  36659. }
  36660. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  36661. return false;
  36662. }
  36663. return false;
  36664. };
  36665. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  36666. var scene = this.getScene();
  36667. var engine = scene.getEngine();
  36668. if (!this.checkReadyOnEveryCall) {
  36669. if (this._renderId === scene.getRenderId()) {
  36670. if (this._checkCache(scene, mesh, useInstances)) {
  36671. return true;
  36672. }
  36673. }
  36674. }
  36675. // Instances
  36676. var defines = [];
  36677. var attribs = [];
  36678. var fallbacks = new BABYLON.EffectFallbacks();
  36679. if (useInstances) {
  36680. defines.push("#define INSTANCES");
  36681. }
  36682. for (var index = 0; index < this._options.defines.length; index++) {
  36683. defines.push(this._options.defines[index]);
  36684. }
  36685. for (var index = 0; index < this._options.attributes.length; index++) {
  36686. attribs.push(this._options.attributes[index]);
  36687. }
  36688. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36689. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36690. defines.push("#define VERTEXCOLOR");
  36691. }
  36692. // Bones
  36693. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  36694. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36695. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36696. if (mesh.numBoneInfluencers > 4) {
  36697. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36698. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36699. }
  36700. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36701. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36702. fallbacks.addCPUSkinningFallback(0, mesh);
  36703. if (this._options.uniforms.indexOf("mBones") === -1) {
  36704. this._options.uniforms.push("mBones");
  36705. }
  36706. }
  36707. else {
  36708. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36709. }
  36710. // Textures
  36711. for (var name in this._textures) {
  36712. if (!this._textures[name].isReady()) {
  36713. return false;
  36714. }
  36715. }
  36716. // Alpha test
  36717. if (engine.getAlphaTesting()) {
  36718. defines.push("#define ALPHATEST");
  36719. }
  36720. var previousEffect = this._effect;
  36721. var join = defines.join("\n");
  36722. this._effect = engine.createEffect(this._shaderPath, {
  36723. attributes: attribs,
  36724. uniformsNames: this._options.uniforms,
  36725. uniformBuffersNames: this._options.uniformBuffers,
  36726. samplers: this._options.samplers,
  36727. defines: join,
  36728. fallbacks: fallbacks,
  36729. onCompiled: this.onCompiled,
  36730. onError: this.onError
  36731. }, engine);
  36732. if (!this._effect.isReady()) {
  36733. return false;
  36734. }
  36735. if (previousEffect !== this._effect) {
  36736. scene.resetCachedMaterial();
  36737. }
  36738. this._renderId = scene.getRenderId();
  36739. return true;
  36740. };
  36741. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36742. var scene = this.getScene();
  36743. if (this._options.uniforms.indexOf("world") !== -1) {
  36744. this._effect.setMatrix("world", world);
  36745. }
  36746. if (this._options.uniforms.indexOf("worldView") !== -1) {
  36747. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  36748. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  36749. }
  36750. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  36751. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  36752. }
  36753. };
  36754. ShaderMaterial.prototype.bind = function (world, mesh) {
  36755. // Std values
  36756. this.bindOnlyWorldMatrix(world);
  36757. if (this.getScene().getCachedMaterial() !== this) {
  36758. if (this._options.uniforms.indexOf("view") !== -1) {
  36759. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  36760. }
  36761. if (this._options.uniforms.indexOf("projection") !== -1) {
  36762. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  36763. }
  36764. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  36765. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36766. }
  36767. // Bones
  36768. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  36769. var name;
  36770. // Texture
  36771. for (name in this._textures) {
  36772. this._effect.setTexture(name, this._textures[name]);
  36773. }
  36774. // Texture arrays
  36775. for (name in this._textureArrays) {
  36776. this._effect.setTextureArray(name, this._textureArrays[name]);
  36777. }
  36778. // Float
  36779. for (name in this._floats) {
  36780. this._effect.setFloat(name, this._floats[name]);
  36781. }
  36782. // Float s
  36783. for (name in this._floatsArrays) {
  36784. this._effect.setArray(name, this._floatsArrays[name]);
  36785. }
  36786. // Color3
  36787. for (name in this._colors3) {
  36788. this._effect.setColor3(name, this._colors3[name]);
  36789. }
  36790. // Color4
  36791. for (name in this._colors4) {
  36792. var color = this._colors4[name];
  36793. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  36794. }
  36795. // Vector2
  36796. for (name in this._vectors2) {
  36797. this._effect.setVector2(name, this._vectors2[name]);
  36798. }
  36799. // Vector3
  36800. for (name in this._vectors3) {
  36801. this._effect.setVector3(name, this._vectors3[name]);
  36802. }
  36803. // Vector4
  36804. for (name in this._vectors4) {
  36805. this._effect.setVector4(name, this._vectors4[name]);
  36806. }
  36807. // Matrix
  36808. for (name in this._matrices) {
  36809. this._effect.setMatrix(name, this._matrices[name]);
  36810. }
  36811. // Matrix 3x3
  36812. for (name in this._matrices3x3) {
  36813. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  36814. }
  36815. // Matrix 2x2
  36816. for (name in this._matrices2x2) {
  36817. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  36818. }
  36819. // Vector3Array
  36820. for (name in this._vectors3Arrays) {
  36821. this._effect.setArray3(name, this._vectors3Arrays[name]);
  36822. }
  36823. }
  36824. this._afterBind(mesh);
  36825. };
  36826. ShaderMaterial.prototype.getActiveTextures = function () {
  36827. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36828. for (var name in this._textures) {
  36829. activeTextures.push(this._textures[name]);
  36830. }
  36831. for (var name in this._textureArrays) {
  36832. var array = this._textureArrays[name];
  36833. for (var index = 0; index < array.length; index++) {
  36834. activeTextures.push(array[index]);
  36835. }
  36836. }
  36837. return activeTextures;
  36838. };
  36839. ShaderMaterial.prototype.clone = function (name) {
  36840. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  36841. return newShaderMaterial;
  36842. };
  36843. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36844. if (forceDisposeTextures) {
  36845. var name;
  36846. for (name in this._textures) {
  36847. this._textures[name].dispose();
  36848. }
  36849. for (name in this._textureArrays) {
  36850. var array = this._textureArrays[name];
  36851. for (var index = 0; index < array.length; index++) {
  36852. array[index].dispose();
  36853. }
  36854. }
  36855. }
  36856. this._textures = {};
  36857. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36858. };
  36859. ShaderMaterial.prototype.serialize = function () {
  36860. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36861. serializationObject.customType = "BABYLON.ShaderMaterial";
  36862. serializationObject.options = this._options;
  36863. serializationObject.shaderPath = this._shaderPath;
  36864. var name;
  36865. // Texture
  36866. serializationObject.textures = {};
  36867. for (name in this._textures) {
  36868. serializationObject.textures[name] = this._textures[name].serialize();
  36869. }
  36870. // Texture arrays
  36871. serializationObject.textureArrays = {};
  36872. for (name in this._textureArrays) {
  36873. serializationObject.textureArrays[name] = [];
  36874. var array = this._textureArrays[name];
  36875. for (var index = 0; index < array.length; index++) {
  36876. serializationObject.textureArrays[name].push(array[index].serialize());
  36877. }
  36878. }
  36879. // Float
  36880. serializationObject.floats = {};
  36881. for (name in this._floats) {
  36882. serializationObject.floats[name] = this._floats[name];
  36883. }
  36884. // Float s
  36885. serializationObject.floatArrays = {};
  36886. for (name in this._floatsArrays) {
  36887. serializationObject.floatArrays[name] = this._floatsArrays[name];
  36888. }
  36889. // Color3
  36890. serializationObject.colors3 = {};
  36891. for (name in this._colors3) {
  36892. serializationObject.colors3[name] = this._colors3[name].asArray();
  36893. }
  36894. // Color4
  36895. serializationObject.colors4 = {};
  36896. for (name in this._colors4) {
  36897. serializationObject.colors4[name] = this._colors4[name].asArray();
  36898. }
  36899. // Vector2
  36900. serializationObject.vectors2 = {};
  36901. for (name in this._vectors2) {
  36902. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  36903. }
  36904. // Vector3
  36905. serializationObject.vectors3 = {};
  36906. for (name in this._vectors3) {
  36907. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  36908. }
  36909. // Vector4
  36910. serializationObject.vectors4 = {};
  36911. for (name in this._vectors4) {
  36912. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  36913. }
  36914. // Matrix
  36915. serializationObject.matrices = {};
  36916. for (name in this._matrices) {
  36917. serializationObject.matrices[name] = this._matrices[name].asArray();
  36918. }
  36919. // Matrix 3x3
  36920. serializationObject.matrices3x3 = {};
  36921. for (name in this._matrices3x3) {
  36922. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  36923. }
  36924. // Matrix 2x2
  36925. serializationObject.matrices2x2 = {};
  36926. for (name in this._matrices2x2) {
  36927. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  36928. }
  36929. // Vector3Array
  36930. serializationObject.vectors3Arrays = {};
  36931. for (name in this._vectors3Arrays) {
  36932. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  36933. }
  36934. return serializationObject;
  36935. };
  36936. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  36937. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  36938. var name;
  36939. // Texture
  36940. for (name in source.textures) {
  36941. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  36942. }
  36943. // Texture arrays
  36944. for (name in source.textureArrays) {
  36945. var array = source.textureArrays[name];
  36946. var textureArray = new Array();
  36947. for (var index = 0; index < array.length; index++) {
  36948. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  36949. }
  36950. material.setTextureArray(name, textureArray);
  36951. }
  36952. // Float
  36953. for (name in source.floats) {
  36954. material.setFloat(name, source.floats[name]);
  36955. }
  36956. // Float s
  36957. for (name in source.floatsArrays) {
  36958. material.setFloats(name, source.floatsArrays[name]);
  36959. }
  36960. // Color3
  36961. for (name in source.colors3) {
  36962. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  36963. }
  36964. // Color4
  36965. for (name in source.colors4) {
  36966. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  36967. }
  36968. // Vector2
  36969. for (name in source.vectors2) {
  36970. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  36971. }
  36972. // Vector3
  36973. for (name in source.vectors3) {
  36974. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  36975. }
  36976. // Vector4
  36977. for (name in source.vectors4) {
  36978. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  36979. }
  36980. // Matrix
  36981. for (name in source.matrices) {
  36982. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  36983. }
  36984. // Matrix 3x3
  36985. for (name in source.matrices3x3) {
  36986. material.setMatrix3x3(name, source.matrices3x3[name]);
  36987. }
  36988. // Matrix 2x2
  36989. for (name in source.matrices2x2) {
  36990. material.setMatrix2x2(name, source.matrices2x2[name]);
  36991. }
  36992. // Vector3Array
  36993. for (name in source.vectors3Arrays) {
  36994. material.setArray3(name, source.vectors3Arrays[name]);
  36995. }
  36996. return material;
  36997. };
  36998. return ShaderMaterial;
  36999. }(BABYLON.Material));
  37000. BABYLON.ShaderMaterial = ShaderMaterial;
  37001. })(BABYLON || (BABYLON = {}));
  37002. //# sourceMappingURL=babylon.shaderMaterial.js.map
  37003. var BABYLON;
  37004. (function (BABYLON) {
  37005. var MeshBuilder = (function () {
  37006. function MeshBuilder() {
  37007. }
  37008. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  37009. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  37010. return BABYLON.Mesh.DOUBLESIDE;
  37011. }
  37012. if (orientation === undefined || orientation === null) {
  37013. return BABYLON.Mesh.FRONTSIDE;
  37014. }
  37015. return orientation;
  37016. };
  37017. /**
  37018. * Creates a box mesh.
  37019. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  37020. * The parameter `size` sets the size (float) of each box side (default 1).
  37021. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  37022. * 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).
  37023. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37025. * 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).
  37026. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37028. */
  37029. MeshBuilder.CreateBox = function (name, options, scene) {
  37030. var box = new BABYLON.Mesh(name, scene);
  37031. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37032. box.sideOrientation = options.sideOrientation;
  37033. var vertexData = BABYLON.VertexData.CreateBox(options);
  37034. vertexData.applyToMesh(box, options.updatable);
  37035. return box;
  37036. };
  37037. /**
  37038. * Creates a sphere mesh.
  37039. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  37040. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  37041. * 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`).
  37042. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  37043. * 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
  37044. * 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).
  37045. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37046. * 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).
  37047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37049. */
  37050. MeshBuilder.CreateSphere = function (name, options, scene) {
  37051. var sphere = new BABYLON.Mesh(name, scene);
  37052. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37053. sphere.sideOrientation = options.sideOrientation;
  37054. var vertexData = BABYLON.VertexData.CreateSphere(options);
  37055. vertexData.applyToMesh(sphere, options.updatable);
  37056. return sphere;
  37057. };
  37058. /**
  37059. * Creates a plane polygonal mesh. By default, this is a disc.
  37060. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  37061. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  37062. * 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.
  37063. * 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
  37064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37065. * 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).
  37066. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37067. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37068. */
  37069. MeshBuilder.CreateDisc = function (name, options, scene) {
  37070. var disc = new BABYLON.Mesh(name, scene);
  37071. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37072. disc.sideOrientation = options.sideOrientation;
  37073. var vertexData = BABYLON.VertexData.CreateDisc(options);
  37074. vertexData.applyToMesh(disc, options.updatable);
  37075. return disc;
  37076. };
  37077. /**
  37078. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  37079. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  37080. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  37081. * 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`).
  37082. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  37083. * 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.
  37084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37085. * 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).
  37086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37088. */
  37089. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  37090. var sphere = new BABYLON.Mesh(name, scene);
  37091. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37092. sphere.sideOrientation = options.sideOrientation;
  37093. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  37094. vertexData.applyToMesh(sphere, options.updatable);
  37095. return sphere;
  37096. };
  37097. ;
  37098. /**
  37099. * Creates a ribbon mesh.
  37100. * 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.
  37101. *
  37102. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  37103. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  37104. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  37105. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  37106. * 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.
  37107. * 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.
  37108. * 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
  37109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37110. * 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).
  37111. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37112. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37113. * 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.
  37114. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  37115. * 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
  37116. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  37117. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  37118. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37119. */
  37120. MeshBuilder.CreateRibbon = function (name, options, scene) {
  37121. var pathArray = options.pathArray;
  37122. var closeArray = options.closeArray;
  37123. var closePath = options.closePath;
  37124. var offset = options.offset;
  37125. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37126. var instance = options.instance;
  37127. var updatable = options.updatable;
  37128. if (instance) {
  37129. // positionFunction : ribbon case
  37130. // only pathArray and sideOrientation parameters are taken into account for positions update
  37131. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  37132. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  37133. var positionFunction = function (positions) {
  37134. var minlg = pathArray[0].length;
  37135. var i = 0;
  37136. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  37137. for (var si = 1; si <= ns; si++) {
  37138. for (var p = 0; p < pathArray.length; p++) {
  37139. var path = pathArray[p];
  37140. var l = path.length;
  37141. minlg = (minlg < l) ? minlg : l;
  37142. var j = 0;
  37143. while (j < minlg) {
  37144. positions[i] = path[j].x;
  37145. positions[i + 1] = path[j].y;
  37146. positions[i + 2] = path[j].z;
  37147. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  37148. BABYLON.Tmp.Vector3[0].x = path[j].x;
  37149. }
  37150. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  37151. BABYLON.Tmp.Vector3[1].x = path[j].x;
  37152. }
  37153. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  37154. BABYLON.Tmp.Vector3[0].y = path[j].y;
  37155. }
  37156. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  37157. BABYLON.Tmp.Vector3[1].y = path[j].y;
  37158. }
  37159. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  37160. BABYLON.Tmp.Vector3[0].z = path[j].z;
  37161. }
  37162. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  37163. BABYLON.Tmp.Vector3[1].z = path[j].z;
  37164. }
  37165. j++;
  37166. i += 3;
  37167. }
  37168. if (instance._closePath) {
  37169. positions[i] = path[0].x;
  37170. positions[i + 1] = path[0].y;
  37171. positions[i + 2] = path[0].z;
  37172. i += 3;
  37173. }
  37174. }
  37175. }
  37176. };
  37177. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37178. positionFunction(positions);
  37179. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  37180. instance._boundingInfo.update(instance._worldMatrix);
  37181. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  37182. if (options.colors) {
  37183. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37184. for (var c = 0; c < options.colors.length; c++) {
  37185. colors[c * 4] = options.colors[c].r;
  37186. colors[c * 4 + 1] = options.colors[c].g;
  37187. colors[c * 4 + 2] = options.colors[c].b;
  37188. colors[c * 4 + 3] = options.colors[c].a;
  37189. }
  37190. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  37191. }
  37192. if (options.uvs) {
  37193. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37194. for (var i = 0; i < options.uvs.length; i++) {
  37195. uvs[i * 2] = options.uvs[i].x;
  37196. uvs[i * 2 + 1] = options.uvs[i].y;
  37197. }
  37198. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  37199. }
  37200. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  37201. var indices = instance.getIndices();
  37202. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37203. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  37204. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  37205. if (instance._closePath) {
  37206. var indexFirst = 0;
  37207. var indexLast = 0;
  37208. for (var p = 0; p < pathArray.length; p++) {
  37209. indexFirst = instance._idx[p] * 3;
  37210. if (p + 1 < pathArray.length) {
  37211. indexLast = (instance._idx[p + 1] - 1) * 3;
  37212. }
  37213. else {
  37214. indexLast = normals.length - 3;
  37215. }
  37216. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37217. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37218. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37219. normals[indexLast] = normals[indexFirst];
  37220. normals[indexLast + 1] = normals[indexFirst + 1];
  37221. normals[indexLast + 2] = normals[indexFirst + 2];
  37222. }
  37223. }
  37224. if (!(instance.areNormalsFrozen)) {
  37225. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  37226. }
  37227. }
  37228. return instance;
  37229. }
  37230. else {
  37231. var ribbon = new BABYLON.Mesh(name, scene);
  37232. ribbon.sideOrientation = sideOrientation;
  37233. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  37234. if (closePath) {
  37235. ribbon._idx = vertexData._idx;
  37236. }
  37237. ribbon._closePath = closePath;
  37238. ribbon._closeArray = closeArray;
  37239. vertexData.applyToMesh(ribbon, updatable);
  37240. return ribbon;
  37241. }
  37242. };
  37243. /**
  37244. * Creates a cylinder or a cone mesh.
  37245. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  37246. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  37247. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  37248. * 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.
  37249. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  37250. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  37251. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  37252. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  37253. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  37254. * 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).
  37255. * 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
  37256. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  37257. * 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
  37258. * 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.
  37259. * If `enclose` is false, a ring surface is one element.
  37260. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  37261. * 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
  37262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37263. * 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).
  37264. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37266. */
  37267. MeshBuilder.CreateCylinder = function (name, options, scene) {
  37268. var cylinder = new BABYLON.Mesh(name, scene);
  37269. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37270. cylinder.sideOrientation = options.sideOrientation;
  37271. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  37272. vertexData.applyToMesh(cylinder, options.updatable);
  37273. return cylinder;
  37274. };
  37275. /**
  37276. * Creates a torus mesh.
  37277. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  37278. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  37279. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  37280. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  37281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37282. * 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).
  37283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37285. */
  37286. MeshBuilder.CreateTorus = function (name, options, scene) {
  37287. var torus = new BABYLON.Mesh(name, scene);
  37288. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37289. torus.sideOrientation = options.sideOrientation;
  37290. var vertexData = BABYLON.VertexData.CreateTorus(options);
  37291. vertexData.applyToMesh(torus, options.updatable);
  37292. return torus;
  37293. };
  37294. /**
  37295. * Creates a torus knot mesh.
  37296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  37297. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  37298. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  37299. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  37300. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  37301. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37302. * 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).
  37303. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37305. */
  37306. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  37307. var torusKnot = new BABYLON.Mesh(name, scene);
  37308. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37309. torusKnot.sideOrientation = options.sideOrientation;
  37310. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  37311. vertexData.applyToMesh(torusKnot, options.updatable);
  37312. return torusKnot;
  37313. };
  37314. /**
  37315. * Creates a line system mesh.
  37316. * A line system is a pool of many lines gathered in a single mesh.
  37317. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  37318. * 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.
  37319. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  37320. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  37321. * 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
  37322. * 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
  37323. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  37324. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37325. */
  37326. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  37327. var instance = options.instance;
  37328. var lines = options.lines;
  37329. if (instance) {
  37330. var positionFunction = function (positions) {
  37331. var i = 0;
  37332. for (var l = 0; l < lines.length; l++) {
  37333. var points = lines[l];
  37334. for (var p = 0; p < points.length; p++) {
  37335. positions[i] = points[p].x;
  37336. positions[i + 1] = points[p].y;
  37337. positions[i + 2] = points[p].z;
  37338. i += 3;
  37339. }
  37340. }
  37341. };
  37342. instance.updateMeshPositions(positionFunction, false);
  37343. return instance;
  37344. }
  37345. // line system creation
  37346. var lineSystem = new BABYLON.LinesMesh(name, scene);
  37347. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  37348. vertexData.applyToMesh(lineSystem, options.updatable);
  37349. return lineSystem;
  37350. };
  37351. /**
  37352. * Creates a line mesh.
  37353. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  37354. * 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.
  37355. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37356. * The parameter `points` is an array successive Vector3.
  37357. * 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
  37358. * When updating an instance, remember that only point positions can change, not the number of points.
  37359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37360. */
  37361. MeshBuilder.CreateLines = function (name, options, scene) {
  37362. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  37363. return lines;
  37364. };
  37365. /**
  37366. * Creates a dashed line mesh.
  37367. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  37368. * 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.
  37369. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  37370. * The parameter `points` is an array successive Vector3.
  37371. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  37372. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  37373. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  37374. * 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
  37375. * When updating an instance, remember that only point positions can change, not the number of points.
  37376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37377. */
  37378. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  37379. var points = options.points;
  37380. var instance = options.instance;
  37381. var gapSize = options.gapSize;
  37382. var dashNb = options.dashNb;
  37383. var dashSize = options.dashSize;
  37384. if (instance) {
  37385. var positionFunction = function (positions) {
  37386. var curvect = BABYLON.Vector3.Zero();
  37387. var nbSeg = positions.length / 6;
  37388. var lg = 0;
  37389. var nb = 0;
  37390. var shft = 0;
  37391. var dashshft = 0;
  37392. var curshft = 0;
  37393. var p = 0;
  37394. var i = 0;
  37395. var j = 0;
  37396. for (i = 0; i < points.length - 1; i++) {
  37397. points[i + 1].subtractToRef(points[i], curvect);
  37398. lg += curvect.length();
  37399. }
  37400. shft = lg / nbSeg;
  37401. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  37402. for (i = 0; i < points.length - 1; i++) {
  37403. points[i + 1].subtractToRef(points[i], curvect);
  37404. nb = Math.floor(curvect.length() / shft);
  37405. curvect.normalize();
  37406. j = 0;
  37407. while (j < nb && p < positions.length) {
  37408. curshft = shft * j;
  37409. positions[p] = points[i].x + curshft * curvect.x;
  37410. positions[p + 1] = points[i].y + curshft * curvect.y;
  37411. positions[p + 2] = points[i].z + curshft * curvect.z;
  37412. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  37413. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  37414. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  37415. p += 6;
  37416. j++;
  37417. }
  37418. }
  37419. while (p < positions.length) {
  37420. positions[p] = points[i].x;
  37421. positions[p + 1] = points[i].y;
  37422. positions[p + 2] = points[i].z;
  37423. p += 3;
  37424. }
  37425. };
  37426. instance.updateMeshPositions(positionFunction, false);
  37427. return instance;
  37428. }
  37429. // dashed lines creation
  37430. var dashedLines = new BABYLON.LinesMesh(name, scene);
  37431. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  37432. vertexData.applyToMesh(dashedLines, options.updatable);
  37433. dashedLines.dashSize = dashSize;
  37434. dashedLines.gapSize = gapSize;
  37435. return dashedLines;
  37436. };
  37437. /**
  37438. * Creates an extruded shape mesh.
  37439. * 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.
  37440. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  37441. *
  37442. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37443. * 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
  37444. * extruded along the Z axis.
  37445. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37446. * 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.
  37447. * The parameter `scale` (float, default 1) is the value to scale the shape.
  37448. * 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
  37449. * 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
  37450. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37451. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37452. * 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).
  37453. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37454. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37455. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37456. */
  37457. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  37458. var path = options.path;
  37459. var shape = options.shape;
  37460. var scale = options.scale || 1;
  37461. var rotation = options.rotation || 0;
  37462. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37463. var updatable = options.updatable;
  37464. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37465. var instance = options.instance;
  37466. var invertUV = options.invertUV || false;
  37467. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37468. };
  37469. /**
  37470. * Creates an custom extruded shape mesh.
  37471. * 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.
  37472. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  37473. *
  37474. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37475. * 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
  37476. * extruded along the Z axis.
  37477. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37478. * 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
  37479. * and the distance of this point from the begining of the path :
  37480. * ```javascript
  37481. * var rotationFunction = function(i, distance) {
  37482. * // do things
  37483. * return rotationValue; }
  37484. * ```
  37485. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  37486. * 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
  37487. * and the distance of this point from the begining of the path :
  37488. * ```javascript
  37489. * var scaleFunction = function(i, distance) {
  37490. * // do things
  37491. * return scaleValue;}
  37492. * ```
  37493. * It must returns a float value that will be the scale value applied to the shape on each path point.
  37494. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  37495. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  37496. * 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
  37497. * 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
  37498. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37500. * 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).
  37501. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37502. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37503. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37504. */
  37505. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  37506. var path = options.path;
  37507. var shape = options.shape;
  37508. var scaleFunction = options.scaleFunction || (function () { return 1; });
  37509. var rotationFunction = options.rotationFunction || (function () { return 0; });
  37510. var ribbonCloseArray = options.ribbonCloseArray || false;
  37511. var ribbonClosePath = options.ribbonClosePath || false;
  37512. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37513. var updatable = options.updatable;
  37514. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37515. var instance = options.instance;
  37516. var invertUV = options.invertUV || false;
  37517. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37518. };
  37519. /**
  37520. * Creates lathe mesh.
  37521. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  37522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  37523. *
  37524. * 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
  37525. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  37526. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  37527. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  37528. * 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.
  37529. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  37530. * 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
  37531. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37532. * 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).
  37533. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37534. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37536. */
  37537. MeshBuilder.CreateLathe = function (name, options, scene) {
  37538. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  37539. var closed = (options.closed === undefined) ? true : options.closed;
  37540. var shape = options.shape;
  37541. var radius = options.radius || 1;
  37542. var tessellation = options.tessellation || 64;
  37543. var updatable = options.updatable;
  37544. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37545. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37546. var pi2 = Math.PI * 2;
  37547. var paths = new Array();
  37548. var invertUV = options.invertUV || false;
  37549. var i = 0;
  37550. var p = 0;
  37551. var step = pi2 / tessellation * arc;
  37552. var rotated;
  37553. var path = new Array();
  37554. ;
  37555. for (i = 0; i <= tessellation; i++) {
  37556. var path = [];
  37557. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  37558. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  37559. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  37560. }
  37561. for (p = 0; p < shape.length; p++) {
  37562. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  37563. path.push(rotated);
  37564. }
  37565. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  37566. 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));
  37567. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  37568. }
  37569. paths.push(path);
  37570. }
  37571. // lathe ribbon
  37572. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37573. return lathe;
  37574. };
  37575. /**
  37576. * Creates a plane mesh.
  37577. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37578. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  37579. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  37580. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  37581. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37582. * 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).
  37583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37585. */
  37586. MeshBuilder.CreatePlane = function (name, options, scene) {
  37587. var plane = new BABYLON.Mesh(name, scene);
  37588. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37589. plane.sideOrientation = options.sideOrientation;
  37590. var vertexData = BABYLON.VertexData.CreatePlane(options);
  37591. vertexData.applyToMesh(plane, options.updatable);
  37592. if (options.sourcePlane) {
  37593. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  37594. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  37595. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  37596. plane.rotate(vectorProduct, product);
  37597. }
  37598. return plane;
  37599. };
  37600. /**
  37601. * Creates a ground mesh.
  37602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37603. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  37604. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  37605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37606. */
  37607. MeshBuilder.CreateGround = function (name, options, scene) {
  37608. var ground = new BABYLON.GroundMesh(name, scene);
  37609. ground._setReady(false);
  37610. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37611. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37612. ground._width = options.width || 1;
  37613. ground._height = options.height || 1;
  37614. ground._maxX = ground._width / 2;
  37615. ground._maxZ = ground._height / 2;
  37616. ground._minX = -ground._maxX;
  37617. ground._minZ = -ground._maxZ;
  37618. var vertexData = BABYLON.VertexData.CreateGround(options);
  37619. vertexData.applyToMesh(ground, options.updatable);
  37620. ground._setReady(true);
  37621. return ground;
  37622. };
  37623. /**
  37624. * Creates a tiled ground mesh.
  37625. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  37626. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  37627. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  37628. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  37629. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  37630. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  37631. * numbers of subdivisions on the ground width and height of each tile.
  37632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37633. */
  37634. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  37635. var tiledGround = new BABYLON.Mesh(name, scene);
  37636. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  37637. vertexData.applyToMesh(tiledGround, options.updatable);
  37638. return tiledGround;
  37639. };
  37640. /**
  37641. * Creates a ground mesh from a height map.
  37642. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  37643. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  37644. * The parameter `url` sets the URL of the height map image resource.
  37645. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  37646. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  37647. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  37648. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  37649. * 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.
  37650. * 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).
  37651. * This function is passed the newly built mesh :
  37652. * ```javascript
  37653. * function(mesh) { // do things
  37654. * return; }
  37655. * ```
  37656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37657. */
  37658. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  37659. var width = options.width || 10.0;
  37660. var height = options.height || 10.0;
  37661. var subdivisions = options.subdivisions || 1 | 0;
  37662. var minHeight = options.minHeight || 0.0;
  37663. var maxHeight = options.maxHeight || 10.0;
  37664. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37665. var updatable = options.updatable;
  37666. var onReady = options.onReady;
  37667. var ground = new BABYLON.GroundMesh(name, scene);
  37668. ground._subdivisionsX = subdivisions;
  37669. ground._subdivisionsY = subdivisions;
  37670. ground._width = width;
  37671. ground._height = height;
  37672. ground._maxX = ground._width / 2.0;
  37673. ground._maxZ = ground._height / 2.0;
  37674. ground._minX = -ground._maxX;
  37675. ground._minZ = -ground._maxZ;
  37676. ground._setReady(false);
  37677. var onload = function (img) {
  37678. // Getting height map data
  37679. var canvas = document.createElement("canvas");
  37680. var context = canvas.getContext("2d");
  37681. var bufferWidth = img.width;
  37682. var bufferHeight = img.height;
  37683. canvas.width = bufferWidth;
  37684. canvas.height = bufferHeight;
  37685. context.drawImage(img, 0, 0);
  37686. // Create VertexData from map data
  37687. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  37688. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  37689. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  37690. width: width, height: height,
  37691. subdivisions: subdivisions,
  37692. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  37693. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  37694. });
  37695. vertexData.applyToMesh(ground, updatable);
  37696. ground._setReady(true);
  37697. //execute ready callback, if set
  37698. if (onReady) {
  37699. onReady(ground);
  37700. }
  37701. };
  37702. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  37703. return ground;
  37704. };
  37705. /**
  37706. * Creates a polygon mesh.
  37707. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  37708. * 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.
  37709. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37711. * 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).
  37712. * Remember you can only change the shape positions, not their number when updating a polygon.
  37713. */
  37714. MeshBuilder.CreatePolygon = function (name, options, scene) {
  37715. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37716. var shape = options.shape;
  37717. var holes = options.holes || [];
  37718. var depth = options.depth || 0;
  37719. var contours = [];
  37720. var hole = [];
  37721. for (var i = 0; i < shape.length; i++) {
  37722. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  37723. }
  37724. var epsilon = 0.00000001;
  37725. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  37726. contours.pop();
  37727. }
  37728. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  37729. for (var hNb = 0; hNb < holes.length; hNb++) {
  37730. hole = [];
  37731. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  37732. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  37733. }
  37734. polygonTriangulation.addHole(hole);
  37735. }
  37736. var polygon = polygonTriangulation.build(options.updatable, depth);
  37737. polygon.sideOrientation = options.sideOrientation;
  37738. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  37739. vertexData.applyToMesh(polygon, options.updatable);
  37740. return polygon;
  37741. };
  37742. ;
  37743. /**
  37744. * Creates an extruded polygon mesh, with depth in the Y direction.
  37745. * 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).
  37746. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37747. */
  37748. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  37749. return MeshBuilder.CreatePolygon(name, options, scene);
  37750. };
  37751. ;
  37752. /**
  37753. * Creates a tube mesh.
  37754. * 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.
  37755. *
  37756. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  37757. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  37758. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  37759. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  37760. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  37761. * 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.
  37762. * It must return a radius value (positive float) :
  37763. * ```javascript
  37764. * var radiusFunction = function(i, distance) {
  37765. * // do things
  37766. * return radius; }
  37767. * ```
  37768. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  37769. * 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
  37770. * 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
  37771. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37772. * 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).
  37773. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37774. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37775. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37776. */
  37777. MeshBuilder.CreateTube = function (name, options, scene) {
  37778. var path = options.path;
  37779. var radius = options.radius || 1.0;
  37780. var tessellation = options.tessellation || 64 | 0;
  37781. var radiusFunction = options.radiusFunction;
  37782. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37783. var invertUV = options.invertUV || false;
  37784. var updatable = options.updatable;
  37785. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37786. var instance = options.instance;
  37787. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  37788. // tube geometry
  37789. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  37790. var tangents = path3D.getTangents();
  37791. var normals = path3D.getNormals();
  37792. var distances = path3D.getDistances();
  37793. var pi2 = Math.PI * 2;
  37794. var step = pi2 / tessellation * arc;
  37795. var returnRadius = function () { return radius; };
  37796. var radiusFunctionFinal = radiusFunction || returnRadius;
  37797. var circlePath;
  37798. var rad;
  37799. var normal;
  37800. var rotated;
  37801. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37802. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37803. for (var i = 0; i < path.length; i++) {
  37804. rad = radiusFunctionFinal(i, distances[i]); // current radius
  37805. circlePath = Array(); // current circle array
  37806. normal = normals[i]; // current normal
  37807. for (var t = 0; t < tessellation; t++) {
  37808. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  37809. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  37810. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  37811. rotated.scaleInPlace(rad).addInPlace(path[i]);
  37812. circlePath[t] = rotated;
  37813. }
  37814. circlePaths[index] = circlePath;
  37815. index++;
  37816. }
  37817. // cap
  37818. var capPath = function (nbPoints, pathIndex) {
  37819. var pointCap = Array();
  37820. for (var i = 0; i < nbPoints; i++) {
  37821. pointCap.push(path[pathIndex]);
  37822. }
  37823. return pointCap;
  37824. };
  37825. switch (cap) {
  37826. case BABYLON.Mesh.NO_CAP:
  37827. break;
  37828. case BABYLON.Mesh.CAP_START:
  37829. circlePaths[0] = capPath(tessellation, 0);
  37830. circlePaths[1] = circlePaths[2].slice(0);
  37831. break;
  37832. case BABYLON.Mesh.CAP_END:
  37833. circlePaths[index] = circlePaths[index - 1].slice(0);
  37834. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37835. break;
  37836. case BABYLON.Mesh.CAP_ALL:
  37837. circlePaths[0] = capPath(tessellation, 0);
  37838. circlePaths[1] = circlePaths[2].slice(0);
  37839. circlePaths[index] = circlePaths[index - 1].slice(0);
  37840. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37841. break;
  37842. default:
  37843. break;
  37844. }
  37845. return circlePaths;
  37846. };
  37847. var path3D;
  37848. var pathArray;
  37849. if (instance) {
  37850. var arc = options.arc || instance.arc;
  37851. path3D = (instance.path3D).update(path);
  37852. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  37853. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  37854. instance.path3D = path3D;
  37855. instance.pathArray = pathArray;
  37856. instance.arc = arc;
  37857. return instance;
  37858. }
  37859. // tube creation
  37860. path3D = new BABYLON.Path3D(path);
  37861. var newPathArray = new Array();
  37862. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37863. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  37864. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37865. tube.pathArray = pathArray;
  37866. tube.path3D = path3D;
  37867. tube.tessellation = tessellation;
  37868. tube.cap = cap;
  37869. tube.arc = options.arc;
  37870. return tube;
  37871. };
  37872. /**
  37873. * Creates a polyhedron mesh.
  37874. *
  37875. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  37876. * 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
  37877. * to choose the wanted type.
  37878. * The parameter `size` (positive float, default 1) sets the polygon size.
  37879. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  37880. * 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`.
  37881. * 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
  37882. * 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)`).
  37883. * 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
  37884. * 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.
  37885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37886. * 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).
  37887. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37888. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37889. */
  37890. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  37891. var polyhedron = new BABYLON.Mesh(name, scene);
  37892. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37893. polyhedron.sideOrientation = options.sideOrientation;
  37894. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  37895. vertexData.applyToMesh(polyhedron, options.updatable);
  37896. return polyhedron;
  37897. };
  37898. /**
  37899. * Creates a decal mesh.
  37900. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  37901. * 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.
  37902. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  37903. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  37904. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  37905. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  37906. */
  37907. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  37908. var indices = sourceMesh.getIndices();
  37909. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37910. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37911. var position = options.position || BABYLON.Vector3.Zero();
  37912. var normal = options.normal || BABYLON.Vector3.Up();
  37913. var size = options.size || BABYLON.Vector3.One();
  37914. var angle = options.angle || 0;
  37915. // Getting correct rotation
  37916. if (!normal) {
  37917. var target = new BABYLON.Vector3(0, 0, 1);
  37918. var camera = sourceMesh.getScene().activeCamera;
  37919. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  37920. normal = camera.globalPosition.subtract(cameraWorldTarget);
  37921. }
  37922. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  37923. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  37924. var pitch = Math.atan2(normal.y, len);
  37925. // Matrix
  37926. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  37927. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  37928. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  37929. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  37930. var vertexData = new BABYLON.VertexData();
  37931. vertexData.indices = [];
  37932. vertexData.positions = [];
  37933. vertexData.normals = [];
  37934. vertexData.uvs = [];
  37935. var currentVertexDataIndex = 0;
  37936. var extractDecalVector3 = function (indexId) {
  37937. var vertexId = indices[indexId];
  37938. var result = new BABYLON.PositionNormalVertex();
  37939. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  37940. // Send vector to decal local world
  37941. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  37942. // Get normal
  37943. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  37944. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  37945. return result;
  37946. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  37947. var clip = function (vertices, axis) {
  37948. if (vertices.length === 0) {
  37949. return vertices;
  37950. }
  37951. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  37952. var clipVertices = function (v0, v1) {
  37953. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  37954. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  37955. };
  37956. var result = new Array();
  37957. for (var index = 0; index < vertices.length; index += 3) {
  37958. var v1Out;
  37959. var v2Out;
  37960. var v3Out;
  37961. var total = 0;
  37962. var nV1, nV2, nV3, nV4;
  37963. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  37964. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  37965. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  37966. v1Out = d1 > 0;
  37967. v2Out = d2 > 0;
  37968. v3Out = d3 > 0;
  37969. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  37970. switch (total) {
  37971. case 0:
  37972. result.push(vertices[index]);
  37973. result.push(vertices[index + 1]);
  37974. result.push(vertices[index + 2]);
  37975. break;
  37976. case 1:
  37977. if (v1Out) {
  37978. nV1 = vertices[index + 1];
  37979. nV2 = vertices[index + 2];
  37980. nV3 = clipVertices(vertices[index], nV1);
  37981. nV4 = clipVertices(vertices[index], nV2);
  37982. }
  37983. if (v2Out) {
  37984. nV1 = vertices[index];
  37985. nV2 = vertices[index + 2];
  37986. nV3 = clipVertices(vertices[index + 1], nV1);
  37987. nV4 = clipVertices(vertices[index + 1], nV2);
  37988. result.push(nV3);
  37989. result.push(nV2.clone());
  37990. result.push(nV1.clone());
  37991. result.push(nV2.clone());
  37992. result.push(nV3.clone());
  37993. result.push(nV4);
  37994. break;
  37995. }
  37996. if (v3Out) {
  37997. nV1 = vertices[index];
  37998. nV2 = vertices[index + 1];
  37999. nV3 = clipVertices(vertices[index + 2], nV1);
  38000. nV4 = clipVertices(vertices[index + 2], nV2);
  38001. }
  38002. result.push(nV1.clone());
  38003. result.push(nV2.clone());
  38004. result.push(nV3);
  38005. result.push(nV4);
  38006. result.push(nV3.clone());
  38007. result.push(nV2.clone());
  38008. break;
  38009. case 2:
  38010. if (!v1Out) {
  38011. nV1 = vertices[index].clone();
  38012. nV2 = clipVertices(nV1, vertices[index + 1]);
  38013. nV3 = clipVertices(nV1, vertices[index + 2]);
  38014. result.push(nV1);
  38015. result.push(nV2);
  38016. result.push(nV3);
  38017. }
  38018. if (!v2Out) {
  38019. nV1 = vertices[index + 1].clone();
  38020. nV2 = clipVertices(nV1, vertices[index + 2]);
  38021. nV3 = clipVertices(nV1, vertices[index]);
  38022. result.push(nV1);
  38023. result.push(nV2);
  38024. result.push(nV3);
  38025. }
  38026. if (!v3Out) {
  38027. nV1 = vertices[index + 2].clone();
  38028. nV2 = clipVertices(nV1, vertices[index]);
  38029. nV3 = clipVertices(nV1, vertices[index + 1]);
  38030. result.push(nV1);
  38031. result.push(nV2);
  38032. result.push(nV3);
  38033. }
  38034. break;
  38035. case 3:
  38036. break;
  38037. }
  38038. }
  38039. return result;
  38040. };
  38041. for (var index = 0; index < indices.length; index += 3) {
  38042. var faceVertices = new Array();
  38043. faceVertices.push(extractDecalVector3(index));
  38044. faceVertices.push(extractDecalVector3(index + 1));
  38045. faceVertices.push(extractDecalVector3(index + 2));
  38046. // Clip
  38047. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  38048. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  38049. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  38050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  38051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  38052. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  38053. if (faceVertices.length === 0) {
  38054. continue;
  38055. }
  38056. // Add UVs and get back to world
  38057. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  38058. var vertex = faceVertices[vIndex];
  38059. //TODO check for Int32Array | Uint32Array | Uint16Array
  38060. vertexData.indices.push(currentVertexDataIndex);
  38061. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  38062. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  38063. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  38064. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  38065. currentVertexDataIndex++;
  38066. }
  38067. }
  38068. // Return mesh
  38069. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  38070. vertexData.applyToMesh(decal);
  38071. decal.position = position.clone();
  38072. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  38073. return decal;
  38074. };
  38075. // Privates
  38076. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  38077. // extrusion geometry
  38078. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  38079. var tangents = path3D.getTangents();
  38080. var normals = path3D.getNormals();
  38081. var binormals = path3D.getBinormals();
  38082. var distances = path3D.getDistances();
  38083. var angle = 0;
  38084. var returnScale = function () { return scale; };
  38085. var returnRotation = function () { return rotation; };
  38086. var rotate = custom ? rotateFunction : returnRotation;
  38087. var scl = custom ? scaleFunction : returnScale;
  38088. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  38089. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  38090. for (var i = 0; i < curve.length; i++) {
  38091. var shapePath = new Array();
  38092. var angleStep = rotate(i, distances[i]);
  38093. var scaleRatio = scl(i, distances[i]);
  38094. for (var p = 0; p < shape.length; p++) {
  38095. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  38096. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  38097. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  38098. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  38099. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  38100. shapePath[p] = rotated;
  38101. }
  38102. shapePaths[index] = shapePath;
  38103. angle += angleStep;
  38104. index++;
  38105. }
  38106. // cap
  38107. var capPath = function (shapePath) {
  38108. var pointCap = Array();
  38109. var barycenter = BABYLON.Vector3.Zero();
  38110. var i;
  38111. for (i = 0; i < shapePath.length; i++) {
  38112. barycenter.addInPlace(shapePath[i]);
  38113. }
  38114. barycenter.scaleInPlace(1.0 / shapePath.length);
  38115. for (i = 0; i < shapePath.length; i++) {
  38116. pointCap.push(barycenter);
  38117. }
  38118. return pointCap;
  38119. };
  38120. switch (cap) {
  38121. case BABYLON.Mesh.NO_CAP:
  38122. break;
  38123. case BABYLON.Mesh.CAP_START:
  38124. shapePaths[0] = capPath(shapePaths[2]);
  38125. shapePaths[1] = shapePaths[2];
  38126. break;
  38127. case BABYLON.Mesh.CAP_END:
  38128. shapePaths[index] = shapePaths[index - 1];
  38129. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38130. break;
  38131. case BABYLON.Mesh.CAP_ALL:
  38132. shapePaths[0] = capPath(shapePaths[2]);
  38133. shapePaths[1] = shapePaths[2];
  38134. shapePaths[index] = shapePaths[index - 1];
  38135. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  38136. break;
  38137. default:
  38138. break;
  38139. }
  38140. return shapePaths;
  38141. };
  38142. var path3D;
  38143. var pathArray;
  38144. if (instance) {
  38145. path3D = (instance.path3D).update(curve);
  38146. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  38147. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  38148. return instance;
  38149. }
  38150. // extruded shape creation
  38151. path3D = new BABYLON.Path3D(curve);
  38152. var newShapePaths = new Array();
  38153. cap = (cap < 0 || cap > 3) ? 0 : cap;
  38154. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  38155. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  38156. extrudedGeneric.pathArray = pathArray;
  38157. extrudedGeneric.path3D = path3D;
  38158. extrudedGeneric.cap = cap;
  38159. return extrudedGeneric;
  38160. };
  38161. return MeshBuilder;
  38162. }());
  38163. BABYLON.MeshBuilder = MeshBuilder;
  38164. })(BABYLON || (BABYLON = {}));
  38165. //# sourceMappingURL=babylon.meshBuilder.js.map
  38166. var BABYLON;
  38167. (function (BABYLON) {
  38168. var Layer = (function () {
  38169. function Layer(name, imgUrl, scene, isBackground, color) {
  38170. this.name = name;
  38171. this.scale = new BABYLON.Vector2(1, 1);
  38172. this.offset = new BABYLON.Vector2(0, 0);
  38173. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  38174. this.layerMask = 0x0FFFFFFF;
  38175. this._vertexBuffers = {};
  38176. // Events
  38177. /**
  38178. * An event triggered when the layer is disposed.
  38179. * @type {BABYLON.Observable}
  38180. */
  38181. this.onDisposeObservable = new BABYLON.Observable();
  38182. /**
  38183. * An event triggered before rendering the scene
  38184. * @type {BABYLON.Observable}
  38185. */
  38186. this.onBeforeRenderObservable = new BABYLON.Observable();
  38187. /**
  38188. * An event triggered after rendering the scene
  38189. * @type {BABYLON.Observable}
  38190. */
  38191. this.onAfterRenderObservable = new BABYLON.Observable();
  38192. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  38193. this.isBackground = isBackground === undefined ? true : isBackground;
  38194. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  38195. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  38196. this._scene.layers.push(this);
  38197. var engine = this._scene.getEngine();
  38198. // VBO
  38199. var vertices = [];
  38200. vertices.push(1, 1);
  38201. vertices.push(-1, 1);
  38202. vertices.push(-1, -1);
  38203. vertices.push(1, -1);
  38204. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38206. // Indices
  38207. var indices = [];
  38208. indices.push(0);
  38209. indices.push(1);
  38210. indices.push(2);
  38211. indices.push(0);
  38212. indices.push(2);
  38213. indices.push(3);
  38214. this._indexBuffer = engine.createIndexBuffer(indices);
  38215. // Effects
  38216. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  38217. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  38218. }
  38219. Object.defineProperty(Layer.prototype, "onDispose", {
  38220. set: function (callback) {
  38221. if (this._onDisposeObserver) {
  38222. this.onDisposeObservable.remove(this._onDisposeObserver);
  38223. }
  38224. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38225. },
  38226. enumerable: true,
  38227. configurable: true
  38228. });
  38229. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  38230. set: function (callback) {
  38231. if (this._onBeforeRenderObserver) {
  38232. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  38233. }
  38234. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  38235. },
  38236. enumerable: true,
  38237. configurable: true
  38238. });
  38239. Object.defineProperty(Layer.prototype, "onAfterRender", {
  38240. set: function (callback) {
  38241. if (this._onAfterRenderObserver) {
  38242. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  38243. }
  38244. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  38245. },
  38246. enumerable: true,
  38247. configurable: true
  38248. });
  38249. Layer.prototype.render = function () {
  38250. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  38251. // Check
  38252. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  38253. return;
  38254. var engine = this._scene.getEngine();
  38255. this.onBeforeRenderObservable.notifyObservers(this);
  38256. // Render
  38257. engine.enableEffect(currentEffect);
  38258. engine.setState(false);
  38259. // Texture
  38260. currentEffect.setTexture("textureSampler", this.texture);
  38261. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  38262. // Color
  38263. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  38264. // Scale / offset
  38265. currentEffect.setVector2("offset", this.offset);
  38266. currentEffect.setVector2("scale", this.scale);
  38267. // VBOs
  38268. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38269. // Draw order
  38270. if (!this.alphaTest) {
  38271. engine.setAlphaMode(this.alphaBlendingMode);
  38272. engine.draw(true, 0, 6);
  38273. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38274. }
  38275. else {
  38276. engine.draw(true, 0, 6);
  38277. }
  38278. this.onAfterRenderObservable.notifyObservers(this);
  38279. };
  38280. Layer.prototype.dispose = function () {
  38281. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38282. if (vertexBuffer) {
  38283. vertexBuffer.dispose();
  38284. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38285. }
  38286. if (this._indexBuffer) {
  38287. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38288. this._indexBuffer = null;
  38289. }
  38290. if (this.texture) {
  38291. this.texture.dispose();
  38292. this.texture = null;
  38293. }
  38294. // Remove from scene
  38295. var index = this._scene.layers.indexOf(this);
  38296. this._scene.layers.splice(index, 1);
  38297. // Callback
  38298. this.onDisposeObservable.notifyObservers(this);
  38299. this.onDisposeObservable.clear();
  38300. this.onAfterRenderObservable.clear();
  38301. this.onBeforeRenderObservable.clear();
  38302. };
  38303. return Layer;
  38304. }());
  38305. BABYLON.Layer = Layer;
  38306. })(BABYLON || (BABYLON = {}));
  38307. //# sourceMappingURL=babylon.layer.js.map
  38308. var BABYLON;
  38309. (function (BABYLON) {
  38310. var BlurPostProcess = (function (_super) {
  38311. __extends(BlurPostProcess, _super);
  38312. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  38313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38314. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38315. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  38316. _this.direction = direction;
  38317. _this._packedFloat = false;
  38318. _this.onApplyObservable.add(function (effect) {
  38319. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  38320. });
  38321. _this.kernel = kernel;
  38322. return _this;
  38323. }
  38324. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  38325. /**
  38326. * Gets the length in pixels of the blur sample region
  38327. */
  38328. get: function () {
  38329. return this._idealKernel;
  38330. },
  38331. /**
  38332. * Sets the length in pixels of the blur sample region
  38333. */
  38334. set: function (v) {
  38335. if (this._idealKernel === v) {
  38336. return;
  38337. }
  38338. v = Math.max(v, 1);
  38339. this._idealKernel = v;
  38340. this._kernel = this._nearestBestKernel(v);
  38341. this._updateParameters();
  38342. },
  38343. enumerable: true,
  38344. configurable: true
  38345. });
  38346. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  38347. /**
  38348. * Gets wether or not the blur is unpacking/repacking floats
  38349. */
  38350. get: function () {
  38351. return this._packedFloat;
  38352. },
  38353. /**
  38354. * Sets wether or not the blur needs to unpack/repack floats
  38355. */
  38356. set: function (v) {
  38357. if (this._packedFloat === v) {
  38358. return;
  38359. }
  38360. this._packedFloat = v;
  38361. this._updateParameters();
  38362. },
  38363. enumerable: true,
  38364. configurable: true
  38365. });
  38366. BlurPostProcess.prototype._updateParameters = function () {
  38367. // Generate sampling offsets and weights
  38368. var N = this._kernel;
  38369. var centerIndex = (N - 1) / 2;
  38370. // Generate Gaussian sampling weights over kernel
  38371. var offsets = [];
  38372. var weights = [];
  38373. var totalWeight = 0;
  38374. for (var i = 0; i < N; i++) {
  38375. var u = i / (N - 1);
  38376. var w = this._gaussianWeight(u * 2.0 - 1);
  38377. offsets[i] = (i - centerIndex);
  38378. weights[i] = w;
  38379. totalWeight += w;
  38380. }
  38381. // Normalize weights
  38382. for (var i = 0; i < weights.length; i++) {
  38383. weights[i] /= totalWeight;
  38384. }
  38385. // Optimize: combine samples to take advantage of hardware linear sampling
  38386. // Walk from left to center, combining pairs (symmetrically)
  38387. var linearSamplingWeights = [];
  38388. var linearSamplingOffsets = [];
  38389. var linearSamplingMap = [];
  38390. for (var i = 0; i <= centerIndex; i += 2) {
  38391. var j = Math.min(i + 1, Math.floor(centerIndex));
  38392. var singleCenterSample = i === j;
  38393. if (singleCenterSample) {
  38394. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38395. }
  38396. else {
  38397. var sharedCell = j === centerIndex;
  38398. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  38399. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  38400. if (offsetLinear === 0) {
  38401. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38402. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  38403. }
  38404. else {
  38405. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  38406. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  38407. }
  38408. }
  38409. }
  38410. for (var i = 0; i < linearSamplingMap.length; i++) {
  38411. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  38412. linearSamplingWeights[i] = linearSamplingMap[i].w;
  38413. }
  38414. // Replace with optimized
  38415. offsets = linearSamplingOffsets;
  38416. weights = linearSamplingWeights;
  38417. // Generate shaders
  38418. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  38419. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  38420. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  38421. var defines = "";
  38422. for (var i = 0; i < varyingCount; i++) {
  38423. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  38424. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  38425. }
  38426. var depCount = 0;
  38427. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  38428. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  38429. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  38430. depCount++;
  38431. }
  38432. if (this.packedFloat) {
  38433. defines += "#define PACKEDFLOAT 1";
  38434. }
  38435. this.updateEffect(defines, null, null, {
  38436. varyingCount: varyingCount,
  38437. depCount: depCount
  38438. });
  38439. };
  38440. /**
  38441. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  38442. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  38443. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  38444. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  38445. * The gaps between physical kernels are compensated for in the weighting of the samples
  38446. * @param idealKernel Ideal blur kernel.
  38447. * @return Nearest best kernel.
  38448. */
  38449. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  38450. var v = Math.round(idealKernel);
  38451. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  38452. var k = _a[_i];
  38453. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  38454. return Math.max(k, 3);
  38455. }
  38456. }
  38457. return Math.max(v, 3);
  38458. };
  38459. /**
  38460. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  38461. * @param x The point on the Gaussian distribution to sample.
  38462. * @return the value of the Gaussian function at x.
  38463. */
  38464. BlurPostProcess.prototype._gaussianWeight = function (x) {
  38465. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  38466. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  38467. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  38468. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  38469. // truncated at around 1.3% of peak strength.
  38470. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  38471. var sigma = (1 / 3);
  38472. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  38473. var exponent = -((x * x) / (2.0 * sigma * sigma));
  38474. var weight = (1.0 / denominator) * Math.exp(exponent);
  38475. return weight;
  38476. };
  38477. /**
  38478. * Generates a string that can be used as a floating point number in GLSL.
  38479. * @param x Value to print.
  38480. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  38481. * @return GLSL float string.
  38482. */
  38483. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  38484. if (decimalFigures === void 0) { decimalFigures = 8; }
  38485. return x.toFixed(decimalFigures).replace(/0+$/, '');
  38486. };
  38487. return BlurPostProcess;
  38488. }(BABYLON.PostProcess));
  38489. BABYLON.BlurPostProcess = BlurPostProcess;
  38490. })(BABYLON || (BABYLON = {}));
  38491. //# sourceMappingURL=babylon.blurPostProcess.js.map
  38492. var BABYLON;
  38493. (function (BABYLON) {
  38494. var FxaaPostProcess = (function (_super) {
  38495. __extends(FxaaPostProcess, _super);
  38496. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38497. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38498. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  38499. _this.onApplyObservable.add(function (effect) {
  38500. var texelSize = _this.texelSize;
  38501. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  38502. });
  38503. return _this;
  38504. }
  38505. return FxaaPostProcess;
  38506. }(BABYLON.PostProcess));
  38507. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38508. })(BABYLON || (BABYLON = {}));
  38509. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  38510. var BABYLON;
  38511. (function (BABYLON) {
  38512. var HighlightsPostProcess = (function (_super) {
  38513. __extends(HighlightsPostProcess, _super);
  38514. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38515. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38516. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  38517. }
  38518. return HighlightsPostProcess;
  38519. }(BABYLON.PostProcess));
  38520. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  38521. })(BABYLON || (BABYLON = {}));
  38522. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  38523. var BABYLON;
  38524. (function (BABYLON) {
  38525. var ImageProcessingPostProcess = (function (_super) {
  38526. __extends(ImageProcessingPostProcess, _super);
  38527. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38528. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38529. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  38530. _this._fromLinearSpace = true;
  38531. /**
  38532. * Defines cache preventing GC.
  38533. */
  38534. _this._defines = {
  38535. IMAGEPROCESSING: false,
  38536. VIGNETTE: false,
  38537. VIGNETTEBLENDMODEMULTIPLY: false,
  38538. VIGNETTEBLENDMODEOPAQUE: false,
  38539. TONEMAPPING: false,
  38540. CONTRAST: false,
  38541. COLORCURVES: false,
  38542. COLORGRADING: false,
  38543. FROMLINEARSPACE: false,
  38544. SAMPLER3DGREENDEPTH: false,
  38545. SAMPLER3DBGRMAP: false,
  38546. IMAGEPROCESSINGPOSTPROCESS: false,
  38547. EXPOSURE: false,
  38548. };
  38549. // Setup the default processing configuration to the scene.
  38550. _this._attachImageProcessingConfiguration(null);
  38551. _this.imageProcessingConfiguration.applyByPostProcess = true;
  38552. _this._updateParameters();
  38553. _this.onApply = function (effect) {
  38554. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  38555. };
  38556. return _this;
  38557. }
  38558. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  38559. /**
  38560. * Gets the image processing configuration used either in this material.
  38561. */
  38562. get: function () {
  38563. return this._imageProcessingConfiguration;
  38564. },
  38565. /**
  38566. * Sets the Default image processing configuration used either in the this material.
  38567. *
  38568. * If sets to null, the scene one is in use.
  38569. */
  38570. set: function (value) {
  38571. this._attachImageProcessingConfiguration(value);
  38572. },
  38573. enumerable: true,
  38574. configurable: true
  38575. });
  38576. /**
  38577. * Attaches a new image processing configuration to the PBR Material.
  38578. * @param configuration
  38579. */
  38580. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration) {
  38581. var _this = this;
  38582. if (configuration === this._imageProcessingConfiguration) {
  38583. return;
  38584. }
  38585. // Detaches observer.
  38586. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38587. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38588. }
  38589. // Pick the scene configuration if needed.
  38590. if (!configuration) {
  38591. var camera = this.getCamera();
  38592. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  38593. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  38594. }
  38595. else {
  38596. this._imageProcessingConfiguration = configuration;
  38597. }
  38598. // Attaches observer.
  38599. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38600. _this._updateParameters();
  38601. });
  38602. // Ensure the effect will be rebuilt.
  38603. this._updateParameters();
  38604. };
  38605. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  38606. /**
  38607. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38608. */
  38609. get: function () {
  38610. return this.imageProcessingConfiguration.colorCurves;
  38611. },
  38612. /**
  38613. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  38614. */
  38615. set: function (value) {
  38616. this.imageProcessingConfiguration.colorCurves = value;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  38622. /**
  38623. * Gets wether the color curves effect is enabled.
  38624. */
  38625. get: function () {
  38626. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38627. },
  38628. /**
  38629. * Sets wether the color curves effect is enabled.
  38630. */
  38631. set: function (value) {
  38632. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38633. },
  38634. enumerable: true,
  38635. configurable: true
  38636. });
  38637. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  38638. /**
  38639. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38640. */
  38641. get: function () {
  38642. return this.imageProcessingConfiguration.colorGradingTexture;
  38643. },
  38644. /**
  38645. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  38646. */
  38647. set: function (value) {
  38648. this.imageProcessingConfiguration.colorGradingTexture = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  38654. /**
  38655. * Gets wether the color grading effect is enabled.
  38656. */
  38657. get: function () {
  38658. return this.imageProcessingConfiguration.colorGradingEnabled;
  38659. },
  38660. /**
  38661. * Gets wether the color grading effect is enabled.
  38662. */
  38663. set: function (value) {
  38664. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38665. },
  38666. enumerable: true,
  38667. configurable: true
  38668. });
  38669. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  38670. /**
  38671. * Gets exposure used in the effect.
  38672. */
  38673. get: function () {
  38674. return this.imageProcessingConfiguration.exposure;
  38675. },
  38676. /**
  38677. * Sets exposure used in the effect.
  38678. */
  38679. set: function (value) {
  38680. this.imageProcessingConfiguration.exposure = value;
  38681. },
  38682. enumerable: true,
  38683. configurable: true
  38684. });
  38685. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  38686. /**
  38687. * Gets wether tonemapping is enabled or not.
  38688. */
  38689. get: function () {
  38690. return this._imageProcessingConfiguration.toneMappingEnabled;
  38691. },
  38692. /**
  38693. * Sets wether tonemapping is enabled or not
  38694. */
  38695. set: function (value) {
  38696. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38697. },
  38698. enumerable: true,
  38699. configurable: true
  38700. });
  38701. ;
  38702. ;
  38703. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  38704. /**
  38705. * Gets contrast used in the effect.
  38706. */
  38707. get: function () {
  38708. return this.imageProcessingConfiguration.contrast;
  38709. },
  38710. /**
  38711. * Sets contrast used in the effect.
  38712. */
  38713. set: function (value) {
  38714. this.imageProcessingConfiguration.contrast = value;
  38715. },
  38716. enumerable: true,
  38717. configurable: true
  38718. });
  38719. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  38720. /**
  38721. * Gets Vignette stretch size.
  38722. */
  38723. get: function () {
  38724. return this.imageProcessingConfiguration.vignetteStretch;
  38725. },
  38726. /**
  38727. * Sets Vignette stretch size.
  38728. */
  38729. set: function (value) {
  38730. this.imageProcessingConfiguration.vignetteStretch = value;
  38731. },
  38732. enumerable: true,
  38733. configurable: true
  38734. });
  38735. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  38736. /**
  38737. * Gets Vignette centre X Offset.
  38738. */
  38739. get: function () {
  38740. return this.imageProcessingConfiguration.vignetteCentreX;
  38741. },
  38742. /**
  38743. * Sets Vignette centre X Offset.
  38744. */
  38745. set: function (value) {
  38746. this.imageProcessingConfiguration.vignetteCentreX = value;
  38747. },
  38748. enumerable: true,
  38749. configurable: true
  38750. });
  38751. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  38752. /**
  38753. * Gets Vignette centre Y Offset.
  38754. */
  38755. get: function () {
  38756. return this.imageProcessingConfiguration.vignetteCentreY;
  38757. },
  38758. /**
  38759. * Sets Vignette centre Y Offset.
  38760. */
  38761. set: function (value) {
  38762. this.imageProcessingConfiguration.vignetteCentreY = value;
  38763. },
  38764. enumerable: true,
  38765. configurable: true
  38766. });
  38767. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  38768. /**
  38769. * Gets Vignette weight or intensity of the vignette effect.
  38770. */
  38771. get: function () {
  38772. return this.imageProcessingConfiguration.vignetteWeight;
  38773. },
  38774. /**
  38775. * Sets Vignette weight or intensity of the vignette effect.
  38776. */
  38777. set: function (value) {
  38778. this.imageProcessingConfiguration.vignetteWeight = value;
  38779. },
  38780. enumerable: true,
  38781. configurable: true
  38782. });
  38783. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  38784. /**
  38785. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38786. * if vignetteEnabled is set to true.
  38787. */
  38788. get: function () {
  38789. return this.imageProcessingConfiguration.vignetteColor;
  38790. },
  38791. /**
  38792. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  38793. * if vignetteEnabled is set to true.
  38794. */
  38795. set: function (value) {
  38796. this.imageProcessingConfiguration.vignetteColor = value;
  38797. },
  38798. enumerable: true,
  38799. configurable: true
  38800. });
  38801. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  38802. /**
  38803. * Gets Camera field of view used by the Vignette effect.
  38804. */
  38805. get: function () {
  38806. return this.imageProcessingConfiguration.vignetteCameraFov;
  38807. },
  38808. /**
  38809. * Sets Camera field of view used by the Vignette effect.
  38810. */
  38811. set: function (value) {
  38812. this.imageProcessingConfiguration.vignetteCameraFov = value;
  38813. },
  38814. enumerable: true,
  38815. configurable: true
  38816. });
  38817. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  38818. /**
  38819. * Gets the vignette blend mode allowing different kind of effect.
  38820. */
  38821. get: function () {
  38822. return this.imageProcessingConfiguration.vignetteBlendMode;
  38823. },
  38824. /**
  38825. * Sets the vignette blend mode allowing different kind of effect.
  38826. */
  38827. set: function (value) {
  38828. this.imageProcessingConfiguration.vignetteBlendMode = value;
  38829. },
  38830. enumerable: true,
  38831. configurable: true
  38832. });
  38833. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  38834. /**
  38835. * Gets wether the vignette effect is enabled.
  38836. */
  38837. get: function () {
  38838. return this.imageProcessingConfiguration.vignetteEnabled;
  38839. },
  38840. /**
  38841. * Sets wether the vignette effect is enabled.
  38842. */
  38843. set: function (value) {
  38844. this.imageProcessingConfiguration.vignetteEnabled = value;
  38845. },
  38846. enumerable: true,
  38847. configurable: true
  38848. });
  38849. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  38850. /**
  38851. * Gets wether the input of the processing is in Gamma or Linear Space.
  38852. */
  38853. get: function () {
  38854. return this._fromLinearSpace;
  38855. },
  38856. /**
  38857. * Sets wether the input of the processing is in Gamma or Linear Space.
  38858. */
  38859. set: function (value) {
  38860. if (this._fromLinearSpace === value) {
  38861. return;
  38862. }
  38863. this._fromLinearSpace = value;
  38864. this._updateParameters();
  38865. },
  38866. enumerable: true,
  38867. configurable: true
  38868. });
  38869. ImageProcessingPostProcess.prototype._updateParameters = function () {
  38870. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  38871. this.imageProcessingConfiguration.prepareDefines(this._defines);
  38872. var defines = "";
  38873. for (var define in this._defines) {
  38874. if (this._defines[define]) {
  38875. defines += "#define " + define + ";\r\n";
  38876. }
  38877. }
  38878. var samplers = ["textureSampler"];
  38879. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  38880. var uniforms = ["scale"];
  38881. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  38882. this.updateEffect(defines, uniforms, samplers);
  38883. };
  38884. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  38885. _super.prototype.dispose.call(this, camera);
  38886. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38887. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38888. }
  38889. this.imageProcessingConfiguration.applyByPostProcess = false;
  38890. };
  38891. return ImageProcessingPostProcess;
  38892. }(BABYLON.PostProcess));
  38893. __decorate([
  38894. BABYLON.serialize()
  38895. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  38896. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  38897. })(BABYLON || (BABYLON = {}));
  38898. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  38899. var BABYLON;
  38900. (function (BABYLON) {
  38901. /**
  38902. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38903. * It can help converting any input color in a desired output one. This can then be used to create effects
  38904. * from sepia, black and white to sixties or futuristic rendering...
  38905. *
  38906. * The only supported format is currently 3dl.
  38907. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38908. */
  38909. var ColorGradingTexture = (function (_super) {
  38910. __extends(ColorGradingTexture, _super);
  38911. /**
  38912. * Instantiates a ColorGradingTexture from the following parameters.
  38913. *
  38914. * @param url The location of the color gradind data (currently only supporting 3dl)
  38915. * @param scene The scene the texture will be used in
  38916. */
  38917. function ColorGradingTexture(url, scene) {
  38918. var _this = _super.call(this, scene) || this;
  38919. if (!url) {
  38920. return _this;
  38921. }
  38922. _this._textureMatrix = BABYLON.Matrix.Identity();
  38923. _this.name = url;
  38924. _this.url = url;
  38925. _this.hasAlpha = false;
  38926. _this.isCube = false;
  38927. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38928. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38929. _this.anisotropicFilteringLevel = 1;
  38930. _this._texture = _this._getFromCache(url, true);
  38931. if (!_this._texture) {
  38932. if (!scene.useDelayedTextureLoading) {
  38933. _this.loadTexture();
  38934. }
  38935. else {
  38936. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38937. }
  38938. }
  38939. return _this;
  38940. }
  38941. /**
  38942. * Returns the texture matrix used in most of the material.
  38943. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38944. */
  38945. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38946. return this._textureMatrix;
  38947. };
  38948. /**
  38949. * Occurs when the file being loaded is a .3dl LUT file.
  38950. */
  38951. ColorGradingTexture.prototype.load3dlTexture = function () {
  38952. var _this = this;
  38953. var mipLevels = 0;
  38954. var floatArrayView = null;
  38955. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38956. this._texture = texture;
  38957. var callback = function (text) {
  38958. var data;
  38959. var tempData;
  38960. var line;
  38961. var lines = text.split('\n');
  38962. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38963. var maxColor = 0;
  38964. for (var i = 0; i < lines.length; i++) {
  38965. line = lines[i];
  38966. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38967. continue;
  38968. if (line.indexOf('#') === 0)
  38969. continue;
  38970. var words = line.split(" ");
  38971. if (size === 0) {
  38972. // Number of space + one
  38973. size = words.length;
  38974. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38975. tempData = new Float32Array(size * size * size * 4);
  38976. continue;
  38977. }
  38978. if (size != 0) {
  38979. var r = Math.max(parseInt(words[0]), 0);
  38980. var g = Math.max(parseInt(words[1]), 0);
  38981. var b = Math.max(parseInt(words[2]), 0);
  38982. maxColor = Math.max(r, maxColor);
  38983. maxColor = Math.max(g, maxColor);
  38984. maxColor = Math.max(b, maxColor);
  38985. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38986. tempData[pixelStorageIndex + 0] = r;
  38987. tempData[pixelStorageIndex + 1] = g;
  38988. tempData[pixelStorageIndex + 2] = b;
  38989. pixelIndexSlice++;
  38990. if (pixelIndexSlice % size == 0) {
  38991. pixelIndexH++;
  38992. pixelIndexSlice = 0;
  38993. if (pixelIndexH % size == 0) {
  38994. pixelIndexW++;
  38995. pixelIndexH = 0;
  38996. }
  38997. }
  38998. }
  38999. }
  39000. for (var i = 0; i < tempData.length; i++) {
  39001. if (i > 0 && (i + 1) % 4 === 0) {
  39002. data[i] = 255;
  39003. }
  39004. else {
  39005. var value = tempData[i];
  39006. data[i] = (value / maxColor * 255);
  39007. }
  39008. }
  39009. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  39010. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  39011. };
  39012. BABYLON.Tools.LoadFile(this.url, callback);
  39013. return this._texture;
  39014. };
  39015. /**
  39016. * Starts the loading process of the texture.
  39017. */
  39018. ColorGradingTexture.prototype.loadTexture = function () {
  39019. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  39020. this.load3dlTexture();
  39021. }
  39022. };
  39023. /**
  39024. * Clones the color gradind texture.
  39025. */
  39026. ColorGradingTexture.prototype.clone = function () {
  39027. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  39028. // Base texture
  39029. newTexture.level = this.level;
  39030. return newTexture;
  39031. };
  39032. /**
  39033. * Called during delayed load for textures.
  39034. */
  39035. ColorGradingTexture.prototype.delayLoad = function () {
  39036. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  39037. return;
  39038. }
  39039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39040. this._texture = this._getFromCache(this.url, true);
  39041. if (!this._texture) {
  39042. this.loadTexture();
  39043. }
  39044. };
  39045. /**
  39046. * Parses a color grading texture serialized by Babylon.
  39047. * @param parsedTexture The texture information being parsedTexture
  39048. * @param scene The scene to load the texture in
  39049. * @param rootUrl The root url of the data assets to load
  39050. * @return A color gradind texture
  39051. */
  39052. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  39053. var texture = null;
  39054. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  39055. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  39056. texture.name = parsedTexture.name;
  39057. texture.level = parsedTexture.level;
  39058. }
  39059. return texture;
  39060. };
  39061. /**
  39062. * Serializes the LUT texture to json format.
  39063. */
  39064. ColorGradingTexture.prototype.serialize = function () {
  39065. if (!this.name) {
  39066. return null;
  39067. }
  39068. var serializationObject = {};
  39069. serializationObject.name = this.name;
  39070. serializationObject.level = this.level;
  39071. serializationObject.customType = "BABYLON.ColorGradingTexture";
  39072. return serializationObject;
  39073. };
  39074. return ColorGradingTexture;
  39075. }(BABYLON.BaseTexture));
  39076. /**
  39077. * Empty line regex stored for GC.
  39078. */
  39079. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  39080. BABYLON.ColorGradingTexture = ColorGradingTexture;
  39081. })(BABYLON || (BABYLON = {}));
  39082. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  39083. var BABYLON;
  39084. (function (BABYLON) {
  39085. /**
  39086. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39087. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39088. * 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;
  39089. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39090. */
  39091. var ColorCurves = (function () {
  39092. function ColorCurves() {
  39093. this._dirty = true;
  39094. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  39095. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  39096. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39097. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  39098. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  39099. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  39100. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  39101. this._globalHue = 30;
  39102. this._globalDensity = 0;
  39103. this._globalSaturation = 0;
  39104. this._globalExposure = 0;
  39105. this._highlightsHue = 30;
  39106. this._highlightsDensity = 0;
  39107. this._highlightsSaturation = 0;
  39108. this._highlightsExposure = 0;
  39109. this._midtonesHue = 30;
  39110. this._midtonesDensity = 0;
  39111. this._midtonesSaturation = 0;
  39112. this._midtonesExposure = 0;
  39113. this._shadowsHue = 30;
  39114. this._shadowsDensity = 0;
  39115. this._shadowsSaturation = 0;
  39116. this._shadowsExposure = 0;
  39117. }
  39118. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  39119. /**
  39120. * Gets the global Hue value.
  39121. * 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).
  39122. */
  39123. get: function () {
  39124. return this._globalHue;
  39125. },
  39126. /**
  39127. * Sets the global Hue value.
  39128. * 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).
  39129. */
  39130. set: function (value) {
  39131. this._globalHue = value;
  39132. this._dirty = true;
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  39138. /**
  39139. * Gets the global Density value.
  39140. * 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.
  39141. * Values less than zero provide a filter of opposite hue.
  39142. */
  39143. get: function () {
  39144. return this._globalDensity;
  39145. },
  39146. /**
  39147. * Sets the global Density value.
  39148. * 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.
  39149. * Values less than zero provide a filter of opposite hue.
  39150. */
  39151. set: function (value) {
  39152. this._globalDensity = value;
  39153. this._dirty = true;
  39154. },
  39155. enumerable: true,
  39156. configurable: true
  39157. });
  39158. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  39159. /**
  39160. * Gets the global Saturation value.
  39161. * 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.
  39162. */
  39163. get: function () {
  39164. return this._globalSaturation;
  39165. },
  39166. /**
  39167. * Sets the global Saturation value.
  39168. * 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.
  39169. */
  39170. set: function (value) {
  39171. this._globalSaturation = value;
  39172. this._dirty = true;
  39173. },
  39174. enumerable: true,
  39175. configurable: true
  39176. });
  39177. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  39178. /**
  39179. * Gets the highlights Hue value.
  39180. * 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).
  39181. */
  39182. get: function () {
  39183. return this._highlightsHue;
  39184. },
  39185. /**
  39186. * Sets the highlights Hue value.
  39187. * 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).
  39188. */
  39189. set: function (value) {
  39190. this._highlightsHue = value;
  39191. this._dirty = true;
  39192. },
  39193. enumerable: true,
  39194. configurable: true
  39195. });
  39196. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  39197. /**
  39198. * Gets the highlights Density value.
  39199. * 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.
  39200. * Values less than zero provide a filter of opposite hue.
  39201. */
  39202. get: function () {
  39203. return this._highlightsDensity;
  39204. },
  39205. /**
  39206. * Sets the highlights Density value.
  39207. * 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.
  39208. * Values less than zero provide a filter of opposite hue.
  39209. */
  39210. set: function (value) {
  39211. this._highlightsDensity = value;
  39212. this._dirty = true;
  39213. },
  39214. enumerable: true,
  39215. configurable: true
  39216. });
  39217. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  39218. /**
  39219. * Gets the highlights Saturation value.
  39220. * 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.
  39221. */
  39222. get: function () {
  39223. return this._highlightsSaturation;
  39224. },
  39225. /**
  39226. * Sets the highlights Saturation value.
  39227. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  39228. */
  39229. set: function (value) {
  39230. this._highlightsSaturation = value;
  39231. this._dirty = true;
  39232. },
  39233. enumerable: true,
  39234. configurable: true
  39235. });
  39236. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  39237. /**
  39238. * Gets the highlights Exposure value.
  39239. * 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.
  39240. */
  39241. get: function () {
  39242. return this._highlightsExposure;
  39243. },
  39244. /**
  39245. * Sets the highlights Exposure value.
  39246. * 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.
  39247. */
  39248. set: function (value) {
  39249. this._highlightsExposure = value;
  39250. this._dirty = true;
  39251. },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  39256. /**
  39257. * Gets the midtones Hue value.
  39258. * 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).
  39259. */
  39260. get: function () {
  39261. return this._midtonesHue;
  39262. },
  39263. /**
  39264. * Sets the midtones Hue value.
  39265. * 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).
  39266. */
  39267. set: function (value) {
  39268. this._midtonesHue = value;
  39269. this._dirty = true;
  39270. },
  39271. enumerable: true,
  39272. configurable: true
  39273. });
  39274. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  39275. /**
  39276. * Gets the midtones Density value.
  39277. * 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.
  39278. * Values less than zero provide a filter of opposite hue.
  39279. */
  39280. get: function () {
  39281. return this._midtonesDensity;
  39282. },
  39283. /**
  39284. * Sets the midtones Density value.
  39285. * 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.
  39286. * Values less than zero provide a filter of opposite hue.
  39287. */
  39288. set: function (value) {
  39289. this._midtonesDensity = value;
  39290. this._dirty = true;
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  39296. /**
  39297. * Gets the midtones Saturation value.
  39298. * 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.
  39299. */
  39300. get: function () {
  39301. return this._midtonesSaturation;
  39302. },
  39303. /**
  39304. * Sets the midtones Saturation value.
  39305. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  39306. */
  39307. set: function (value) {
  39308. this._midtonesSaturation = value;
  39309. this._dirty = true;
  39310. },
  39311. enumerable: true,
  39312. configurable: true
  39313. });
  39314. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  39315. /**
  39316. * Gets the midtones Exposure value.
  39317. * 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.
  39318. */
  39319. get: function () {
  39320. return this._midtonesExposure;
  39321. },
  39322. /**
  39323. * Sets the midtones Exposure value.
  39324. * 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.
  39325. */
  39326. set: function (value) {
  39327. this._midtonesExposure = value;
  39328. this._dirty = true;
  39329. },
  39330. enumerable: true,
  39331. configurable: true
  39332. });
  39333. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  39334. /**
  39335. * Gets the shadows Hue value.
  39336. * 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).
  39337. */
  39338. get: function () {
  39339. return this._shadowsHue;
  39340. },
  39341. /**
  39342. * Sets the shadows Hue value.
  39343. * 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).
  39344. */
  39345. set: function (value) {
  39346. this._shadowsHue = value;
  39347. this._dirty = true;
  39348. },
  39349. enumerable: true,
  39350. configurable: true
  39351. });
  39352. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  39353. /**
  39354. * Gets the shadows Density value.
  39355. * 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.
  39356. * Values less than zero provide a filter of opposite hue.
  39357. */
  39358. get: function () {
  39359. return this._shadowsDensity;
  39360. },
  39361. /**
  39362. * Sets the shadows Density value.
  39363. * 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.
  39364. * Values less than zero provide a filter of opposite hue.
  39365. */
  39366. set: function (value) {
  39367. this._shadowsDensity = value;
  39368. this._dirty = true;
  39369. },
  39370. enumerable: true,
  39371. configurable: true
  39372. });
  39373. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  39374. /**
  39375. * Gets the shadows Saturation value.
  39376. * 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.
  39377. */
  39378. get: function () {
  39379. return this._shadowsSaturation;
  39380. },
  39381. /**
  39382. * Sets the shadows Saturation value.
  39383. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  39384. */
  39385. set: function (value) {
  39386. this._shadowsSaturation = value;
  39387. this._dirty = true;
  39388. },
  39389. enumerable: true,
  39390. configurable: true
  39391. });
  39392. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  39393. /**
  39394. * Gets the shadows Exposure value.
  39395. * 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.
  39396. */
  39397. get: function () {
  39398. return this._shadowsExposure;
  39399. },
  39400. /**
  39401. * Sets the shadows Exposure value.
  39402. * 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.
  39403. */
  39404. set: function (value) {
  39405. this._shadowsExposure = value;
  39406. this._dirty = true;
  39407. },
  39408. enumerable: true,
  39409. configurable: true
  39410. });
  39411. /**
  39412. * Binds the color curves to the shader.
  39413. * @param colorCurves The color curve to bind
  39414. * @param effect The effect to bind to
  39415. */
  39416. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  39417. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  39418. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  39419. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  39420. if (colorCurves._dirty) {
  39421. colorCurves._dirty = false;
  39422. // Fill in global info.
  39423. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  39424. // Compute highlights info.
  39425. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  39426. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  39427. // Compute midtones info.
  39428. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  39429. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  39430. // Compute shadows info.
  39431. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  39432. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  39433. // Compute deltas (neutral is midtones).
  39434. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  39435. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  39436. }
  39437. if (effect) {
  39438. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  39439. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  39440. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  39441. }
  39442. };
  39443. /**
  39444. * Prepare the list of uniforms associated with the ColorCurves effects.
  39445. * @param uniformsList The list of uniforms used in the effect
  39446. */
  39447. ColorCurves.PrepareUniforms = function (uniformsList) {
  39448. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  39449. };
  39450. /**
  39451. * Returns color grading data based on a hue, density, saturation and exposure value.
  39452. * @param filterHue The hue of the color filter.
  39453. * @param filterDensity The density of the color filter.
  39454. * @param saturation The saturation.
  39455. * @param exposure The exposure.
  39456. * @param result The result data container.
  39457. */
  39458. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  39459. if (hue == null) {
  39460. return;
  39461. }
  39462. hue = ColorCurves.clamp(hue, 0, 360);
  39463. density = ColorCurves.clamp(density, -100, 100);
  39464. saturation = ColorCurves.clamp(saturation, -100, 100);
  39465. exposure = ColorCurves.clamp(exposure, -100, 100);
  39466. // Remap the slider/config filter density with non-linear mapping and also scale by half
  39467. // so that the maximum filter density is only 50% control. This provides fine control
  39468. // for small values and reasonable range.
  39469. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  39470. density *= 0.5;
  39471. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  39472. if (density < 0) {
  39473. density *= -1;
  39474. hue = (hue + 180) % 360;
  39475. }
  39476. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  39477. result.scaleToRef(2, result);
  39478. result.a = 1 + 0.01 * saturation;
  39479. };
  39480. /**
  39481. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  39482. * @param value The input slider value in range [-100,100].
  39483. * @returns Adjusted value.
  39484. */
  39485. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  39486. value /= 100;
  39487. var x = Math.abs(value);
  39488. x = Math.pow(x, 2);
  39489. if (value < 0) {
  39490. x *= -1;
  39491. }
  39492. x *= 100;
  39493. return x;
  39494. };
  39495. /**
  39496. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  39497. * @param hue The hue (H) input.
  39498. * @param saturation The saturation (S) input.
  39499. * @param brightness The brightness (B) input.
  39500. * @result An RGBA color represented as Vector4.
  39501. */
  39502. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  39503. var h = ColorCurves.clamp(hue, 0, 360);
  39504. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  39505. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  39506. if (s === 0) {
  39507. result.r = v;
  39508. result.g = v;
  39509. result.b = v;
  39510. }
  39511. else {
  39512. // sector 0 to 5
  39513. h /= 60;
  39514. var i = Math.floor(h);
  39515. // fractional part of h
  39516. var f = h - i;
  39517. var p = v * (1 - s);
  39518. var q = v * (1 - s * f);
  39519. var t = v * (1 - s * (1 - f));
  39520. switch (i) {
  39521. case 0:
  39522. result.r = v;
  39523. result.g = t;
  39524. result.b = p;
  39525. break;
  39526. case 1:
  39527. result.r = q;
  39528. result.g = v;
  39529. result.b = p;
  39530. break;
  39531. case 2:
  39532. result.r = p;
  39533. result.g = v;
  39534. result.b = t;
  39535. break;
  39536. case 3:
  39537. result.r = p;
  39538. result.g = q;
  39539. result.b = v;
  39540. break;
  39541. case 4:
  39542. result.r = t;
  39543. result.g = p;
  39544. result.b = v;
  39545. break;
  39546. default:
  39547. result.r = v;
  39548. result.g = p;
  39549. result.b = q;
  39550. break;
  39551. }
  39552. }
  39553. result.a = 1;
  39554. };
  39555. /**
  39556. * Returns a value clamped between min and max
  39557. * @param value The value to clamp
  39558. * @param min The minimum of value
  39559. * @param max The maximum of value
  39560. * @returns The clamped value.
  39561. */
  39562. ColorCurves.clamp = function (value, min, max) {
  39563. return Math.min(Math.max(value, min), max);
  39564. };
  39565. /**
  39566. * Clones the current color curve instance.
  39567. * @return The cloned curves
  39568. */
  39569. ColorCurves.prototype.clone = function () {
  39570. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39571. };
  39572. /**
  39573. * Serializes the current color curve instance to a json representation.
  39574. * @return a JSON representation
  39575. */
  39576. ColorCurves.prototype.serialize = function () {
  39577. return BABYLON.SerializationHelper.Serialize(this);
  39578. };
  39579. /**
  39580. * Parses the color curve from a json representation.
  39581. * @param source the JSON source to parse
  39582. * @return The parsed curves
  39583. */
  39584. ColorCurves.Parse = function (source) {
  39585. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39586. };
  39587. return ColorCurves;
  39588. }());
  39589. __decorate([
  39590. BABYLON.serialize()
  39591. ], ColorCurves.prototype, "_globalHue", void 0);
  39592. __decorate([
  39593. BABYLON.serialize()
  39594. ], ColorCurves.prototype, "_globalDensity", void 0);
  39595. __decorate([
  39596. BABYLON.serialize()
  39597. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39598. __decorate([
  39599. BABYLON.serialize()
  39600. ], ColorCurves.prototype, "_globalExposure", void 0);
  39601. __decorate([
  39602. BABYLON.serialize()
  39603. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39604. __decorate([
  39605. BABYLON.serialize()
  39606. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39607. __decorate([
  39608. BABYLON.serialize()
  39609. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39610. __decorate([
  39611. BABYLON.serialize()
  39612. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39613. __decorate([
  39614. BABYLON.serialize()
  39615. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39616. __decorate([
  39617. BABYLON.serialize()
  39618. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39619. __decorate([
  39620. BABYLON.serialize()
  39621. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39622. __decorate([
  39623. BABYLON.serialize()
  39624. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39625. BABYLON.ColorCurves = ColorCurves;
  39626. })(BABYLON || (BABYLON = {}));
  39627. //# sourceMappingURL=babylon.colorCurves.js.map
  39628. var BABYLON;
  39629. (function (BABYLON) {
  39630. var PostProcessRenderPipelineManager = (function () {
  39631. function PostProcessRenderPipelineManager() {
  39632. this._renderPipelines = {};
  39633. }
  39634. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39635. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39636. };
  39637. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39638. var renderPipeline = this._renderPipelines[renderPipelineName];
  39639. if (!renderPipeline) {
  39640. return;
  39641. }
  39642. renderPipeline._attachCameras(cameras, unique);
  39643. };
  39644. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39645. var renderPipeline = this._renderPipelines[renderPipelineName];
  39646. if (!renderPipeline) {
  39647. return;
  39648. }
  39649. renderPipeline._detachCameras(cameras);
  39650. };
  39651. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39652. var renderPipeline = this._renderPipelines[renderPipelineName];
  39653. if (!renderPipeline) {
  39654. return;
  39655. }
  39656. renderPipeline._enableEffect(renderEffectName, cameras);
  39657. };
  39658. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39659. var renderPipeline = this._renderPipelines[renderPipelineName];
  39660. if (!renderPipeline) {
  39661. return;
  39662. }
  39663. renderPipeline._disableEffect(renderEffectName, cameras);
  39664. };
  39665. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39666. var renderPipeline = this._renderPipelines[renderPipelineName];
  39667. if (!renderPipeline) {
  39668. return;
  39669. }
  39670. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39671. };
  39672. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39673. var renderPipeline = this._renderPipelines[renderPipelineName];
  39674. if (!renderPipeline) {
  39675. return;
  39676. }
  39677. renderPipeline._disableDisplayOnlyPass(cameras);
  39678. };
  39679. PostProcessRenderPipelineManager.prototype.update = function () {
  39680. for (var renderPipelineName in this._renderPipelines) {
  39681. var pipeline = this._renderPipelines[renderPipelineName];
  39682. if (!pipeline.isSupported) {
  39683. pipeline.dispose();
  39684. delete this._renderPipelines[renderPipelineName];
  39685. }
  39686. else {
  39687. pipeline._update();
  39688. }
  39689. }
  39690. };
  39691. return PostProcessRenderPipelineManager;
  39692. }());
  39693. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39694. })(BABYLON || (BABYLON = {}));
  39695. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39696. var BABYLON;
  39697. (function (BABYLON) {
  39698. var PostProcessRenderPass = (function () {
  39699. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39700. this._enabled = true;
  39701. this._refCount = 0;
  39702. this._name = name;
  39703. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39704. this.setRenderList(renderList);
  39705. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39706. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39707. this._scene = scene;
  39708. this._renderList = renderList;
  39709. }
  39710. // private
  39711. PostProcessRenderPass.prototype._incRefCount = function () {
  39712. if (this._refCount === 0) {
  39713. this._scene.customRenderTargets.push(this._renderTexture);
  39714. }
  39715. return ++this._refCount;
  39716. };
  39717. PostProcessRenderPass.prototype._decRefCount = function () {
  39718. this._refCount--;
  39719. if (this._refCount <= 0) {
  39720. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39721. }
  39722. return this._refCount;
  39723. };
  39724. PostProcessRenderPass.prototype._update = function () {
  39725. this.setRenderList(this._renderList);
  39726. };
  39727. // public
  39728. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39729. this._renderTexture.renderList = renderList;
  39730. };
  39731. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39732. return this._renderTexture;
  39733. };
  39734. return PostProcessRenderPass;
  39735. }());
  39736. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39737. })(BABYLON || (BABYLON = {}));
  39738. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39739. var BABYLON;
  39740. (function (BABYLON) {
  39741. var PostProcessRenderEffect = (function () {
  39742. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39743. this._engine = engine;
  39744. this._name = name;
  39745. this._singleInstance = singleInstance || true;
  39746. this._getPostProcess = getPostProcess;
  39747. this._cameras = [];
  39748. this._indicesForCamera = [];
  39749. this._postProcesses = {};
  39750. this._renderPasses = {};
  39751. this._renderEffectAsPasses = {};
  39752. }
  39753. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39754. get: function () {
  39755. for (var index in this._postProcesses) {
  39756. if (!this._postProcesses[index].isSupported) {
  39757. return false;
  39758. }
  39759. }
  39760. return true;
  39761. },
  39762. enumerable: true,
  39763. configurable: true
  39764. });
  39765. PostProcessRenderEffect.prototype._update = function () {
  39766. for (var renderPassName in this._renderPasses) {
  39767. this._renderPasses[renderPassName]._update();
  39768. }
  39769. };
  39770. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39771. this._renderPasses[renderPass._name] = renderPass;
  39772. this._linkParameters();
  39773. };
  39774. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39775. delete this._renderPasses[renderPass._name];
  39776. this._linkParameters();
  39777. };
  39778. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39779. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39780. this._linkParameters();
  39781. };
  39782. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39783. for (var renderPassName in this._renderPasses) {
  39784. if (renderPassName === passName) {
  39785. return this._renderPasses[passName];
  39786. }
  39787. }
  39788. };
  39789. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39790. this._renderPasses = {};
  39791. this._linkParameters();
  39792. };
  39793. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39794. var cameraKey;
  39795. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39796. for (var i = 0; i < _cam.length; i++) {
  39797. var camera = _cam[i];
  39798. var cameraName = camera.name;
  39799. if (this._singleInstance) {
  39800. cameraKey = 0;
  39801. }
  39802. else {
  39803. cameraKey = cameraName;
  39804. }
  39805. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39806. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39807. if (!this._indicesForCamera[cameraName]) {
  39808. this._indicesForCamera[cameraName] = [];
  39809. }
  39810. this._indicesForCamera[cameraName].push(index);
  39811. if (this._cameras.indexOf(camera) === -1) {
  39812. this._cameras[cameraName] = camera;
  39813. }
  39814. for (var passName in this._renderPasses) {
  39815. this._renderPasses[passName]._incRefCount();
  39816. }
  39817. }
  39818. this._linkParameters();
  39819. };
  39820. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39821. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39822. for (var i = 0; i < _cam.length; i++) {
  39823. var camera = _cam[i];
  39824. var cameraName = camera.name;
  39825. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39826. var index = this._cameras.indexOf(cameraName);
  39827. this._indicesForCamera.splice(index, 1);
  39828. this._cameras.splice(index, 1);
  39829. for (var passName in this._renderPasses) {
  39830. this._renderPasses[passName]._decRefCount();
  39831. }
  39832. }
  39833. };
  39834. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39835. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39836. for (var i = 0; i < _cam.length; i++) {
  39837. var camera = _cam[i];
  39838. var cameraName = camera.name;
  39839. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39840. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39841. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39842. }
  39843. }
  39844. for (var passName in this._renderPasses) {
  39845. this._renderPasses[passName]._incRefCount();
  39846. }
  39847. }
  39848. };
  39849. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39850. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39851. for (var i = 0; i < _cam.length; i++) {
  39852. var camera = _cam[i];
  39853. var cameraName = camera.Name;
  39854. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39855. for (var passName in this._renderPasses) {
  39856. this._renderPasses[passName]._decRefCount();
  39857. }
  39858. }
  39859. };
  39860. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39861. if (this._singleInstance) {
  39862. return this._postProcesses[0];
  39863. }
  39864. else {
  39865. return this._postProcesses[camera.name];
  39866. }
  39867. };
  39868. PostProcessRenderEffect.prototype._linkParameters = function () {
  39869. var _this = this;
  39870. for (var index in this._postProcesses) {
  39871. if (this.applyParameters) {
  39872. this.applyParameters(this._postProcesses[index]);
  39873. }
  39874. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39875. _this._linkTextures(effect);
  39876. });
  39877. }
  39878. };
  39879. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39880. for (var renderPassName in this._renderPasses) {
  39881. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39882. }
  39883. for (var renderEffectName in this._renderEffectAsPasses) {
  39884. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39885. }
  39886. };
  39887. return PostProcessRenderEffect;
  39888. }());
  39889. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39890. })(BABYLON || (BABYLON = {}));
  39891. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39892. var BABYLON;
  39893. (function (BABYLON) {
  39894. var PostProcessRenderPipeline = (function () {
  39895. function PostProcessRenderPipeline(engine, name) {
  39896. this._engine = engine;
  39897. this._name = name;
  39898. this._renderEffects = new Array();
  39899. this._renderEffectsForIsolatedPass = new Array();
  39900. this._cameras = [];
  39901. }
  39902. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39903. get: function () {
  39904. for (var renderEffectName in this._renderEffects) {
  39905. if (!this._renderEffects[renderEffectName].isSupported) {
  39906. return false;
  39907. }
  39908. }
  39909. return true;
  39910. },
  39911. enumerable: true,
  39912. configurable: true
  39913. });
  39914. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39915. this._renderEffects[renderEffect._name] = renderEffect;
  39916. };
  39917. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39918. var renderEffects = this._renderEffects[renderEffectName];
  39919. if (!renderEffects) {
  39920. return;
  39921. }
  39922. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39923. };
  39924. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39925. var renderEffects = this._renderEffects[renderEffectName];
  39926. if (!renderEffects) {
  39927. return;
  39928. }
  39929. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39930. };
  39931. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39932. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39933. var indicesToDelete = [];
  39934. var i;
  39935. for (i = 0; i < _cam.length; i++) {
  39936. var camera = _cam[i];
  39937. var cameraName = camera.name;
  39938. if (this._cameras.indexOf(camera) === -1) {
  39939. this._cameras[cameraName] = camera;
  39940. }
  39941. else if (unique) {
  39942. indicesToDelete.push(i);
  39943. }
  39944. }
  39945. for (i = 0; i < indicesToDelete.length; i++) {
  39946. cameras.splice(indicesToDelete[i], 1);
  39947. }
  39948. for (var renderEffectName in this._renderEffects) {
  39949. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39950. }
  39951. };
  39952. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39953. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39954. for (var renderEffectName in this._renderEffects) {
  39955. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39956. }
  39957. for (var i = 0; i < _cam.length; i++) {
  39958. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39959. }
  39960. };
  39961. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39962. var _this = this;
  39963. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39964. var pass = null;
  39965. var renderEffectName;
  39966. for (renderEffectName in this._renderEffects) {
  39967. pass = this._renderEffects[renderEffectName].getPass(passName);
  39968. if (pass != null) {
  39969. break;
  39970. }
  39971. }
  39972. if (pass === null) {
  39973. return;
  39974. }
  39975. for (renderEffectName in this._renderEffects) {
  39976. this._renderEffects[renderEffectName]._disable(_cam);
  39977. }
  39978. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39979. for (var i = 0; i < _cam.length; i++) {
  39980. var camera = _cam[i];
  39981. var cameraName = camera.name;
  39982. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  39983. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39984. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39985. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39986. }
  39987. };
  39988. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39989. var _this = this;
  39990. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39991. for (var i = 0; i < _cam.length; i++) {
  39992. var camera = _cam[i];
  39993. var cameraName = camera.name;
  39994. 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); });
  39995. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39996. }
  39997. for (var renderEffectName in this._renderEffects) {
  39998. this._renderEffects[renderEffectName]._enable(_cam);
  39999. }
  40000. };
  40001. PostProcessRenderPipeline.prototype._update = function () {
  40002. for (var renderEffectName in this._renderEffects) {
  40003. this._renderEffects[renderEffectName]._update();
  40004. }
  40005. for (var i = 0; i < this._cameras.length; i++) {
  40006. var cameraName = this._cameras[i].name;
  40007. if (this._renderEffectsForIsolatedPass[cameraName]) {
  40008. this._renderEffectsForIsolatedPass[cameraName]._update();
  40009. }
  40010. }
  40011. };
  40012. PostProcessRenderPipeline.prototype._reset = function () {
  40013. this._renderEffects = new Array();
  40014. this._renderEffectsForIsolatedPass = new Array();
  40015. };
  40016. PostProcessRenderPipeline.prototype.dispose = function () {
  40017. // Must be implemented by children
  40018. };
  40019. return PostProcessRenderPipeline;
  40020. }());
  40021. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  40022. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  40023. __decorate([
  40024. BABYLON.serialize()
  40025. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  40026. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  40027. })(BABYLON || (BABYLON = {}));
  40028. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  40029. var BABYLON;
  40030. (function (BABYLON) {
  40031. var DefaultRenderingPipeline = (function (_super) {
  40032. __extends(DefaultRenderingPipeline, _super);
  40033. /**
  40034. * @constructor
  40035. * @param {string} name - The rendering pipeline name
  40036. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40037. * @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)
  40038. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40039. */
  40040. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  40041. var _this = _super.call(this, scene.getEngine(), name) || this;
  40042. _this.PassPostProcessId = "PassPostProcessEffect";
  40043. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  40044. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  40045. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  40046. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  40047. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  40048. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  40049. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  40050. // IAnimatable
  40051. _this.animations = [];
  40052. // Values
  40053. _this._bloomEnabled = false;
  40054. _this._fxaaEnabled = false;
  40055. _this._imageProcessingEnabled = true;
  40056. _this._bloomScale = 0.6;
  40057. /**
  40058. * Specifies the size of the bloom blur kernel, relative to the final output size
  40059. */
  40060. _this.bloomKernel = 64;
  40061. /**
  40062. * Specifies the weight of the bloom in the final rendering
  40063. */
  40064. _this._bloomWeight = 0.15;
  40065. _this._cameras = cameras || [];
  40066. // Initialize
  40067. _this._scene = scene;
  40068. var caps = _this._scene.getEngine().getCaps();
  40069. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  40070. // Misc
  40071. if (_this._hdr) {
  40072. if (caps.textureHalfFloatRender) {
  40073. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  40074. }
  40075. else if (caps.textureFloatRender) {
  40076. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  40077. }
  40078. }
  40079. else {
  40080. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  40081. }
  40082. // Attach
  40083. scene.postProcessRenderPipelineManager.addPipeline(_this);
  40084. _this._buildPipeline();
  40085. return _this;
  40086. }
  40087. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  40088. get: function () {
  40089. return this._bloomWeight;
  40090. },
  40091. set: function (value) {
  40092. if (this._bloomWeight === value) {
  40093. return;
  40094. }
  40095. this._bloomWeight = value;
  40096. if (this._hdr && this.copyBack) {
  40097. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  40098. }
  40099. },
  40100. enumerable: true,
  40101. configurable: true
  40102. });
  40103. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  40104. get: function () {
  40105. return this._bloomScale;
  40106. },
  40107. set: function (value) {
  40108. if (this._bloomScale === value) {
  40109. return;
  40110. }
  40111. this._bloomScale = value;
  40112. this._buildPipeline();
  40113. },
  40114. enumerable: true,
  40115. configurable: true
  40116. });
  40117. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  40118. get: function () {
  40119. return this._bloomEnabled;
  40120. },
  40121. set: function (enabled) {
  40122. if (this._bloomEnabled === enabled) {
  40123. return;
  40124. }
  40125. this._bloomEnabled = enabled;
  40126. this._buildPipeline();
  40127. },
  40128. enumerable: true,
  40129. configurable: true
  40130. });
  40131. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  40132. get: function () {
  40133. return this._fxaaEnabled;
  40134. },
  40135. set: function (enabled) {
  40136. if (this._fxaaEnabled === enabled) {
  40137. return;
  40138. }
  40139. this._fxaaEnabled = enabled;
  40140. this._buildPipeline();
  40141. },
  40142. enumerable: true,
  40143. configurable: true
  40144. });
  40145. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  40146. get: function () {
  40147. return this._imageProcessingEnabled;
  40148. },
  40149. set: function (enabled) {
  40150. if (this._imageProcessingEnabled === enabled) {
  40151. return;
  40152. }
  40153. this._imageProcessingEnabled = enabled;
  40154. this._buildPipeline();
  40155. },
  40156. enumerable: true,
  40157. configurable: true
  40158. });
  40159. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  40160. var _this = this;
  40161. var engine = this._scene.getEngine();
  40162. this._disposePostProcesses();
  40163. this._reset();
  40164. if (this.bloomEnabled) {
  40165. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40166. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  40167. if (!this._hdr) {
  40168. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40169. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  40170. this.highlights.autoClear = false;
  40171. this.highlights.alwaysForcePOT = true;
  40172. }
  40173. 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);
  40174. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  40175. this.blurX.alwaysForcePOT = true;
  40176. this.blurX.autoClear = false;
  40177. this.blurX.onActivateObservable.add(function () {
  40178. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  40179. _this.blurX.kernel = _this.bloomKernel * dw;
  40180. });
  40181. 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);
  40182. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  40183. this.blurY.alwaysForcePOT = true;
  40184. this.blurY.autoClear = false;
  40185. this.blurY.onActivateObservable.add(function () {
  40186. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  40187. _this.blurY.kernel = _this.bloomKernel * dh;
  40188. });
  40189. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40190. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  40191. this.copyBack.alwaysForcePOT = true;
  40192. if (this._hdr) {
  40193. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  40194. var w = this.bloomWeight;
  40195. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  40196. }
  40197. else {
  40198. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  40199. }
  40200. this.copyBack.autoClear = false;
  40201. }
  40202. if (this._imageProcessingEnabled) {
  40203. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40204. if (this._hdr) {
  40205. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  40206. }
  40207. }
  40208. if (this.fxaaEnabled) {
  40209. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40210. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  40211. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40212. }
  40213. else {
  40214. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  40215. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  40216. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  40217. }
  40218. if (this.bloomEnabled) {
  40219. if (this._hdr) {
  40220. this.copyBack.shareOutputWith(this.blurX);
  40221. if (this.imageProcessing) {
  40222. this.imageProcessing.shareOutputWith(this.pass);
  40223. this.imageProcessing.autoClear = false;
  40224. }
  40225. else if (this.fxaa) {
  40226. this.fxaa.shareOutputWith(this.pass);
  40227. }
  40228. else {
  40229. this.finalMerge.shareOutputWith(this.pass);
  40230. }
  40231. }
  40232. else {
  40233. if (this.fxaa) {
  40234. this.fxaa.shareOutputWith(this.pass);
  40235. }
  40236. else {
  40237. this.finalMerge.shareOutputWith(this.pass);
  40238. }
  40239. }
  40240. }
  40241. if (this._cameras !== null) {
  40242. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  40243. }
  40244. };
  40245. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  40246. for (var i = 0; i < this._cameras.length; i++) {
  40247. var camera = this._cameras[i];
  40248. if (this.pass) {
  40249. this.pass.dispose(camera);
  40250. }
  40251. if (this.highlights) {
  40252. this.highlights.dispose(camera);
  40253. }
  40254. if (this.blurX) {
  40255. this.blurX.dispose(camera);
  40256. }
  40257. if (this.blurY) {
  40258. this.blurY.dispose(camera);
  40259. }
  40260. if (this.copyBack) {
  40261. this.copyBack.dispose(camera);
  40262. }
  40263. if (this.imageProcessing) {
  40264. this.imageProcessing.dispose(camera);
  40265. }
  40266. if (this.fxaa) {
  40267. this.fxaa.dispose(camera);
  40268. }
  40269. if (this.finalMerge) {
  40270. this.finalMerge.dispose(camera);
  40271. }
  40272. }
  40273. this.pass = null;
  40274. this.highlights = null;
  40275. this.blurX = null;
  40276. this.blurY = null;
  40277. this.copyBack = null;
  40278. this.imageProcessing = null;
  40279. this.fxaa = null;
  40280. this.finalMerge = null;
  40281. };
  40282. // Dispose
  40283. DefaultRenderingPipeline.prototype.dispose = function () {
  40284. this._disposePostProcesses();
  40285. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  40286. _super.prototype.dispose.call(this);
  40287. };
  40288. // Serialize rendering pipeline
  40289. DefaultRenderingPipeline.prototype.serialize = function () {
  40290. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40291. serializationObject.customType = "DefaultRenderingPipeline";
  40292. return serializationObject;
  40293. };
  40294. // Parse serialized pipeline
  40295. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  40296. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  40297. };
  40298. return DefaultRenderingPipeline;
  40299. }(BABYLON.PostProcessRenderPipeline));
  40300. __decorate([
  40301. BABYLON.serialize()
  40302. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  40303. __decorate([
  40304. BABYLON.serialize()
  40305. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  40306. __decorate([
  40307. BABYLON.serialize()
  40308. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  40309. __decorate([
  40310. BABYLON.serialize()
  40311. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  40312. __decorate([
  40313. BABYLON.serialize()
  40314. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  40315. __decorate([
  40316. BABYLON.serialize()
  40317. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  40318. __decorate([
  40319. BABYLON.serialize()
  40320. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  40321. __decorate([
  40322. BABYLON.serialize()
  40323. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  40324. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  40325. })(BABYLON || (BABYLON = {}));
  40326. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  40327. var BABYLON;
  40328. (function (BABYLON) {
  40329. /**
  40330. * This groups together the common properties used for image processing either in direct forward pass
  40331. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40332. * or not.
  40333. */
  40334. var ImageProcessingConfiguration = (function () {
  40335. function ImageProcessingConfiguration() {
  40336. /**
  40337. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40338. */
  40339. this.colorCurves = new BABYLON.ColorCurves();
  40340. this._colorCurvesEnabled = false;
  40341. this._colorGradingEnabled = false;
  40342. this._colorGradingWithGreenDepth = false;
  40343. this._colorGradingBGR = false;
  40344. this._exposure = 1.0;
  40345. this._toneMappingEnabled = false;
  40346. this._contrast = 1.0;
  40347. /**
  40348. * Vignette stretch size.
  40349. */
  40350. this.vignetteStretch = 0;
  40351. /**
  40352. * Vignette centre X Offset.
  40353. */
  40354. this.vignetteCentreX = 0;
  40355. /**
  40356. * Vignette centre Y Offset.
  40357. */
  40358. this.vignetteCentreY = 0;
  40359. /**
  40360. * Vignette weight or intensity of the vignette effect.
  40361. */
  40362. this.vignetteWeight = 1.5;
  40363. /**
  40364. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40365. * if vignetteEnabled is set to true.
  40366. */
  40367. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40368. /**
  40369. * Camera field of view used by the Vignette effect.
  40370. */
  40371. this.vignetteCameraFov = 0.5;
  40372. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40373. this._vignetteEnabled = false;
  40374. this._applyByPostProcess = false;
  40375. /**
  40376. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40377. * @type {BABYLON.Observable}
  40378. */
  40379. this.onUpdateParameters = new BABYLON.Observable();
  40380. }
  40381. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40382. /**
  40383. * Gets wether the color curves effect is enabled.
  40384. */
  40385. get: function () {
  40386. return this._colorCurvesEnabled;
  40387. },
  40388. /**
  40389. * Sets wether the color curves effect is enabled.
  40390. */
  40391. set: function (value) {
  40392. if (this._colorCurvesEnabled === value) {
  40393. return;
  40394. }
  40395. this._colorCurvesEnabled = value;
  40396. this._updateParameters();
  40397. },
  40398. enumerable: true,
  40399. configurable: true
  40400. });
  40401. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40402. /**
  40403. * Gets wether the color grading effect is enabled.
  40404. */
  40405. get: function () {
  40406. return this._colorGradingEnabled;
  40407. },
  40408. /**
  40409. * Sets wether the color grading effect is enabled.
  40410. */
  40411. set: function (value) {
  40412. if (this._colorGradingEnabled === value) {
  40413. return;
  40414. }
  40415. this._colorGradingEnabled = value;
  40416. this._updateParameters();
  40417. },
  40418. enumerable: true,
  40419. configurable: true
  40420. });
  40421. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40422. /**
  40423. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40424. */
  40425. get: function () {
  40426. return this._colorGradingWithGreenDepth;
  40427. },
  40428. /**
  40429. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40430. */
  40431. set: function (value) {
  40432. if (this._colorGradingWithGreenDepth === value) {
  40433. return;
  40434. }
  40435. this._colorGradingWithGreenDepth = value;
  40436. this._updateParameters();
  40437. },
  40438. enumerable: true,
  40439. configurable: true
  40440. });
  40441. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40442. /**
  40443. * Gets wether the color grading texture contains BGR values.
  40444. */
  40445. get: function () {
  40446. return this._colorGradingBGR;
  40447. },
  40448. /**
  40449. * Sets wether the color grading texture contains BGR values.
  40450. */
  40451. set: function (value) {
  40452. if (this._colorGradingBGR === value) {
  40453. return;
  40454. }
  40455. this._colorGradingBGR = value;
  40456. this._updateParameters();
  40457. },
  40458. enumerable: true,
  40459. configurable: true
  40460. });
  40461. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40462. /**
  40463. * Gets the Exposure used in the effect.
  40464. */
  40465. get: function () {
  40466. return this._exposure;
  40467. },
  40468. /**
  40469. * Sets the Exposure used in the effect.
  40470. */
  40471. set: function (value) {
  40472. if (this._exposure === value) {
  40473. return;
  40474. }
  40475. this._exposure = value;
  40476. this._updateParameters();
  40477. },
  40478. enumerable: true,
  40479. configurable: true
  40480. });
  40481. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40482. /**
  40483. * Gets wether the tone mapping effect is enabled.
  40484. */
  40485. get: function () {
  40486. return this._toneMappingEnabled;
  40487. },
  40488. /**
  40489. * Sets wether the tone mapping effect is enabled.
  40490. */
  40491. set: function (value) {
  40492. if (this._toneMappingEnabled === value) {
  40493. return;
  40494. }
  40495. this._toneMappingEnabled = value;
  40496. this._updateParameters();
  40497. },
  40498. enumerable: true,
  40499. configurable: true
  40500. });
  40501. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40502. /**
  40503. * Gets the contrast used in the effect.
  40504. */
  40505. get: function () {
  40506. return this._contrast;
  40507. },
  40508. /**
  40509. * Sets the contrast used in the effect.
  40510. */
  40511. set: function (value) {
  40512. if (this._contrast === value) {
  40513. return;
  40514. }
  40515. this._contrast = value;
  40516. this._updateParameters();
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40522. /**
  40523. * Gets the vignette blend mode allowing different kind of effect.
  40524. */
  40525. get: function () {
  40526. return this._vignetteBlendMode;
  40527. },
  40528. /**
  40529. * Sets the vignette blend mode allowing different kind of effect.
  40530. */
  40531. set: function (value) {
  40532. if (this._vignetteBlendMode === value) {
  40533. return;
  40534. }
  40535. this._vignetteBlendMode = value;
  40536. this._updateParameters();
  40537. },
  40538. enumerable: true,
  40539. configurable: true
  40540. });
  40541. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40542. /**
  40543. * Gets wether the vignette effect is enabled.
  40544. */
  40545. get: function () {
  40546. return this._vignetteEnabled;
  40547. },
  40548. /**
  40549. * Sets wether the vignette effect is enabled.
  40550. */
  40551. set: function (value) {
  40552. if (this._vignetteEnabled === value) {
  40553. return;
  40554. }
  40555. this._vignetteEnabled = value;
  40556. this._updateParameters();
  40557. },
  40558. enumerable: true,
  40559. configurable: true
  40560. });
  40561. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40562. /**
  40563. * Gets wether the image processing is applied through a post process or not.
  40564. */
  40565. get: function () {
  40566. return this._applyByPostProcess;
  40567. },
  40568. /**
  40569. * Sets wether the image processing is applied through a post process or not.
  40570. */
  40571. set: function (value) {
  40572. if (this._applyByPostProcess === value) {
  40573. return;
  40574. }
  40575. this._applyByPostProcess = value;
  40576. this._updateParameters();
  40577. },
  40578. enumerable: true,
  40579. configurable: true
  40580. });
  40581. /**
  40582. * Method called each time the image processing information changes requires to recompile the effect.
  40583. */
  40584. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40585. this.onUpdateParameters.notifyObservers(this);
  40586. };
  40587. /**
  40588. * Prepare the list of uniforms associated with the Image Processing effects.
  40589. * @param uniformsList The list of uniforms used in the effect
  40590. * @param defines the list of defines currently in use
  40591. */
  40592. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40593. if (defines.EXPOSURE) {
  40594. uniforms.push("exposureLinear");
  40595. }
  40596. if (defines.CONTRAST) {
  40597. uniforms.push("contrast");
  40598. }
  40599. if (defines.COLORGRADING) {
  40600. uniforms.push("colorTransformSettings");
  40601. }
  40602. if (defines.VIGNETTE) {
  40603. uniforms.push("vInverseScreenSize");
  40604. uniforms.push("vignetteSettings1");
  40605. uniforms.push("vignetteSettings2");
  40606. }
  40607. if (defines.COLORCURVES) {
  40608. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40609. }
  40610. };
  40611. /**
  40612. * Prepare the list of samplers associated with the Image Processing effects.
  40613. * @param uniformsList The list of uniforms used in the effect
  40614. * @param defines the list of defines currently in use
  40615. */
  40616. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40617. if (defines.COLORGRADING) {
  40618. samplersList.push("txColorTransform");
  40619. }
  40620. };
  40621. /**
  40622. * Prepare the list of defines associated to the shader.
  40623. * @param defines the list of defines to complete
  40624. */
  40625. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  40626. defines.VIGNETTE = this.vignetteEnabled;
  40627. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40628. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40629. defines.TONEMAPPING = this.toneMappingEnabled;
  40630. defines.CONTRAST = (this.contrast !== 1.0);
  40631. defines.EXPOSURE = (this.exposure !== 1.0);
  40632. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40633. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40634. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40635. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40636. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40637. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40638. };
  40639. /**
  40640. * Returns true if all the image processing information are ready.
  40641. */
  40642. ImageProcessingConfiguration.prototype.isReady = function () {
  40643. // Color Grading texure can not be none blocking.
  40644. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40645. };
  40646. /**
  40647. * Binds the image processing to the shader.
  40648. * @param effect The effect to bind to
  40649. */
  40650. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40651. if (aspectRatio === void 0) { aspectRatio = 1; }
  40652. // Color Curves
  40653. if (this._colorCurvesEnabled) {
  40654. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40655. }
  40656. // Vignette
  40657. if (this._vignetteEnabled) {
  40658. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40659. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40660. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40661. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40662. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40663. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40664. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40665. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40666. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40667. var vignettePower = -2.0 * this.vignetteWeight;
  40668. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40669. }
  40670. // Exposure
  40671. effect.setFloat("exposureLinear", this.exposure);
  40672. // Contrast
  40673. effect.setFloat("contrast", this.contrast);
  40674. // Color transform settings
  40675. if (this.colorGradingTexture) {
  40676. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40677. var textureSize = this.colorGradingTexture.getSize().height;
  40678. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40679. 0.5 / textureSize, // textureOffset
  40680. textureSize, // textureSize
  40681. this.colorGradingTexture.level // weight
  40682. );
  40683. }
  40684. };
  40685. /**
  40686. * Clones the current image processing instance.
  40687. * @return The cloned image processing
  40688. */
  40689. ImageProcessingConfiguration.prototype.clone = function () {
  40690. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40691. };
  40692. /**
  40693. * Serializes the current image processing instance to a json representation.
  40694. * @return a JSON representation
  40695. */
  40696. ImageProcessingConfiguration.prototype.serialize = function () {
  40697. return BABYLON.SerializationHelper.Serialize(this);
  40698. };
  40699. /**
  40700. * Parses the image processing from a json representation.
  40701. * @param source the JSON source to parse
  40702. * @return The parsed image processing
  40703. */
  40704. ImageProcessingConfiguration.Parse = function (source) {
  40705. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40706. };
  40707. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40708. /**
  40709. * Used to apply the vignette as a mix with the pixel color.
  40710. */
  40711. get: function () {
  40712. return this._VIGNETTEMODE_MULTIPLY;
  40713. },
  40714. enumerable: true,
  40715. configurable: true
  40716. });
  40717. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40718. /**
  40719. * Used to apply the vignette as a replacement of the pixel color.
  40720. */
  40721. get: function () {
  40722. return this._VIGNETTEMODE_OPAQUE;
  40723. },
  40724. enumerable: true,
  40725. configurable: true
  40726. });
  40727. return ImageProcessingConfiguration;
  40728. }());
  40729. // Static constants associated to the image processing.
  40730. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40731. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40732. __decorate([
  40733. BABYLON.serializeAsColorCurves()
  40734. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40735. __decorate([
  40736. BABYLON.serialize()
  40737. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40738. __decorate([
  40739. BABYLON.serializeAsTexture()
  40740. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40741. __decorate([
  40742. BABYLON.serialize()
  40743. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40744. __decorate([
  40745. BABYLON.serialize()
  40746. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40747. __decorate([
  40748. BABYLON.serialize()
  40749. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40750. __decorate([
  40751. BABYLON.serialize()
  40752. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40753. __decorate([
  40754. BABYLON.serialize()
  40755. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40756. __decorate([
  40757. BABYLON.serialize()
  40758. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40759. __decorate([
  40760. BABYLON.serialize()
  40761. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40762. __decorate([
  40763. BABYLON.serialize()
  40764. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40765. __decorate([
  40766. BABYLON.serialize()
  40767. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40768. __decorate([
  40769. BABYLON.serialize()
  40770. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40771. __decorate([
  40772. BABYLON.serializeAsColor4()
  40773. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40774. __decorate([
  40775. BABYLON.serialize()
  40776. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40780. __decorate([
  40781. BABYLON.serialize()
  40782. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40783. __decorate([
  40784. BABYLON.serialize()
  40785. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40786. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40787. })(BABYLON || (BABYLON = {}));
  40788. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40789. /// <reference path="babylon.mesh.ts" />
  40790. var BABYLON;
  40791. (function (BABYLON) {
  40792. var GroundMesh = (function (_super) {
  40793. __extends(GroundMesh, _super);
  40794. function GroundMesh(name, scene) {
  40795. var _this = _super.call(this, name, scene) || this;
  40796. _this.generateOctree = false;
  40797. _this._worldInverse = new BABYLON.Matrix();
  40798. return _this;
  40799. }
  40800. GroundMesh.prototype.getClassName = function () {
  40801. return "GroundMesh";
  40802. };
  40803. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  40804. get: function () {
  40805. return Math.min(this._subdivisionsX, this._subdivisionsY);
  40806. },
  40807. enumerable: true,
  40808. configurable: true
  40809. });
  40810. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  40811. get: function () {
  40812. return this._subdivisionsX;
  40813. },
  40814. enumerable: true,
  40815. configurable: true
  40816. });
  40817. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  40818. get: function () {
  40819. return this._subdivisionsY;
  40820. },
  40821. enumerable: true,
  40822. configurable: true
  40823. });
  40824. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  40825. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  40826. this._subdivisionsX = chunksCount;
  40827. this._subdivisionsY = chunksCount;
  40828. this.subdivide(chunksCount);
  40829. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  40830. };
  40831. /**
  40832. * Returns a height (y) value in the Worl system :
  40833. * the ground altitude at the coordinates (x, z) expressed in the World system.
  40834. * Returns the ground y position if (x, z) are outside the ground surface.
  40835. */
  40836. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  40837. var world = this.getWorldMatrix();
  40838. var invMat = BABYLON.Tmp.Matrix[5];
  40839. world.invertToRef(invMat);
  40840. var tmpVect = BABYLON.Tmp.Vector3[8];
  40841. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  40842. x = tmpVect.x;
  40843. z = tmpVect.z;
  40844. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40845. return this.position.y;
  40846. }
  40847. if (!this._heightQuads || this._heightQuads.length == 0) {
  40848. this._initHeightQuads();
  40849. this._computeHeightQuads();
  40850. }
  40851. var facet = this._getFacetAt(x, z);
  40852. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  40853. // return y in the World system
  40854. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  40855. return tmpVect.y;
  40856. };
  40857. /**
  40858. * Returns a normalized vector (Vector3) orthogonal to the ground
  40859. * at the ground coordinates (x, z) expressed in the World system.
  40860. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  40861. */
  40862. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  40863. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  40864. this.getNormalAtCoordinatesToRef(x, z, normal);
  40865. return normal;
  40866. };
  40867. /**
  40868. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  40869. * at the ground coordinates (x, z) expressed in the World system.
  40870. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  40871. * Returns the GroundMesh.
  40872. */
  40873. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  40874. var world = this.getWorldMatrix();
  40875. var tmpMat = BABYLON.Tmp.Matrix[5];
  40876. world.invertToRef(tmpMat);
  40877. var tmpVect = BABYLON.Tmp.Vector3[8];
  40878. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  40879. x = tmpVect.x;
  40880. z = tmpVect.z;
  40881. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  40882. return this;
  40883. }
  40884. if (!this._heightQuads || this._heightQuads.length == 0) {
  40885. this._initHeightQuads();
  40886. this._computeHeightQuads();
  40887. }
  40888. var facet = this._getFacetAt(x, z);
  40889. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  40890. return this;
  40891. };
  40892. /**
  40893. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  40894. * if the ground has been updated.
  40895. * This can be used in the render loop.
  40896. * Returns the GroundMesh.
  40897. */
  40898. GroundMesh.prototype.updateCoordinateHeights = function () {
  40899. if (!this._heightQuads || this._heightQuads.length == 0) {
  40900. this._initHeightQuads();
  40901. }
  40902. this._computeHeightQuads();
  40903. return this;
  40904. };
  40905. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  40906. GroundMesh.prototype._getFacetAt = function (x, z) {
  40907. // retrieve col and row from x, z coordinates in the ground local system
  40908. var subdivisionsX = this._subdivisionsX;
  40909. var subdivisionsY = this._subdivisionsY;
  40910. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  40911. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  40912. var quad = this._heightQuads[row * this._subdivisionsX + col];
  40913. var facet;
  40914. if (z < quad.slope.x * x + quad.slope.y) {
  40915. facet = quad.facet1;
  40916. }
  40917. else {
  40918. facet = quad.facet2;
  40919. }
  40920. return facet;
  40921. };
  40922. // Creates and populates the heightMap array with "facet" elements :
  40923. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  40924. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40925. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40926. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40927. // Returns the GroundMesh.
  40928. GroundMesh.prototype._initHeightQuads = function () {
  40929. var subdivisionsX = this._subdivisionsX;
  40930. var subdivisionsY = this._subdivisionsY;
  40931. this._heightQuads = new Array();
  40932. for (var row = 0; row < subdivisionsY; row++) {
  40933. for (var col = 0; col < subdivisionsX; col++) {
  40934. 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) };
  40935. this._heightQuads[row * subdivisionsX + col] = quad;
  40936. }
  40937. }
  40938. return this;
  40939. };
  40940. // Compute each quad element values and update the the heightMap array :
  40941. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  40942. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  40943. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  40944. // Returns the GroundMesh.
  40945. GroundMesh.prototype._computeHeightQuads = function () {
  40946. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40947. var v1 = BABYLON.Tmp.Vector3[3];
  40948. var v2 = BABYLON.Tmp.Vector3[2];
  40949. var v3 = BABYLON.Tmp.Vector3[1];
  40950. var v4 = BABYLON.Tmp.Vector3[0];
  40951. var v1v2 = BABYLON.Tmp.Vector3[4];
  40952. var v1v3 = BABYLON.Tmp.Vector3[5];
  40953. var v1v4 = BABYLON.Tmp.Vector3[6];
  40954. var norm1 = BABYLON.Tmp.Vector3[7];
  40955. var norm2 = BABYLON.Tmp.Vector3[8];
  40956. var i = 0;
  40957. var j = 0;
  40958. var k = 0;
  40959. var cd = 0; // 2D slope coefficient : z = cd * x + h
  40960. var h = 0;
  40961. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  40962. var d2 = 0;
  40963. var subdivisionsX = this._subdivisionsX;
  40964. var subdivisionsY = this._subdivisionsY;
  40965. for (var row = 0; row < subdivisionsY; row++) {
  40966. for (var col = 0; col < subdivisionsX; col++) {
  40967. i = col * 3;
  40968. j = row * (subdivisionsX + 1) * 3;
  40969. k = (row + 1) * (subdivisionsX + 1) * 3;
  40970. v1.x = positions[j + i];
  40971. v1.y = positions[j + i + 1];
  40972. v1.z = positions[j + i + 2];
  40973. v2.x = positions[j + i + 3];
  40974. v2.y = positions[j + i + 4];
  40975. v2.z = positions[j + i + 5];
  40976. v3.x = positions[k + i];
  40977. v3.y = positions[k + i + 1];
  40978. v3.z = positions[k + i + 2];
  40979. v4.x = positions[k + i + 3];
  40980. v4.y = positions[k + i + 4];
  40981. v4.z = positions[k + i + 5];
  40982. // 2D slope V1V4
  40983. cd = (v4.z - v1.z) / (v4.x - v1.x);
  40984. h = v1.z - cd * v1.x; // v1 belongs to the slope
  40985. // facet equations :
  40986. // we compute each facet normal vector
  40987. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  40988. // we compute the value d by applying the equation to v1 which belongs to the plane
  40989. // then we store the facet equation in a Vector4
  40990. v2.subtractToRef(v1, v1v2);
  40991. v3.subtractToRef(v1, v1v3);
  40992. v4.subtractToRef(v1, v1v4);
  40993. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  40994. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  40995. norm1.normalize();
  40996. norm2.normalize();
  40997. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  40998. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  40999. var quad = this._heightQuads[row * subdivisionsX + col];
  41000. quad.slope.copyFromFloats(cd, h);
  41001. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41002. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41003. }
  41004. }
  41005. return this;
  41006. };
  41007. GroundMesh.prototype.serialize = function (serializationObject) {
  41008. _super.prototype.serialize.call(this, serializationObject);
  41009. serializationObject.subdivisionsX = this._subdivisionsX;
  41010. serializationObject.subdivisionsY = this._subdivisionsY;
  41011. serializationObject.minX = this._minX;
  41012. serializationObject.maxX = this._maxX;
  41013. serializationObject.minZ = this._minZ;
  41014. serializationObject.maxZ = this._maxZ;
  41015. serializationObject.width = this._width;
  41016. serializationObject.height = this._height;
  41017. };
  41018. GroundMesh.Parse = function (parsedMesh, scene) {
  41019. var result = new GroundMesh(parsedMesh.name, scene);
  41020. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41021. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41022. result._minX = parsedMesh.minX;
  41023. result._maxX = parsedMesh.maxX;
  41024. result._minZ = parsedMesh.minZ;
  41025. result._maxZ = parsedMesh.maxZ;
  41026. result._width = parsedMesh.width;
  41027. result._height = parsedMesh.height;
  41028. return result;
  41029. };
  41030. return GroundMesh;
  41031. }(BABYLON.Mesh));
  41032. BABYLON.GroundMesh = GroundMesh;
  41033. })(BABYLON || (BABYLON = {}));
  41034. //# sourceMappingURL=babylon.groundMesh.js.map
  41035. var BABYLON;
  41036. (function (BABYLON) {
  41037. /**
  41038. * Creates an instance based on a source mesh.
  41039. */
  41040. var InstancedMesh = (function (_super) {
  41041. __extends(InstancedMesh, _super);
  41042. function InstancedMesh(name, source) {
  41043. var _this = _super.call(this, name, source.getScene()) || this;
  41044. source.instances.push(_this);
  41045. _this._sourceMesh = source;
  41046. _this.position.copyFrom(source.position);
  41047. _this.rotation.copyFrom(source.rotation);
  41048. _this.scaling.copyFrom(source.scaling);
  41049. if (source.rotationQuaternion) {
  41050. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41051. }
  41052. _this.infiniteDistance = source.infiniteDistance;
  41053. _this.setPivotMatrix(source.getPivotMatrix());
  41054. _this.refreshBoundingInfo();
  41055. _this._syncSubMeshes();
  41056. return _this;
  41057. }
  41058. /**
  41059. * Returns the string "InstancedMesh".
  41060. */
  41061. InstancedMesh.prototype.getClassName = function () {
  41062. return "InstancedMesh";
  41063. };
  41064. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41065. // Methods
  41066. get: function () {
  41067. return this._sourceMesh.receiveShadows;
  41068. },
  41069. enumerable: true,
  41070. configurable: true
  41071. });
  41072. Object.defineProperty(InstancedMesh.prototype, "material", {
  41073. get: function () {
  41074. return this._sourceMesh.material;
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  41080. get: function () {
  41081. return this._sourceMesh.visibility;
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  41087. get: function () {
  41088. return this._sourceMesh.skeleton;
  41089. },
  41090. enumerable: true,
  41091. configurable: true
  41092. });
  41093. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  41094. get: function () {
  41095. return this._sourceMesh.renderingGroupId;
  41096. },
  41097. enumerable: true,
  41098. configurable: true
  41099. });
  41100. /**
  41101. * Returns the total number of vertices (integer).
  41102. */
  41103. InstancedMesh.prototype.getTotalVertices = function () {
  41104. return this._sourceMesh.getTotalVertices();
  41105. };
  41106. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  41107. get: function () {
  41108. return this._sourceMesh;
  41109. },
  41110. enumerable: true,
  41111. configurable: true
  41112. });
  41113. /**
  41114. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  41115. */
  41116. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  41117. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  41118. };
  41119. /**
  41120. * Sets the vertex data of the mesh geometry for the requested `kind`.
  41121. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  41122. * The `data` are either a numeric array either a Float32Array.
  41123. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  41124. * 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).
  41125. * Note that a new underlying VertexBuffer object is created each call.
  41126. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  41127. *
  41128. * Possible `kind` values :
  41129. * - BABYLON.VertexBuffer.PositionKind
  41130. * - BABYLON.VertexBuffer.UVKind
  41131. * - BABYLON.VertexBuffer.UV2Kind
  41132. * - BABYLON.VertexBuffer.UV3Kind
  41133. * - BABYLON.VertexBuffer.UV4Kind
  41134. * - BABYLON.VertexBuffer.UV5Kind
  41135. * - BABYLON.VertexBuffer.UV6Kind
  41136. * - BABYLON.VertexBuffer.ColorKind
  41137. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41138. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41139. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41140. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41141. *
  41142. * Returns the Mesh.
  41143. */
  41144. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  41145. if (this.sourceMesh) {
  41146. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  41147. }
  41148. return this.sourceMesh;
  41149. };
  41150. /**
  41151. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  41152. * If the mesh has no geometry, it is simply returned as it is.
  41153. * The `data` are either a numeric array either a Float32Array.
  41154. * No new underlying VertexBuffer object is created.
  41155. * 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.
  41156. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  41157. *
  41158. * Possible `kind` values :
  41159. * - BABYLON.VertexBuffer.PositionKind
  41160. * - BABYLON.VertexBuffer.UVKind
  41161. * - BABYLON.VertexBuffer.UV2Kind
  41162. * - BABYLON.VertexBuffer.UV3Kind
  41163. * - BABYLON.VertexBuffer.UV4Kind
  41164. * - BABYLON.VertexBuffer.UV5Kind
  41165. * - BABYLON.VertexBuffer.UV6Kind
  41166. * - BABYLON.VertexBuffer.ColorKind
  41167. * - BABYLON.VertexBuffer.MatricesIndicesKind
  41168. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  41169. * - BABYLON.VertexBuffer.MatricesWeightsKind
  41170. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  41171. *
  41172. * Returns the Mesh.
  41173. */
  41174. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  41175. if (this.sourceMesh) {
  41176. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  41177. }
  41178. return this.sourceMesh;
  41179. };
  41180. /**
  41181. * Sets the mesh indices.
  41182. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  41183. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  41184. * This method creates a new index buffer each call.
  41185. * Returns the Mesh.
  41186. */
  41187. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  41188. if (this.sourceMesh) {
  41189. this.sourceMesh.setIndices(indices, totalVertices);
  41190. }
  41191. return this.sourceMesh;
  41192. };
  41193. /**
  41194. * Boolean : True if the mesh owns the requested kind of data.
  41195. */
  41196. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  41197. return this._sourceMesh.isVerticesDataPresent(kind);
  41198. };
  41199. /**
  41200. * Returns an array of indices (IndicesArray).
  41201. */
  41202. InstancedMesh.prototype.getIndices = function () {
  41203. return this._sourceMesh.getIndices();
  41204. };
  41205. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  41206. get: function () {
  41207. return this._sourceMesh._positions;
  41208. },
  41209. enumerable: true,
  41210. configurable: true
  41211. });
  41212. /**
  41213. * Sets a new updated BoundingInfo to the mesh.
  41214. * Returns the mesh.
  41215. */
  41216. InstancedMesh.prototype.refreshBoundingInfo = function () {
  41217. var meshBB = this._sourceMesh.getBoundingInfo();
  41218. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  41219. this._updateBoundingInfo();
  41220. return this;
  41221. };
  41222. InstancedMesh.prototype._preActivate = function () {
  41223. if (this._currentLOD) {
  41224. this._currentLOD._preActivate();
  41225. }
  41226. return this;
  41227. };
  41228. InstancedMesh.prototype._activate = function (renderId) {
  41229. if (this._currentLOD) {
  41230. this._currentLOD._registerInstanceForRenderId(this, renderId);
  41231. }
  41232. return this;
  41233. };
  41234. /**
  41235. * Returns the current associated LOD AbstractMesh.
  41236. */
  41237. InstancedMesh.prototype.getLOD = function (camera) {
  41238. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  41239. if (this._currentLOD === this.sourceMesh) {
  41240. return this;
  41241. }
  41242. return this._currentLOD;
  41243. };
  41244. InstancedMesh.prototype._syncSubMeshes = function () {
  41245. this.releaseSubMeshes();
  41246. if (this._sourceMesh.subMeshes) {
  41247. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  41248. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  41249. }
  41250. }
  41251. return this;
  41252. };
  41253. InstancedMesh.prototype._generatePointsArray = function () {
  41254. return this._sourceMesh._generatePointsArray();
  41255. };
  41256. /**
  41257. * Creates a new InstancedMesh from the current mesh.
  41258. * - name (string) : the cloned mesh name
  41259. * - newParent (optional Node) : the optional Node to parent the clone to.
  41260. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  41261. *
  41262. * Returns the clone.
  41263. */
  41264. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41265. var result = this._sourceMesh.createInstance(name);
  41266. // Deep copy
  41267. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  41268. // Bounding info
  41269. this.refreshBoundingInfo();
  41270. // Parent
  41271. if (newParent) {
  41272. result.parent = newParent;
  41273. }
  41274. if (!doNotCloneChildren) {
  41275. // Children
  41276. for (var index = 0; index < this.getScene().meshes.length; index++) {
  41277. var mesh = this.getScene().meshes[index];
  41278. if (mesh.parent === this) {
  41279. mesh.clone(mesh.name, result);
  41280. }
  41281. }
  41282. }
  41283. result.computeWorldMatrix(true);
  41284. return result;
  41285. };
  41286. /**
  41287. * Disposes the InstancedMesh.
  41288. * Returns nothing.
  41289. */
  41290. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  41291. // Remove from mesh
  41292. var index = this._sourceMesh.instances.indexOf(this);
  41293. this._sourceMesh.instances.splice(index, 1);
  41294. _super.prototype.dispose.call(this, doNotRecurse);
  41295. };
  41296. return InstancedMesh;
  41297. }(BABYLON.AbstractMesh));
  41298. BABYLON.InstancedMesh = InstancedMesh;
  41299. })(BABYLON || (BABYLON = {}));
  41300. //# sourceMappingURL=babylon.instancedMesh.js.map
  41301. /// <reference path="babylon.mesh.ts" />
  41302. var BABYLON;
  41303. (function (BABYLON) {
  41304. var LinesMesh = (function (_super) {
  41305. __extends(LinesMesh, _super);
  41306. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  41307. if (parent === void 0) { parent = null; }
  41308. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  41309. _this.useVertexColor = useVertexColor;
  41310. _this.color = new BABYLON.Color3(1, 1, 1);
  41311. _this.alpha = 1;
  41312. if (source) {
  41313. _this.color = source.color.clone();
  41314. _this.alpha = source.alpha;
  41315. _this.useVertexColor = source.useVertexColor;
  41316. }
  41317. _this._intersectionThreshold = 0.1;
  41318. var options = {
  41319. attributes: [BABYLON.VertexBuffer.PositionKind],
  41320. uniforms: ["world", "viewProjection"],
  41321. needAlphaBlending: false,
  41322. };
  41323. if (!useVertexColor) {
  41324. options.uniforms.push("color");
  41325. options.needAlphaBlending = true;
  41326. }
  41327. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  41328. return _this;
  41329. }
  41330. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  41331. /**
  41332. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41333. * This margin is expressed in world space coordinates, so its value may vary.
  41334. * Default value is 0.1
  41335. * @returns the intersection Threshold value.
  41336. */
  41337. get: function () {
  41338. return this._intersectionThreshold;
  41339. },
  41340. /**
  41341. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  41342. * This margin is expressed in world space coordinates, so its value may vary.
  41343. * @param value the new threshold to apply
  41344. */
  41345. set: function (value) {
  41346. if (this._intersectionThreshold === value) {
  41347. return;
  41348. }
  41349. this._intersectionThreshold = value;
  41350. if (this.geometry) {
  41351. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  41352. }
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. /**
  41358. * Returns the string "LineMesh"
  41359. */
  41360. LinesMesh.prototype.getClassName = function () {
  41361. return "LinesMesh";
  41362. };
  41363. Object.defineProperty(LinesMesh.prototype, "material", {
  41364. get: function () {
  41365. return this._colorShader;
  41366. },
  41367. enumerable: true,
  41368. configurable: true
  41369. });
  41370. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  41371. get: function () {
  41372. return false;
  41373. },
  41374. enumerable: true,
  41375. configurable: true
  41376. });
  41377. LinesMesh.prototype.createInstance = function (name) {
  41378. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  41379. return null;
  41380. };
  41381. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  41382. // VBOs
  41383. this._geometry._bind(this._colorShader.getEffect());
  41384. // Color
  41385. if (!this.useVertexColor) {
  41386. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  41387. }
  41388. return this;
  41389. };
  41390. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  41391. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  41392. return this;
  41393. }
  41394. var engine = this.getScene().getEngine();
  41395. // Draw order
  41396. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  41397. return this;
  41398. };
  41399. LinesMesh.prototype.dispose = function (doNotRecurse) {
  41400. this._colorShader.dispose();
  41401. _super.prototype.dispose.call(this, doNotRecurse);
  41402. };
  41403. /**
  41404. * Returns a new LineMesh object cloned from the current one.
  41405. */
  41406. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  41407. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  41408. };
  41409. return LinesMesh;
  41410. }(BABYLON.Mesh));
  41411. BABYLON.LinesMesh = LinesMesh;
  41412. })(BABYLON || (BABYLON = {}));
  41413. //# sourceMappingURL=babylon.linesMesh.js.map
  41414. var BABYLON;
  41415. (function (BABYLON) {
  41416. var StandardMaterialDefines = (function (_super) {
  41417. __extends(StandardMaterialDefines, _super);
  41418. function StandardMaterialDefines() {
  41419. var _this = _super.call(this) || this;
  41420. _this.DIFFUSE = false;
  41421. _this.AMBIENT = false;
  41422. _this.OPACITY = false;
  41423. _this.OPACITYRGB = false;
  41424. _this.REFLECTION = false;
  41425. _this.EMISSIVE = false;
  41426. _this.SPECULAR = false;
  41427. _this.BUMP = false;
  41428. _this.PARALLAX = false;
  41429. _this.PARALLAXOCCLUSION = false;
  41430. _this.SPECULAROVERALPHA = false;
  41431. _this.CLIPPLANE = false;
  41432. _this.ALPHATEST = false;
  41433. _this.ALPHAFROMDIFFUSE = false;
  41434. _this.POINTSIZE = false;
  41435. _this.FOG = false;
  41436. _this.SPECULARTERM = false;
  41437. _this.DIFFUSEFRESNEL = false;
  41438. _this.OPACITYFRESNEL = false;
  41439. _this.REFLECTIONFRESNEL = false;
  41440. _this.REFRACTIONFRESNEL = false;
  41441. _this.EMISSIVEFRESNEL = false;
  41442. _this.FRESNEL = false;
  41443. _this.NORMAL = false;
  41444. _this.UV1 = false;
  41445. _this.UV2 = false;
  41446. _this.VERTEXCOLOR = false;
  41447. _this.VERTEXALPHA = false;
  41448. _this.NUM_BONE_INFLUENCERS = 0;
  41449. _this.BonesPerMesh = 0;
  41450. _this.INSTANCES = false;
  41451. _this.GLOSSINESS = false;
  41452. _this.ROUGHNESS = false;
  41453. _this.EMISSIVEASILLUMINATION = false;
  41454. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41455. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41456. _this.LIGHTMAP = false;
  41457. _this.USELIGHTMAPASSHADOWMAP = false;
  41458. _this.REFLECTIONMAP_3D = false;
  41459. _this.REFLECTIONMAP_SPHERICAL = false;
  41460. _this.REFLECTIONMAP_PLANAR = false;
  41461. _this.REFLECTIONMAP_CUBIC = false;
  41462. _this.REFLECTIONMAP_PROJECTION = false;
  41463. _this.REFLECTIONMAP_SKYBOX = false;
  41464. _this.REFLECTIONMAP_EXPLICIT = false;
  41465. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41466. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41467. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41468. _this.INVERTCUBICMAP = false;
  41469. _this.LOGARITHMICDEPTH = false;
  41470. _this.REFRACTION = false;
  41471. _this.REFRACTIONMAP_3D = false;
  41472. _this.REFLECTIONOVERALPHA = false;
  41473. _this.INVERTNORMALMAPX = false;
  41474. _this.INVERTNORMALMAPY = false;
  41475. _this.TWOSIDEDLIGHTING = false;
  41476. _this.SHADOWFLOAT = false;
  41477. _this.MORPHTARGETS = false;
  41478. _this.MORPHTARGETS_NORMAL = false;
  41479. _this.MORPHTARGETS_TANGENT = false;
  41480. _this.NUM_MORPH_INFLUENCERS = 0;
  41481. _this.USERIGHTHANDEDSYSTEM = false;
  41482. _this.IMAGEPROCESSING = false;
  41483. _this.VIGNETTE = false;
  41484. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41485. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41486. _this.TONEMAPPING = false;
  41487. _this.CONTRAST = false;
  41488. _this.COLORCURVES = false;
  41489. _this.COLORGRADING = false;
  41490. _this.SAMPLER3DGREENDEPTH = false;
  41491. _this.SAMPLER3DBGRMAP = false;
  41492. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41493. _this.EXPOSURE = false;
  41494. _this.rebuild();
  41495. return _this;
  41496. }
  41497. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41498. var modes = [
  41499. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41500. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41501. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41502. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41503. ];
  41504. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41505. var mode = modes_1[_i];
  41506. this[mode] = (mode === modeToEnable);
  41507. }
  41508. };
  41509. return StandardMaterialDefines;
  41510. }(BABYLON.MaterialDefines));
  41511. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41512. var StandardMaterial = (function (_super) {
  41513. __extends(StandardMaterial, _super);
  41514. function StandardMaterial(name, scene) {
  41515. var _this = _super.call(this, name, scene) || this;
  41516. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41517. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41518. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41519. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41520. _this.specularPower = 64;
  41521. _this._useAlphaFromDiffuseTexture = false;
  41522. _this._useEmissiveAsIllumination = false;
  41523. _this._linkEmissiveWithDiffuse = false;
  41524. _this._useSpecularOverAlpha = false;
  41525. _this._useReflectionOverAlpha = false;
  41526. _this._disableLighting = false;
  41527. _this._useParallax = false;
  41528. _this._useParallaxOcclusion = false;
  41529. _this.parallaxScaleBias = 0.05;
  41530. _this._roughness = 0;
  41531. _this.indexOfRefraction = 0.98;
  41532. _this.invertRefractionY = true;
  41533. _this._useLightmapAsShadowmap = false;
  41534. _this._useReflectionFresnelFromSpecular = false;
  41535. _this._useGlossinessFromSpecularMapAlpha = false;
  41536. _this._maxSimultaneousLights = 4;
  41537. /**
  41538. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41539. */
  41540. _this._invertNormalMapX = false;
  41541. /**
  41542. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41543. */
  41544. _this._invertNormalMapY = false;
  41545. /**
  41546. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41547. */
  41548. _this._twoSidedLighting = false;
  41549. _this._renderTargets = new BABYLON.SmartArray(16);
  41550. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41551. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41552. // Setup the default processing configuration to the scene.
  41553. _this._attachImageProcessingConfiguration(null);
  41554. _this.getRenderTargetTextures = function () {
  41555. _this._renderTargets.reset();
  41556. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41557. _this._renderTargets.push(_this._reflectionTexture);
  41558. }
  41559. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41560. _this._renderTargets.push(_this._refractionTexture);
  41561. }
  41562. return _this._renderTargets;
  41563. };
  41564. return _this;
  41565. }
  41566. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41567. /**
  41568. * Gets the image processing configuration used either in this material.
  41569. */
  41570. get: function () {
  41571. return this._imageProcessingConfiguration;
  41572. },
  41573. /**
  41574. * Sets the Default image processing configuration used either in the this material.
  41575. *
  41576. * If sets to null, the scene one is in use.
  41577. */
  41578. set: function (value) {
  41579. this._attachImageProcessingConfiguration(value);
  41580. // Ensure the effect will be rebuilt.
  41581. this._markAllSubMeshesAsTexturesDirty();
  41582. },
  41583. enumerable: true,
  41584. configurable: true
  41585. });
  41586. /**
  41587. * Attaches a new image processing configuration to the Standard Material.
  41588. * @param configuration
  41589. */
  41590. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41591. var _this = this;
  41592. if (configuration === this._imageProcessingConfiguration) {
  41593. return;
  41594. }
  41595. // Detaches observer.
  41596. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41597. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41598. }
  41599. // Pick the scene configuration if needed.
  41600. if (!configuration) {
  41601. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41602. }
  41603. else {
  41604. this._imageProcessingConfiguration = configuration;
  41605. }
  41606. // Attaches observer.
  41607. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41608. _this._markAllSubMeshesAsImageProcessingDirty();
  41609. });
  41610. };
  41611. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41612. /**
  41613. * Gets wether the color curves effect is enabled.
  41614. */
  41615. get: function () {
  41616. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41617. },
  41618. /**
  41619. * Sets wether the color curves effect is enabled.
  41620. */
  41621. set: function (value) {
  41622. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41623. },
  41624. enumerable: true,
  41625. configurable: true
  41626. });
  41627. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41628. /**
  41629. * Gets wether the color grading effect is enabled.
  41630. */
  41631. get: function () {
  41632. return this.imageProcessingConfiguration.colorGradingEnabled;
  41633. },
  41634. /**
  41635. * Gets wether the color grading effect is enabled.
  41636. */
  41637. set: function (value) {
  41638. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41639. },
  41640. enumerable: true,
  41641. configurable: true
  41642. });
  41643. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  41644. /**
  41645. * Gets wether tonemapping is enabled or not.
  41646. */
  41647. get: function () {
  41648. return this._imageProcessingConfiguration.toneMappingEnabled;
  41649. },
  41650. /**
  41651. * Sets wether tonemapping is enabled or not
  41652. */
  41653. set: function (value) {
  41654. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41655. },
  41656. enumerable: true,
  41657. configurable: true
  41658. });
  41659. ;
  41660. ;
  41661. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  41662. /**
  41663. * The camera exposure used on this material.
  41664. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41665. * This corresponds to a photographic exposure.
  41666. */
  41667. get: function () {
  41668. return this._imageProcessingConfiguration.exposure;
  41669. },
  41670. /**
  41671. * The camera exposure used on this material.
  41672. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41673. * This corresponds to a photographic exposure.
  41674. */
  41675. set: function (value) {
  41676. this._imageProcessingConfiguration.exposure = value;
  41677. },
  41678. enumerable: true,
  41679. configurable: true
  41680. });
  41681. ;
  41682. ;
  41683. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  41684. /**
  41685. * Gets The camera contrast used on this material.
  41686. */
  41687. get: function () {
  41688. return this._imageProcessingConfiguration.contrast;
  41689. },
  41690. /**
  41691. * Sets The camera contrast used on this material.
  41692. */
  41693. set: function (value) {
  41694. this._imageProcessingConfiguration.contrast = value;
  41695. },
  41696. enumerable: true,
  41697. configurable: true
  41698. });
  41699. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  41700. /**
  41701. * Gets the Color Grading 2D Lookup Texture.
  41702. */
  41703. get: function () {
  41704. return this._imageProcessingConfiguration.colorGradingTexture;
  41705. },
  41706. /**
  41707. * Sets the Color Grading 2D Lookup Texture.
  41708. */
  41709. set: function (value) {
  41710. this._imageProcessingConfiguration.colorGradingTexture = value;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. StandardMaterial.prototype.getClassName = function () {
  41716. return "StandardMaterial";
  41717. };
  41718. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  41719. get: function () {
  41720. return this._useLogarithmicDepth;
  41721. },
  41722. set: function (value) {
  41723. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41724. this._markAllSubMeshesAsMiscDirty();
  41725. },
  41726. enumerable: true,
  41727. configurable: true
  41728. });
  41729. StandardMaterial.prototype.needAlphaBlending = function () {
  41730. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  41731. };
  41732. StandardMaterial.prototype.needAlphaTesting = function () {
  41733. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  41734. };
  41735. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  41736. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  41737. };
  41738. StandardMaterial.prototype.getAlphaTestTexture = function () {
  41739. return this._diffuseTexture;
  41740. };
  41741. /**
  41742. * Child classes can use it to update shaders
  41743. */
  41744. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41745. if (this.isFrozen) {
  41746. if (this._wasPreviouslyReady && subMesh.effect) {
  41747. return true;
  41748. }
  41749. }
  41750. if (!subMesh._materialDefines) {
  41751. subMesh._materialDefines = new StandardMaterialDefines();
  41752. }
  41753. var scene = this.getScene();
  41754. var defines = subMesh._materialDefines;
  41755. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41756. if (defines._renderId === scene.getRenderId()) {
  41757. return true;
  41758. }
  41759. }
  41760. var engine = scene.getEngine();
  41761. // Lights
  41762. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41763. // Textures
  41764. if (defines._areTexturesDirty) {
  41765. defines._needUVs = false;
  41766. if (scene.texturesEnabled) {
  41767. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41768. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  41769. return false;
  41770. }
  41771. else {
  41772. defines._needUVs = true;
  41773. defines.DIFFUSE = true;
  41774. }
  41775. }
  41776. else {
  41777. defines.DIFFUSE = false;
  41778. }
  41779. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41780. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41781. return false;
  41782. }
  41783. else {
  41784. defines._needUVs = true;
  41785. defines.AMBIENT = true;
  41786. }
  41787. }
  41788. else {
  41789. defines.AMBIENT = false;
  41790. }
  41791. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41792. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41793. return false;
  41794. }
  41795. else {
  41796. defines._needUVs = true;
  41797. defines.OPACITY = true;
  41798. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41799. }
  41800. }
  41801. else {
  41802. defines.OPACITY = false;
  41803. }
  41804. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41805. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  41806. return false;
  41807. }
  41808. else {
  41809. defines._needNormals = true;
  41810. defines.REFLECTION = true;
  41811. defines.ROUGHNESS = (this._roughness > 0);
  41812. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  41813. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  41814. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  41815. switch (this._reflectionTexture.coordinatesMode) {
  41816. case BABYLON.Texture.CUBIC_MODE:
  41817. case BABYLON.Texture.INVCUBIC_MODE:
  41818. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  41819. break;
  41820. case BABYLON.Texture.EXPLICIT_MODE:
  41821. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  41822. break;
  41823. case BABYLON.Texture.PLANAR_MODE:
  41824. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  41825. break;
  41826. case BABYLON.Texture.PROJECTION_MODE:
  41827. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  41828. break;
  41829. case BABYLON.Texture.SKYBOX_MODE:
  41830. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  41831. break;
  41832. case BABYLON.Texture.SPHERICAL_MODE:
  41833. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  41834. break;
  41835. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41836. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  41837. break;
  41838. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41839. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  41840. break;
  41841. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41842. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  41843. break;
  41844. }
  41845. }
  41846. }
  41847. else {
  41848. defines.REFLECTION = false;
  41849. }
  41850. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41851. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41852. return false;
  41853. }
  41854. else {
  41855. defines._needUVs = true;
  41856. defines.EMISSIVE = true;
  41857. }
  41858. }
  41859. else {
  41860. defines.EMISSIVE = false;
  41861. }
  41862. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41863. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41864. return false;
  41865. }
  41866. else {
  41867. defines._needUVs = true;
  41868. defines.LIGHTMAP = true;
  41869. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41870. }
  41871. }
  41872. else {
  41873. defines.LIGHTMAP = false;
  41874. }
  41875. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41876. if (!this._specularTexture.isReadyOrNotBlocking()) {
  41877. return false;
  41878. }
  41879. else {
  41880. defines._needUVs = true;
  41881. defines.SPECULAR = true;
  41882. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  41883. }
  41884. }
  41885. else {
  41886. defines.SPECULAR = false;
  41887. }
  41888. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  41889. // Bump texure can not be not blocking.
  41890. if (!this._bumpTexture.isReady()) {
  41891. return false;
  41892. }
  41893. else {
  41894. defines._needUVs = true;
  41895. defines.BUMP = true;
  41896. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  41897. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  41898. defines.PARALLAX = this._useParallax;
  41899. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  41900. }
  41901. }
  41902. else {
  41903. defines.BUMP = false;
  41904. }
  41905. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41906. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  41907. return false;
  41908. }
  41909. else {
  41910. defines._needUVs = true;
  41911. defines.REFRACTION = true;
  41912. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  41913. }
  41914. }
  41915. else {
  41916. defines.REFRACTION = false;
  41917. }
  41918. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  41919. }
  41920. else {
  41921. defines.DIFFUSE = false;
  41922. defines.AMBIENT = false;
  41923. defines.OPACITY = false;
  41924. defines.REFLECTION = false;
  41925. defines.EMISSIVE = false;
  41926. defines.LIGHTMAP = false;
  41927. defines.BUMP = false;
  41928. defines.REFRACTION = false;
  41929. }
  41930. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  41931. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  41932. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  41933. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41934. }
  41935. if (defines._areImageProcessingDirty) {
  41936. if (!this._imageProcessingConfiguration.isReady()) {
  41937. return false;
  41938. }
  41939. this._imageProcessingConfiguration.prepareDefines(defines);
  41940. }
  41941. if (defines._areFresnelDirty) {
  41942. if (StandardMaterial.FresnelEnabled) {
  41943. // Fresnel
  41944. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  41945. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  41946. this._reflectionFresnelParameters) {
  41947. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  41948. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  41949. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  41950. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  41951. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  41952. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  41953. defines._needNormals = true;
  41954. defines.FRESNEL = true;
  41955. }
  41956. }
  41957. else {
  41958. defines.FRESNEL = false;
  41959. }
  41960. }
  41961. // Misc.
  41962. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  41963. // Attribs
  41964. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  41965. // Values that need to be evaluated on every frame
  41966. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  41967. if (scene._mirroredCameraPosition && defines.BUMP) {
  41968. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  41969. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  41970. defines.markAsUnprocessed();
  41971. }
  41972. // Get correct effect
  41973. if (defines.isDirty) {
  41974. defines.markAsProcessed();
  41975. scene.resetCachedMaterial();
  41976. // Fallbacks
  41977. var fallbacks = new BABYLON.EffectFallbacks();
  41978. if (defines.REFLECTION) {
  41979. fallbacks.addFallback(0, "REFLECTION");
  41980. }
  41981. if (defines.SPECULAR) {
  41982. fallbacks.addFallback(0, "SPECULAR");
  41983. }
  41984. if (defines.BUMP) {
  41985. fallbacks.addFallback(0, "BUMP");
  41986. }
  41987. if (defines.PARALLAX) {
  41988. fallbacks.addFallback(1, "PARALLAX");
  41989. }
  41990. if (defines.PARALLAXOCCLUSION) {
  41991. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  41992. }
  41993. if (defines.SPECULAROVERALPHA) {
  41994. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  41995. }
  41996. if (defines.FOG) {
  41997. fallbacks.addFallback(1, "FOG");
  41998. }
  41999. if (defines.POINTSIZE) {
  42000. fallbacks.addFallback(0, "POINTSIZE");
  42001. }
  42002. if (defines.LOGARITHMICDEPTH) {
  42003. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42004. }
  42005. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42006. if (defines.SPECULARTERM) {
  42007. fallbacks.addFallback(0, "SPECULARTERM");
  42008. }
  42009. if (defines.DIFFUSEFRESNEL) {
  42010. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42011. }
  42012. if (defines.OPACITYFRESNEL) {
  42013. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42014. }
  42015. if (defines.REFLECTIONFRESNEL) {
  42016. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42017. }
  42018. if (defines.EMISSIVEFRESNEL) {
  42019. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42020. }
  42021. if (defines.FRESNEL) {
  42022. fallbacks.addFallback(4, "FRESNEL");
  42023. }
  42024. //Attributes
  42025. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42026. if (defines.NORMAL) {
  42027. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42028. }
  42029. if (defines.UV1) {
  42030. attribs.push(BABYLON.VertexBuffer.UVKind);
  42031. }
  42032. if (defines.UV2) {
  42033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42034. }
  42035. if (defines.VERTEXCOLOR) {
  42036. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42037. }
  42038. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42039. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42040. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42041. var shaderName = "default";
  42042. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42043. "vFogInfos", "vFogColor", "pointSize",
  42044. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42045. "mBones",
  42046. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  42047. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42048. "logarithmicDepthConstant"
  42049. ];
  42050. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42051. var uniformBuffers = ["Material", "Scene"];
  42052. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42053. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42054. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42055. uniformsNames: uniforms,
  42056. uniformBuffersNames: uniformBuffers,
  42057. samplers: samplers,
  42058. defines: defines,
  42059. maxSimultaneousLights: this._maxSimultaneousLights
  42060. });
  42061. if (this.customShaderNameResolve) {
  42062. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42063. }
  42064. var join = defines.toString();
  42065. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42066. attributes: attribs,
  42067. uniformsNames: uniforms,
  42068. uniformBuffersNames: uniformBuffers,
  42069. samplers: samplers,
  42070. defines: join,
  42071. fallbacks: fallbacks,
  42072. onCompiled: this.onCompiled,
  42073. onError: this.onError,
  42074. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42075. }, engine), defines);
  42076. this.buildUniformLayout();
  42077. }
  42078. if (!subMesh.effect.isReady()) {
  42079. return false;
  42080. }
  42081. defines._renderId = scene.getRenderId();
  42082. this._wasPreviouslyReady = true;
  42083. return true;
  42084. };
  42085. StandardMaterial.prototype.buildUniformLayout = function () {
  42086. // Order is important !
  42087. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42088. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42089. this._uniformBuffer.addUniform("opacityParts", 4);
  42090. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42091. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42092. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42093. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42094. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42095. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42096. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42097. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42098. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42099. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42100. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42101. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42102. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42103. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42104. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42105. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42106. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42107. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42108. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42109. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42110. this._uniformBuffer.addUniform("specularMatrix", 16);
  42111. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42112. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42113. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42114. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42115. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42116. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42117. this._uniformBuffer.addUniform("pointSize", 1);
  42118. this._uniformBuffer.create();
  42119. };
  42120. StandardMaterial.prototype.unbind = function () {
  42121. if (this._activeEffect) {
  42122. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42123. this._activeEffect.setTexture("reflection2DSampler", null);
  42124. }
  42125. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42126. this._activeEffect.setTexture("refraction2DSampler", null);
  42127. }
  42128. }
  42129. _super.prototype.unbind.call(this);
  42130. };
  42131. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42132. var scene = this.getScene();
  42133. var defines = subMesh._materialDefines;
  42134. if (!defines) {
  42135. return;
  42136. }
  42137. var effect = subMesh.effect;
  42138. this._activeEffect = effect;
  42139. // Matrices
  42140. this.bindOnlyWorldMatrix(world);
  42141. // Bones
  42142. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42143. if (this._mustRebind(scene, effect, mesh.visibility)) {
  42144. this._uniformBuffer.bindToEffect(effect, "Material");
  42145. this.bindViewProjection(effect);
  42146. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42147. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42148. // Fresnel
  42149. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42150. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42151. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42152. }
  42153. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42154. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42155. }
  42156. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42157. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42158. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42159. }
  42160. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42161. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42162. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42163. }
  42164. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42165. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42166. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42167. }
  42168. }
  42169. // Textures
  42170. if (scene.texturesEnabled) {
  42171. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42172. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42173. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  42174. }
  42175. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42176. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42177. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  42178. }
  42179. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42180. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42181. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  42182. }
  42183. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42184. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42185. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42186. }
  42187. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42188. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42189. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  42190. }
  42191. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42192. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42193. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  42194. }
  42195. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42196. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42197. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  42198. }
  42199. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42200. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42201. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  42202. }
  42203. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42204. var depth = 1.0;
  42205. if (!this._refractionTexture.isCube) {
  42206. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42207. if (this._refractionTexture.depth) {
  42208. depth = this._refractionTexture.depth;
  42209. }
  42210. }
  42211. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42212. }
  42213. }
  42214. // Point size
  42215. if (this.pointsCloud) {
  42216. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42217. }
  42218. if (defines.SPECULARTERM) {
  42219. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42220. }
  42221. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42222. // Diffuse
  42223. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42224. }
  42225. // Textures
  42226. if (scene.texturesEnabled) {
  42227. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42228. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42229. }
  42230. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42231. effect.setTexture("ambientSampler", this._ambientTexture);
  42232. }
  42233. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42234. effect.setTexture("opacitySampler", this._opacityTexture);
  42235. }
  42236. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42237. if (this._reflectionTexture.isCube) {
  42238. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42239. }
  42240. else {
  42241. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42242. }
  42243. }
  42244. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42245. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42246. }
  42247. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42248. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42249. }
  42250. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42251. effect.setTexture("specularSampler", this._specularTexture);
  42252. }
  42253. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42254. effect.setTexture("bumpSampler", this._bumpTexture);
  42255. }
  42256. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42257. var depth = 1.0;
  42258. if (this._refractionTexture.isCube) {
  42259. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42260. }
  42261. else {
  42262. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42263. }
  42264. }
  42265. }
  42266. // Clip plane
  42267. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42268. // Colors
  42269. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42270. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  42271. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42272. }
  42273. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  42274. // Lights
  42275. if (scene.lightsEnabled && !this._disableLighting) {
  42276. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42277. }
  42278. // View
  42279. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42280. this.bindView(effect);
  42281. }
  42282. // Fog
  42283. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42284. // Morph targets
  42285. if (defines.NUM_MORPH_INFLUENCERS) {
  42286. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42287. }
  42288. // Log. depth
  42289. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42290. // image processing
  42291. this._imageProcessingConfiguration.bind(this._activeEffect);
  42292. }
  42293. this._uniformBuffer.update();
  42294. this._afterBind(mesh, this._activeEffect);
  42295. };
  42296. StandardMaterial.prototype.getAnimatables = function () {
  42297. var results = [];
  42298. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42299. results.push(this._diffuseTexture);
  42300. }
  42301. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42302. results.push(this._ambientTexture);
  42303. }
  42304. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42305. results.push(this._opacityTexture);
  42306. }
  42307. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42308. results.push(this._reflectionTexture);
  42309. }
  42310. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42311. results.push(this._emissiveTexture);
  42312. }
  42313. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42314. results.push(this._specularTexture);
  42315. }
  42316. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42317. results.push(this._bumpTexture);
  42318. }
  42319. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42320. results.push(this._lightmapTexture);
  42321. }
  42322. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42323. results.push(this._refractionTexture);
  42324. }
  42325. return results;
  42326. };
  42327. StandardMaterial.prototype.getActiveTextures = function () {
  42328. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42329. if (this._diffuseTexture) {
  42330. activeTextures.push(this._diffuseTexture);
  42331. }
  42332. if (this._ambientTexture) {
  42333. activeTextures.push(this._ambientTexture);
  42334. }
  42335. if (this._opacityTexture) {
  42336. activeTextures.push(this._opacityTexture);
  42337. }
  42338. if (this._reflectionTexture) {
  42339. activeTextures.push(this._reflectionTexture);
  42340. }
  42341. if (this._emissiveTexture) {
  42342. activeTextures.push(this._emissiveTexture);
  42343. }
  42344. if (this._specularTexture) {
  42345. activeTextures.push(this._specularTexture);
  42346. }
  42347. if (this._bumpTexture) {
  42348. activeTextures.push(this._bumpTexture);
  42349. }
  42350. if (this._lightmapTexture) {
  42351. activeTextures.push(this._lightmapTexture);
  42352. }
  42353. if (this._refractionTexture) {
  42354. activeTextures.push(this._refractionTexture);
  42355. }
  42356. return activeTextures;
  42357. };
  42358. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42359. if (forceDisposeTextures) {
  42360. if (this._diffuseTexture) {
  42361. this._diffuseTexture.dispose();
  42362. }
  42363. if (this._ambientTexture) {
  42364. this._ambientTexture.dispose();
  42365. }
  42366. if (this._opacityTexture) {
  42367. this._opacityTexture.dispose();
  42368. }
  42369. if (this._reflectionTexture) {
  42370. this._reflectionTexture.dispose();
  42371. }
  42372. if (this._emissiveTexture) {
  42373. this._emissiveTexture.dispose();
  42374. }
  42375. if (this._specularTexture) {
  42376. this._specularTexture.dispose();
  42377. }
  42378. if (this._bumpTexture) {
  42379. this._bumpTexture.dispose();
  42380. }
  42381. if (this._lightmapTexture) {
  42382. this._lightmapTexture.dispose();
  42383. }
  42384. if (this._refractionTexture) {
  42385. this._refractionTexture.dispose();
  42386. }
  42387. }
  42388. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42389. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42390. }
  42391. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42392. };
  42393. StandardMaterial.prototype.clone = function (name) {
  42394. var _this = this;
  42395. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42396. result.name = name;
  42397. result.id = name;
  42398. return result;
  42399. };
  42400. StandardMaterial.prototype.serialize = function () {
  42401. return BABYLON.SerializationHelper.Serialize(this);
  42402. };
  42403. // Statics
  42404. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42405. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42406. };
  42407. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42408. get: function () {
  42409. return StandardMaterial._DiffuseTextureEnabled;
  42410. },
  42411. set: function (value) {
  42412. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42413. return;
  42414. }
  42415. StandardMaterial._DiffuseTextureEnabled = value;
  42416. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42422. get: function () {
  42423. return StandardMaterial._AmbientTextureEnabled;
  42424. },
  42425. set: function (value) {
  42426. if (StandardMaterial._AmbientTextureEnabled === value) {
  42427. return;
  42428. }
  42429. StandardMaterial._AmbientTextureEnabled = value;
  42430. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42431. },
  42432. enumerable: true,
  42433. configurable: true
  42434. });
  42435. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42436. get: function () {
  42437. return StandardMaterial._OpacityTextureEnabled;
  42438. },
  42439. set: function (value) {
  42440. if (StandardMaterial._OpacityTextureEnabled === value) {
  42441. return;
  42442. }
  42443. StandardMaterial._OpacityTextureEnabled = value;
  42444. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42445. },
  42446. enumerable: true,
  42447. configurable: true
  42448. });
  42449. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42450. get: function () {
  42451. return StandardMaterial._ReflectionTextureEnabled;
  42452. },
  42453. set: function (value) {
  42454. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42455. return;
  42456. }
  42457. StandardMaterial._ReflectionTextureEnabled = value;
  42458. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42459. },
  42460. enumerable: true,
  42461. configurable: true
  42462. });
  42463. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42464. get: function () {
  42465. return StandardMaterial._EmissiveTextureEnabled;
  42466. },
  42467. set: function (value) {
  42468. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42469. return;
  42470. }
  42471. StandardMaterial._EmissiveTextureEnabled = value;
  42472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42473. },
  42474. enumerable: true,
  42475. configurable: true
  42476. });
  42477. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42478. get: function () {
  42479. return StandardMaterial._SpecularTextureEnabled;
  42480. },
  42481. set: function (value) {
  42482. if (StandardMaterial._SpecularTextureEnabled === value) {
  42483. return;
  42484. }
  42485. StandardMaterial._SpecularTextureEnabled = value;
  42486. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42487. },
  42488. enumerable: true,
  42489. configurable: true
  42490. });
  42491. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42492. get: function () {
  42493. return StandardMaterial._BumpTextureEnabled;
  42494. },
  42495. set: function (value) {
  42496. if (StandardMaterial._BumpTextureEnabled === value) {
  42497. return;
  42498. }
  42499. StandardMaterial._BumpTextureEnabled = value;
  42500. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42501. },
  42502. enumerable: true,
  42503. configurable: true
  42504. });
  42505. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42506. get: function () {
  42507. return StandardMaterial._LightmapTextureEnabled;
  42508. },
  42509. set: function (value) {
  42510. if (StandardMaterial._LightmapTextureEnabled === value) {
  42511. return;
  42512. }
  42513. StandardMaterial._LightmapTextureEnabled = value;
  42514. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42515. },
  42516. enumerable: true,
  42517. configurable: true
  42518. });
  42519. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42520. get: function () {
  42521. return StandardMaterial._RefractionTextureEnabled;
  42522. },
  42523. set: function (value) {
  42524. if (StandardMaterial._RefractionTextureEnabled === value) {
  42525. return;
  42526. }
  42527. StandardMaterial._RefractionTextureEnabled = value;
  42528. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42529. },
  42530. enumerable: true,
  42531. configurable: true
  42532. });
  42533. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42534. get: function () {
  42535. return StandardMaterial._ColorGradingTextureEnabled;
  42536. },
  42537. set: function (value) {
  42538. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42539. return;
  42540. }
  42541. StandardMaterial._ColorGradingTextureEnabled = value;
  42542. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42543. },
  42544. enumerable: true,
  42545. configurable: true
  42546. });
  42547. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42548. get: function () {
  42549. return StandardMaterial._FresnelEnabled;
  42550. },
  42551. set: function (value) {
  42552. if (StandardMaterial._FresnelEnabled === value) {
  42553. return;
  42554. }
  42555. StandardMaterial._FresnelEnabled = value;
  42556. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  42557. },
  42558. enumerable: true,
  42559. configurable: true
  42560. });
  42561. return StandardMaterial;
  42562. }(BABYLON.PushMaterial));
  42563. // Flags used to enable or disable a type of texture for all Standard Materials
  42564. StandardMaterial._DiffuseTextureEnabled = true;
  42565. StandardMaterial._AmbientTextureEnabled = true;
  42566. StandardMaterial._OpacityTextureEnabled = true;
  42567. StandardMaterial._ReflectionTextureEnabled = true;
  42568. StandardMaterial._EmissiveTextureEnabled = true;
  42569. StandardMaterial._SpecularTextureEnabled = true;
  42570. StandardMaterial._BumpTextureEnabled = true;
  42571. StandardMaterial._LightmapTextureEnabled = true;
  42572. StandardMaterial._RefractionTextureEnabled = true;
  42573. StandardMaterial._ColorGradingTextureEnabled = true;
  42574. StandardMaterial._FresnelEnabled = true;
  42575. __decorate([
  42576. BABYLON.serializeAsTexture("diffuseTexture")
  42577. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  42578. __decorate([
  42579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42580. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  42581. __decorate([
  42582. BABYLON.serializeAsTexture("ambientTexture")
  42583. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  42584. __decorate([
  42585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42586. ], StandardMaterial.prototype, "ambientTexture", void 0);
  42587. __decorate([
  42588. BABYLON.serializeAsTexture("opacityTexture")
  42589. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  42590. __decorate([
  42591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42592. ], StandardMaterial.prototype, "opacityTexture", void 0);
  42593. __decorate([
  42594. BABYLON.serializeAsTexture("reflectionTexture")
  42595. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  42596. __decorate([
  42597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42598. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  42599. __decorate([
  42600. BABYLON.serializeAsTexture("emissiveTexture")
  42601. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  42602. __decorate([
  42603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42604. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  42605. __decorate([
  42606. BABYLON.serializeAsTexture("specularTexture")
  42607. ], StandardMaterial.prototype, "_specularTexture", void 0);
  42608. __decorate([
  42609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42610. ], StandardMaterial.prototype, "specularTexture", void 0);
  42611. __decorate([
  42612. BABYLON.serializeAsTexture("bumpTexture")
  42613. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  42614. __decorate([
  42615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42616. ], StandardMaterial.prototype, "bumpTexture", void 0);
  42617. __decorate([
  42618. BABYLON.serializeAsTexture("lightmapTexture")
  42619. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  42620. __decorate([
  42621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42622. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  42623. __decorate([
  42624. BABYLON.serializeAsTexture("refractionTexture")
  42625. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  42626. __decorate([
  42627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42628. ], StandardMaterial.prototype, "refractionTexture", void 0);
  42629. __decorate([
  42630. BABYLON.serializeAsColor3("ambient")
  42631. ], StandardMaterial.prototype, "ambientColor", void 0);
  42632. __decorate([
  42633. BABYLON.serializeAsColor3("diffuse")
  42634. ], StandardMaterial.prototype, "diffuseColor", void 0);
  42635. __decorate([
  42636. BABYLON.serializeAsColor3("specular")
  42637. ], StandardMaterial.prototype, "specularColor", void 0);
  42638. __decorate([
  42639. BABYLON.serializeAsColor3("emissive")
  42640. ], StandardMaterial.prototype, "emissiveColor", void 0);
  42641. __decorate([
  42642. BABYLON.serialize()
  42643. ], StandardMaterial.prototype, "specularPower", void 0);
  42644. __decorate([
  42645. BABYLON.serialize("useAlphaFromDiffuseTexture")
  42646. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  42647. __decorate([
  42648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42649. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  42650. __decorate([
  42651. BABYLON.serialize("useEmissiveAsIllumination")
  42652. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  42653. __decorate([
  42654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42655. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  42656. __decorate([
  42657. BABYLON.serialize("linkEmissiveWithDiffuse")
  42658. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  42659. __decorate([
  42660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42661. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  42662. __decorate([
  42663. BABYLON.serialize("useSpecularOverAlpha")
  42664. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  42665. __decorate([
  42666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42667. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  42668. __decorate([
  42669. BABYLON.serialize("useReflectionOverAlpha")
  42670. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  42671. __decorate([
  42672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42673. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  42674. __decorate([
  42675. BABYLON.serialize("disableLighting")
  42676. ], StandardMaterial.prototype, "_disableLighting", void 0);
  42677. __decorate([
  42678. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42679. ], StandardMaterial.prototype, "disableLighting", void 0);
  42680. __decorate([
  42681. BABYLON.serialize("useParallax")
  42682. ], StandardMaterial.prototype, "_useParallax", void 0);
  42683. __decorate([
  42684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42685. ], StandardMaterial.prototype, "useParallax", void 0);
  42686. __decorate([
  42687. BABYLON.serialize("useParallaxOcclusion")
  42688. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  42689. __decorate([
  42690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42691. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  42692. __decorate([
  42693. BABYLON.serialize()
  42694. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  42695. __decorate([
  42696. BABYLON.serialize("roughness")
  42697. ], StandardMaterial.prototype, "_roughness", void 0);
  42698. __decorate([
  42699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42700. ], StandardMaterial.prototype, "roughness", void 0);
  42701. __decorate([
  42702. BABYLON.serialize()
  42703. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  42704. __decorate([
  42705. BABYLON.serialize()
  42706. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  42707. __decorate([
  42708. BABYLON.serialize("useLightmapAsShadowmap")
  42709. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  42710. __decorate([
  42711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42712. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42713. __decorate([
  42714. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  42715. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  42716. __decorate([
  42717. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42718. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  42719. __decorate([
  42720. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  42721. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  42722. __decorate([
  42723. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42724. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  42725. __decorate([
  42726. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  42727. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  42728. __decorate([
  42729. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42730. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  42731. __decorate([
  42732. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  42733. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  42734. __decorate([
  42735. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42736. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  42737. __decorate([
  42738. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  42739. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  42740. __decorate([
  42741. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42742. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  42743. __decorate([
  42744. BABYLON.serialize("useReflectionFresnelFromSpecular")
  42745. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  42746. __decorate([
  42747. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  42748. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  42749. __decorate([
  42750. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  42751. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  42752. __decorate([
  42753. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42754. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  42755. __decorate([
  42756. BABYLON.serialize("maxSimultaneousLights")
  42757. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  42758. __decorate([
  42759. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42760. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  42761. __decorate([
  42762. BABYLON.serialize("invertNormalMapX")
  42763. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  42764. __decorate([
  42765. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42766. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  42767. __decorate([
  42768. BABYLON.serialize("invertNormalMapY")
  42769. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  42770. __decorate([
  42771. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42772. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  42773. __decorate([
  42774. BABYLON.serialize("twoSidedLighting")
  42775. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  42776. __decorate([
  42777. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42778. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  42779. __decorate([
  42780. BABYLON.serialize()
  42781. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  42782. BABYLON.StandardMaterial = StandardMaterial;
  42783. })(BABYLON || (BABYLON = {}));
  42784. //# sourceMappingURL=babylon.standardMaterial.js.map
  42785. var BABYLON;
  42786. (function (BABYLON) {
  42787. /**
  42788. * This class implement a typical dictionary using a string as key and the generic type T as value.
  42789. * The underlying implementation relies on an associative array to ensure the best performances.
  42790. * The value can be anything including 'null' but except 'undefined'
  42791. */
  42792. var StringDictionary = (function () {
  42793. function StringDictionary() {
  42794. this._count = 0;
  42795. this._data = {};
  42796. }
  42797. /**
  42798. * This will clear this dictionary and copy the content from the 'source' one.
  42799. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  42800. * @param source the dictionary to take the content from and copy to this dictionary
  42801. */
  42802. StringDictionary.prototype.copyFrom = function (source) {
  42803. var _this = this;
  42804. this.clear();
  42805. source.forEach(function (t, v) { return _this.add(t, v); });
  42806. };
  42807. /**
  42808. * Get a value based from its key
  42809. * @param key the given key to get the matching value from
  42810. * @return the value if found, otherwise undefined is returned
  42811. */
  42812. StringDictionary.prototype.get = function (key) {
  42813. var val = this._data[key];
  42814. if (val !== undefined) {
  42815. return val;
  42816. }
  42817. return undefined;
  42818. };
  42819. /**
  42820. * Get a value from its key or add it if it doesn't exist.
  42821. * This method will ensure you that a given key/data will be present in the dictionary.
  42822. * @param key the given key to get the matching value from
  42823. * @param factory the factory that will create the value if the key is not present in the dictionary.
  42824. * The factory will only be invoked if there's no data for the given key.
  42825. * @return the value corresponding to the key.
  42826. */
  42827. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  42828. var val = this.get(key);
  42829. if (val !== undefined) {
  42830. return val;
  42831. }
  42832. val = factory(key);
  42833. if (val) {
  42834. this.add(key, val);
  42835. }
  42836. return val;
  42837. };
  42838. /**
  42839. * Get a value from its key if present in the dictionary otherwise add it
  42840. * @param key the key to get the value from
  42841. * @param val if there's no such key/value pair in the dictionary add it with this value
  42842. * @return the value corresponding to the key
  42843. */
  42844. StringDictionary.prototype.getOrAdd = function (key, val) {
  42845. var curVal = this.get(key);
  42846. if (curVal !== undefined) {
  42847. return curVal;
  42848. }
  42849. this.add(key, val);
  42850. return val;
  42851. };
  42852. /**
  42853. * Check if there's a given key in the dictionary
  42854. * @param key the key to check for
  42855. * @return true if the key is present, false otherwise
  42856. */
  42857. StringDictionary.prototype.contains = function (key) {
  42858. return this._data[key] !== undefined;
  42859. };
  42860. /**
  42861. * Add a new key and its corresponding value
  42862. * @param key the key to add
  42863. * @param value the value corresponding to the key
  42864. * @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
  42865. */
  42866. StringDictionary.prototype.add = function (key, value) {
  42867. if (this._data[key] !== undefined) {
  42868. return false;
  42869. }
  42870. this._data[key] = value;
  42871. ++this._count;
  42872. return true;
  42873. };
  42874. StringDictionary.prototype.set = function (key, value) {
  42875. if (this._data[key] === undefined) {
  42876. return false;
  42877. }
  42878. this._data[key] = value;
  42879. return true;
  42880. };
  42881. /**
  42882. * Get the element of the given key and remove it from the dictionary
  42883. * @param key
  42884. */
  42885. StringDictionary.prototype.getAndRemove = function (key) {
  42886. var val = this.get(key);
  42887. if (val !== undefined) {
  42888. delete this._data[key];
  42889. --this._count;
  42890. return val;
  42891. }
  42892. return null;
  42893. };
  42894. /**
  42895. * Remove a key/value from the dictionary.
  42896. * @param key the key to remove
  42897. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  42898. */
  42899. StringDictionary.prototype.remove = function (key) {
  42900. if (this.contains(key)) {
  42901. delete this._data[key];
  42902. --this._count;
  42903. return true;
  42904. }
  42905. return false;
  42906. };
  42907. /**
  42908. * Clear the whole content of the dictionary
  42909. */
  42910. StringDictionary.prototype.clear = function () {
  42911. this._data = {};
  42912. this._count = 0;
  42913. };
  42914. Object.defineProperty(StringDictionary.prototype, "count", {
  42915. get: function () {
  42916. return this._count;
  42917. },
  42918. enumerable: true,
  42919. configurable: true
  42920. });
  42921. /**
  42922. * Execute a callback on each key/val of the dictionary.
  42923. * Note that you can remove any element in this dictionary in the callback implementation
  42924. * @param callback the callback to execute on a given key/value pair
  42925. */
  42926. StringDictionary.prototype.forEach = function (callback) {
  42927. for (var cur in this._data) {
  42928. var val = this._data[cur];
  42929. callback(cur, val);
  42930. }
  42931. };
  42932. /**
  42933. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  42934. * If the callback returns null or undefined the method will iterate to the next key/value pair
  42935. * Note that you can remove any element in this dictionary in the callback implementation
  42936. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  42937. */
  42938. StringDictionary.prototype.first = function (callback) {
  42939. for (var cur in this._data) {
  42940. var val = this._data[cur];
  42941. var res = callback(cur, val);
  42942. if (res) {
  42943. return res;
  42944. }
  42945. }
  42946. return null;
  42947. };
  42948. return StringDictionary;
  42949. }());
  42950. BABYLON.StringDictionary = StringDictionary;
  42951. })(BABYLON || (BABYLON = {}));
  42952. //# sourceMappingURL=babylon.stringDictionary.js.map
  42953. var BABYLON;
  42954. (function (BABYLON) {
  42955. var DynamicFloatArrayElementInfo = (function () {
  42956. function DynamicFloatArrayElementInfo() {
  42957. }
  42958. return DynamicFloatArrayElementInfo;
  42959. }());
  42960. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  42961. /**
  42962. * 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.
  42963. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  42964. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  42965. * 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.
  42966. * 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.
  42967. * 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".
  42968. */
  42969. var DynamicFloatArray = (function () {
  42970. /**
  42971. * Construct an instance of the dynamic float array
  42972. * @param stride size of one element in float (i.e. not bytes!)
  42973. * @param initialElementCount the number of available entries at construction
  42974. */
  42975. function DynamicFloatArray(stride, initialElementCount) {
  42976. this.compareValueOffset = null;
  42977. this.sortingAscending = true;
  42978. this._stride = stride;
  42979. this.buffer = new Float32Array(stride * initialElementCount);
  42980. this._lastUsed = 0;
  42981. this._firstFree = 0;
  42982. this._allEntries = new Array(initialElementCount);
  42983. this._freeEntries = new Array(initialElementCount);
  42984. for (var i = 0; i < initialElementCount; i++) {
  42985. var element = new DynamicFloatArrayElementInfo();
  42986. element.offset = i * stride;
  42987. this._allEntries[i] = element;
  42988. this._freeEntries[initialElementCount - i - 1] = element;
  42989. }
  42990. }
  42991. /**
  42992. * Allocate an element in the array.
  42993. * @return the element info instance that contains the offset into the main buffer of the element's location.
  42994. * Beware, this offset may change when you call pack()
  42995. */
  42996. DynamicFloatArray.prototype.allocElement = function () {
  42997. if (this._freeEntries.length === 0) {
  42998. this._growBuffer();
  42999. }
  43000. var el = this._freeEntries.pop();
  43001. this._lastUsed = Math.max(el.offset, this._lastUsed);
  43002. if (el.offset === this._firstFree) {
  43003. if (this._freeEntries.length > 0) {
  43004. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  43005. }
  43006. else {
  43007. this._firstFree += this._stride;
  43008. }
  43009. }
  43010. return el;
  43011. };
  43012. /**
  43013. * Free the element corresponding to the given element info
  43014. * @param elInfo the element that describe the allocated element
  43015. */
  43016. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  43017. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  43018. this._freeEntries.push(elInfo);
  43019. };
  43020. /**
  43021. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  43022. * 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().
  43023. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  43024. */
  43025. DynamicFloatArray.prototype.pack = function () {
  43026. // no free slot? no need to pack
  43027. if (this._freeEntries.length === 0) {
  43028. return this.buffer;
  43029. }
  43030. // If the buffer is already packed the last used will always be lower than the first free
  43031. // 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.
  43032. if (this._lastUsed < this._firstFree) {
  43033. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  43034. return elementsBuffer_1;
  43035. }
  43036. var s = this._stride;
  43037. // 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
  43038. var lastFree = new DynamicFloatArrayElementInfo();
  43039. lastFree.offset = this.totalElementCount * s;
  43040. this._freeEntries.push(lastFree);
  43041. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  43042. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43043. var firstFreeSlotOffset = sortedFree[0].offset;
  43044. var freeZoneSize = 1;
  43045. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  43046. var prevOffset = sortedFree[0].offset;
  43047. for (var i = 1; i < sortedFree.length; i++) {
  43048. // 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
  43049. if (firstFreeSlotOffset >= occupiedZoneSize) {
  43050. break;
  43051. }
  43052. var curFree = sortedFree[i];
  43053. var curOffset = curFree.offset;
  43054. // Compute the distance between this offset and the previous
  43055. var distance = curOffset - prevOffset;
  43056. // If the distance is the stride size, they are adjacent, it good, move to the next
  43057. if (distance === s) {
  43058. // Free zone is one element bigger
  43059. ++freeZoneSize;
  43060. // as we're about to iterate to the next, the cur becomes the previous...
  43061. prevOffset = curOffset;
  43062. continue;
  43063. }
  43064. // Distance is bigger, which means there's x element between the previous free and this one
  43065. var usedRange = (distance / s) - 1;
  43066. // Two cases the free zone is smaller than the data to move or bigger
  43067. // Copy what can fit in the free zone
  43068. var curMoveOffset = curOffset - s;
  43069. var copyCount = Math.min(freeZoneSize, usedRange);
  43070. for (var j = 0; j < copyCount; j++) {
  43071. var freeI = firstFreeSlotOffset / s;
  43072. var curI = curMoveOffset / s;
  43073. var moveEl = sortedAll[curI];
  43074. this._moveElement(moveEl, firstFreeSlotOffset);
  43075. var replacedEl = sortedAll[freeI];
  43076. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  43077. replacedEl.offset = curMoveOffset;
  43078. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  43079. sortedAll[freeI] = moveEl;
  43080. sortedAll[curI] = replacedEl;
  43081. curMoveOffset -= s;
  43082. firstFreeSlotOffset += s;
  43083. }
  43084. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  43085. if (freeZoneSize <= usedRange) {
  43086. firstFreeSlotOffset = curMoveOffset + s;
  43087. freeZoneSize = 1 + copyCount;
  43088. }
  43089. else {
  43090. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  43091. }
  43092. // as we're about to iterate to the next, the cur becomes the previous...
  43093. prevOffset = curOffset;
  43094. }
  43095. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  43096. this._lastUsed = firstFreeSlotOffset - s;
  43097. this._firstFree = firstFreeSlotOffset;
  43098. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  43099. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  43100. this._allEntries = sortedAll;
  43101. return elementsBuffer;
  43102. };
  43103. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  43104. for (var i = 0; i < this._stride; i++) {
  43105. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  43106. }
  43107. element.offset = destOffset;
  43108. };
  43109. DynamicFloatArray.prototype._growBuffer = function () {
  43110. // Allocate the new buffer with 50% more entries, copy the content of the current one
  43111. var newElCount = Math.floor(this.totalElementCount * 1.5);
  43112. var newBuffer = new Float32Array(newElCount * this._stride);
  43113. newBuffer.set(this.buffer);
  43114. var curCount = this.totalElementCount;
  43115. var addedCount = newElCount - this.totalElementCount;
  43116. for (var i = 0; i < addedCount; i++) {
  43117. var element = new DynamicFloatArrayElementInfo();
  43118. element.offset = (curCount + i) * this.stride;
  43119. this._allEntries.push(element);
  43120. this._freeEntries[addedCount - i - 1] = element;
  43121. }
  43122. this._firstFree = curCount * this.stride;
  43123. this.buffer = newBuffer;
  43124. };
  43125. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  43126. /**
  43127. * Get the total count of entries that can fit in the current buffer
  43128. * @returns the elements count
  43129. */
  43130. get: function () {
  43131. return this._allEntries.length;
  43132. },
  43133. enumerable: true,
  43134. configurable: true
  43135. });
  43136. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  43137. /**
  43138. * Get the count of free entries that can still be allocated without resizing the buffer
  43139. * @returns the free elements count
  43140. */
  43141. get: function () {
  43142. return this._freeEntries.length;
  43143. },
  43144. enumerable: true,
  43145. configurable: true
  43146. });
  43147. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  43148. /**
  43149. * Get the count of allocated elements
  43150. * @returns the allocated elements count
  43151. */
  43152. get: function () {
  43153. return this._allEntries.length - this._freeEntries.length;
  43154. },
  43155. enumerable: true,
  43156. configurable: true
  43157. });
  43158. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  43159. /**
  43160. * Return the size of one element in float
  43161. * @returns the size in float
  43162. */
  43163. get: function () {
  43164. return this._stride;
  43165. },
  43166. enumerable: true,
  43167. configurable: true
  43168. });
  43169. DynamicFloatArray.prototype.sort = function () {
  43170. var _this = this;
  43171. if (!this.compareValueOffset) {
  43172. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  43173. }
  43174. var count = this.usedElementCount;
  43175. // Do we have to (re)create the sort table?
  43176. if (!this._sortTable || this._sortTable.length < count) {
  43177. // 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...
  43178. var newCount = Math.min(this.totalElementCount, count * 2);
  43179. this._sortTable = new Array(newCount);
  43180. }
  43181. if (!this._sortedTable || this._sortedTable.length !== count) {
  43182. this._sortedTable = new Array(count);
  43183. }
  43184. // Because, you know...
  43185. this.pack();
  43186. //let stride = this.stride;
  43187. //for (let i = 0; i < count; i++) {
  43188. // let si = this._sortTable[i];
  43189. // if (!si) {
  43190. // si = new SortInfo();
  43191. // this._sortTable[i] = si;
  43192. // }
  43193. // si.entry = this._allEntries[i];
  43194. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  43195. // si.swapedOffset = null;
  43196. // this._sortedTable[i] = si;
  43197. //}
  43198. var curOffset = 0;
  43199. var stride = this.stride;
  43200. for (var i = 0; i < count; i++, curOffset += stride) {
  43201. var si = this._sortTable[i];
  43202. if (!si) {
  43203. si = new SortInfo();
  43204. this._sortTable[i] = si;
  43205. }
  43206. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  43207. si.offset = curOffset;
  43208. si.swapedOffset = null;
  43209. this._sortedTable[i] = si;
  43210. }
  43211. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  43212. if (this.sortingAscending) {
  43213. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  43214. }
  43215. else {
  43216. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  43217. }
  43218. var swapElements = function (src, dst) {
  43219. for (var i = 0; i < stride; i++) {
  43220. var tps = _this.buffer[dst + i];
  43221. _this.buffer[dst + i] = _this.buffer[src + i];
  43222. _this.buffer[src + i] = tps;
  43223. }
  43224. };
  43225. // 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:
  43226. // 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),
  43227. // and I still want something with a good algorithm complexity.
  43228. // 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,
  43229. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  43230. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  43231. // 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
  43232. // until we find a SortInfo object without a swapedOffset which means we got the right location
  43233. // 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
  43234. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  43235. for (var i = 0; i < count; i++) {
  43236. // Get the element to move
  43237. var sourceSI = this._sortedTable[i];
  43238. var destSI = this._sortTable[i];
  43239. var sourceOff = sourceSI.offset;
  43240. // If the source changed location, find the new one
  43241. if (sourceSI.swapedOffset) {
  43242. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  43243. var curSI = sourceSI;
  43244. while (curSI.swapedOffset) {
  43245. curSI = this._sortTable[curSI.swapedOffset / stride];
  43246. }
  43247. // Finally get the right location
  43248. sourceOff = curSI.offset;
  43249. }
  43250. // Tag the element being replaced with its new location
  43251. destSI.swapedOffset = sourceOff;
  43252. // Swap elements (only if needed)
  43253. if (sourceOff !== destSI.offset) {
  43254. swapElements(sourceOff, destSI.offset);
  43255. }
  43256. // Update the offset in the corresponding DFAE
  43257. //sourceSI.entry.offset = destSI.entry.offset;
  43258. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  43259. }
  43260. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  43261. return true;
  43262. };
  43263. return DynamicFloatArray;
  43264. }());
  43265. BABYLON.DynamicFloatArray = DynamicFloatArray;
  43266. var SortInfo = (function () {
  43267. function SortInfo() {
  43268. this.compareData = this.offset = this.swapedOffset = null;
  43269. }
  43270. return SortInfo;
  43271. }());
  43272. })(BABYLON || (BABYLON = {}));
  43273. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  43274. var BABYLON;
  43275. (function (BABYLON) {
  43276. var Condition = (function () {
  43277. function Condition(actionManager) {
  43278. this._actionManager = actionManager;
  43279. }
  43280. Condition.prototype.isValid = function () {
  43281. return true;
  43282. };
  43283. Condition.prototype._getProperty = function (propertyPath) {
  43284. return this._actionManager._getProperty(propertyPath);
  43285. };
  43286. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43287. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43288. };
  43289. Condition.prototype.serialize = function () {
  43290. };
  43291. Condition.prototype._serialize = function (serializedCondition) {
  43292. return {
  43293. type: 2,
  43294. children: [],
  43295. name: serializedCondition.name,
  43296. properties: serializedCondition.properties
  43297. };
  43298. };
  43299. return Condition;
  43300. }());
  43301. BABYLON.Condition = Condition;
  43302. var ValueCondition = (function (_super) {
  43303. __extends(ValueCondition, _super);
  43304. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43305. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43306. var _this = _super.call(this, actionManager) || this;
  43307. _this.propertyPath = propertyPath;
  43308. _this.value = value;
  43309. _this.operator = operator;
  43310. _this._target = target;
  43311. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43312. _this._property = _this._getProperty(_this.propertyPath);
  43313. return _this;
  43314. }
  43315. Object.defineProperty(ValueCondition, "IsEqual", {
  43316. get: function () {
  43317. return ValueCondition._IsEqual;
  43318. },
  43319. enumerable: true,
  43320. configurable: true
  43321. });
  43322. Object.defineProperty(ValueCondition, "IsDifferent", {
  43323. get: function () {
  43324. return ValueCondition._IsDifferent;
  43325. },
  43326. enumerable: true,
  43327. configurable: true
  43328. });
  43329. Object.defineProperty(ValueCondition, "IsGreater", {
  43330. get: function () {
  43331. return ValueCondition._IsGreater;
  43332. },
  43333. enumerable: true,
  43334. configurable: true
  43335. });
  43336. Object.defineProperty(ValueCondition, "IsLesser", {
  43337. get: function () {
  43338. return ValueCondition._IsLesser;
  43339. },
  43340. enumerable: true,
  43341. configurable: true
  43342. });
  43343. // Methods
  43344. ValueCondition.prototype.isValid = function () {
  43345. switch (this.operator) {
  43346. case ValueCondition.IsGreater:
  43347. return this._effectiveTarget[this._property] > this.value;
  43348. case ValueCondition.IsLesser:
  43349. return this._effectiveTarget[this._property] < this.value;
  43350. case ValueCondition.IsEqual:
  43351. case ValueCondition.IsDifferent:
  43352. var check;
  43353. if (this.value.equals) {
  43354. check = this.value.equals(this._effectiveTarget[this._property]);
  43355. }
  43356. else {
  43357. check = this.value === this._effectiveTarget[this._property];
  43358. }
  43359. return this.operator === ValueCondition.IsEqual ? check : !check;
  43360. }
  43361. return false;
  43362. };
  43363. ValueCondition.prototype.serialize = function () {
  43364. return this._serialize({
  43365. name: "ValueCondition",
  43366. properties: [
  43367. BABYLON.Action._GetTargetProperty(this._target),
  43368. { name: "propertyPath", value: this.propertyPath },
  43369. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43370. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43371. ]
  43372. });
  43373. };
  43374. ValueCondition.GetOperatorName = function (operator) {
  43375. switch (operator) {
  43376. case ValueCondition._IsEqual: return "IsEqual";
  43377. case ValueCondition._IsDifferent: return "IsDifferent";
  43378. case ValueCondition._IsGreater: return "IsGreater";
  43379. case ValueCondition._IsLesser: return "IsLesser";
  43380. default: return "";
  43381. }
  43382. };
  43383. return ValueCondition;
  43384. }(Condition));
  43385. // Statics
  43386. ValueCondition._IsEqual = 0;
  43387. ValueCondition._IsDifferent = 1;
  43388. ValueCondition._IsGreater = 2;
  43389. ValueCondition._IsLesser = 3;
  43390. BABYLON.ValueCondition = ValueCondition;
  43391. var PredicateCondition = (function (_super) {
  43392. __extends(PredicateCondition, _super);
  43393. function PredicateCondition(actionManager, predicate) {
  43394. var _this = _super.call(this, actionManager) || this;
  43395. _this.predicate = predicate;
  43396. return _this;
  43397. }
  43398. PredicateCondition.prototype.isValid = function () {
  43399. return this.predicate();
  43400. };
  43401. return PredicateCondition;
  43402. }(Condition));
  43403. BABYLON.PredicateCondition = PredicateCondition;
  43404. var StateCondition = (function (_super) {
  43405. __extends(StateCondition, _super);
  43406. function StateCondition(actionManager, target, value) {
  43407. var _this = _super.call(this, actionManager) || this;
  43408. _this.value = value;
  43409. _this._target = target;
  43410. return _this;
  43411. }
  43412. // Methods
  43413. StateCondition.prototype.isValid = function () {
  43414. return this._target.state === this.value;
  43415. };
  43416. StateCondition.prototype.serialize = function () {
  43417. return this._serialize({
  43418. name: "StateCondition",
  43419. properties: [
  43420. BABYLON.Action._GetTargetProperty(this._target),
  43421. { name: "value", value: this.value }
  43422. ]
  43423. });
  43424. };
  43425. return StateCondition;
  43426. }(Condition));
  43427. BABYLON.StateCondition = StateCondition;
  43428. })(BABYLON || (BABYLON = {}));
  43429. //# sourceMappingURL=babylon.condition.js.map
  43430. var BABYLON;
  43431. (function (BABYLON) {
  43432. var Action = (function () {
  43433. function Action(triggerOptions, condition) {
  43434. this.triggerOptions = triggerOptions;
  43435. if (triggerOptions.parameter) {
  43436. this.trigger = triggerOptions.trigger;
  43437. this._triggerParameter = triggerOptions.parameter;
  43438. }
  43439. else {
  43440. this.trigger = triggerOptions;
  43441. }
  43442. this._nextActiveAction = this;
  43443. this._condition = condition;
  43444. }
  43445. // Methods
  43446. Action.prototype._prepare = function () {
  43447. };
  43448. Action.prototype.getTriggerParameter = function () {
  43449. return this._triggerParameter;
  43450. };
  43451. Action.prototype._executeCurrent = function (evt) {
  43452. if (this._nextActiveAction._condition) {
  43453. var condition = this._nextActiveAction._condition;
  43454. var currentRenderId = this._actionManager.getScene().getRenderId();
  43455. // We cache the current evaluation for the current frame
  43456. if (condition._evaluationId === currentRenderId) {
  43457. if (!condition._currentResult) {
  43458. return;
  43459. }
  43460. }
  43461. else {
  43462. condition._evaluationId = currentRenderId;
  43463. if (!condition.isValid()) {
  43464. condition._currentResult = false;
  43465. return;
  43466. }
  43467. condition._currentResult = true;
  43468. }
  43469. }
  43470. this._nextActiveAction.execute(evt);
  43471. this.skipToNextActiveAction();
  43472. };
  43473. Action.prototype.execute = function (evt) {
  43474. };
  43475. Action.prototype.skipToNextActiveAction = function () {
  43476. if (this._nextActiveAction._child) {
  43477. if (!this._nextActiveAction._child._actionManager) {
  43478. this._nextActiveAction._child._actionManager = this._actionManager;
  43479. }
  43480. this._nextActiveAction = this._nextActiveAction._child;
  43481. }
  43482. else {
  43483. this._nextActiveAction = this;
  43484. }
  43485. };
  43486. Action.prototype.then = function (action) {
  43487. this._child = action;
  43488. action._actionManager = this._actionManager;
  43489. action._prepare();
  43490. return action;
  43491. };
  43492. Action.prototype._getProperty = function (propertyPath) {
  43493. return this._actionManager._getProperty(propertyPath);
  43494. };
  43495. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43496. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43497. };
  43498. Action.prototype.serialize = function (parent) {
  43499. };
  43500. // Called by BABYLON.Action objects in serialize(...). Internal use
  43501. Action.prototype._serialize = function (serializedAction, parent) {
  43502. var serializationObject = {
  43503. type: 1,
  43504. children: [],
  43505. name: serializedAction.name,
  43506. properties: serializedAction.properties || []
  43507. };
  43508. // Serialize child
  43509. if (this._child) {
  43510. this._child.serialize(serializationObject);
  43511. }
  43512. // Check if "this" has a condition
  43513. if (this._condition) {
  43514. var serializedCondition = this._condition.serialize();
  43515. serializedCondition.children.push(serializationObject);
  43516. if (parent) {
  43517. parent.children.push(serializedCondition);
  43518. }
  43519. return serializedCondition;
  43520. }
  43521. if (parent) {
  43522. parent.children.push(serializationObject);
  43523. }
  43524. return serializationObject;
  43525. };
  43526. return Action;
  43527. }());
  43528. Action._SerializeValueAsString = function (value) {
  43529. if (typeof value === "number") {
  43530. return value.toString();
  43531. }
  43532. if (typeof value === "boolean") {
  43533. return value ? "true" : "false";
  43534. }
  43535. if (value instanceof BABYLON.Vector2) {
  43536. return value.x + ", " + value.y;
  43537. }
  43538. if (value instanceof BABYLON.Vector3) {
  43539. return value.x + ", " + value.y + ", " + value.z;
  43540. }
  43541. if (value instanceof BABYLON.Color3) {
  43542. return value.r + ", " + value.g + ", " + value.b;
  43543. }
  43544. if (value instanceof BABYLON.Color4) {
  43545. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43546. }
  43547. return value; // string
  43548. };
  43549. Action._GetTargetProperty = function (target) {
  43550. return {
  43551. name: "target",
  43552. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43553. : target instanceof BABYLON.Light ? "LightProperties"
  43554. : target instanceof BABYLON.Camera ? "CameraProperties"
  43555. : "SceneProperties",
  43556. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43557. };
  43558. };
  43559. BABYLON.Action = Action;
  43560. })(BABYLON || (BABYLON = {}));
  43561. //# sourceMappingURL=babylon.action.js.map
  43562. var BABYLON;
  43563. (function (BABYLON) {
  43564. /**
  43565. * ActionEvent is the event beint sent when an action is triggered.
  43566. */
  43567. var ActionEvent = (function () {
  43568. /**
  43569. * @constructor
  43570. * @param source The mesh or sprite that triggered the action.
  43571. * @param pointerX The X mouse cursor position at the time of the event
  43572. * @param pointerY The Y mouse cursor position at the time of the event
  43573. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43574. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43575. */
  43576. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43577. this.source = source;
  43578. this.pointerX = pointerX;
  43579. this.pointerY = pointerY;
  43580. this.meshUnderPointer = meshUnderPointer;
  43581. this.sourceEvent = sourceEvent;
  43582. this.additionalData = additionalData;
  43583. }
  43584. /**
  43585. * Helper function to auto-create an ActionEvent from a source mesh.
  43586. * @param source The source mesh that triggered the event
  43587. * @param evt {Event} The original (browser) event
  43588. */
  43589. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43590. var scene = source.getScene();
  43591. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43592. };
  43593. /**
  43594. * Helper function to auto-create an ActionEvent from a source mesh.
  43595. * @param source The source sprite that triggered the event
  43596. * @param scene Scene associated with the sprite
  43597. * @param evt {Event} The original (browser) event
  43598. */
  43599. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43600. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43601. };
  43602. /**
  43603. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43604. * @param scene the scene where the event occurred
  43605. * @param evt {Event} The original (browser) event
  43606. */
  43607. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43608. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43609. };
  43610. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43611. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43612. };
  43613. return ActionEvent;
  43614. }());
  43615. BABYLON.ActionEvent = ActionEvent;
  43616. /**
  43617. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43618. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43619. */
  43620. var ActionManager = (function () {
  43621. function ActionManager(scene) {
  43622. // Members
  43623. this.actions = new Array();
  43624. this.hoverCursor = '';
  43625. this._scene = scene;
  43626. scene._actionManagers.push(this);
  43627. }
  43628. Object.defineProperty(ActionManager, "NothingTrigger", {
  43629. get: function () {
  43630. return ActionManager._NothingTrigger;
  43631. },
  43632. enumerable: true,
  43633. configurable: true
  43634. });
  43635. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43636. get: function () {
  43637. return ActionManager._OnPickTrigger;
  43638. },
  43639. enumerable: true,
  43640. configurable: true
  43641. });
  43642. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43643. get: function () {
  43644. return ActionManager._OnLeftPickTrigger;
  43645. },
  43646. enumerable: true,
  43647. configurable: true
  43648. });
  43649. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43650. get: function () {
  43651. return ActionManager._OnRightPickTrigger;
  43652. },
  43653. enumerable: true,
  43654. configurable: true
  43655. });
  43656. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43657. get: function () {
  43658. return ActionManager._OnCenterPickTrigger;
  43659. },
  43660. enumerable: true,
  43661. configurable: true
  43662. });
  43663. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43664. get: function () {
  43665. return ActionManager._OnPickDownTrigger;
  43666. },
  43667. enumerable: true,
  43668. configurable: true
  43669. });
  43670. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43671. get: function () {
  43672. return ActionManager._OnDoublePickTrigger;
  43673. },
  43674. enumerable: true,
  43675. configurable: true
  43676. });
  43677. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43678. get: function () {
  43679. return ActionManager._OnPickUpTrigger;
  43680. },
  43681. enumerable: true,
  43682. configurable: true
  43683. });
  43684. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43685. /// This trigger will only be raised if you also declared a OnPickDown
  43686. get: function () {
  43687. return ActionManager._OnPickOutTrigger;
  43688. },
  43689. enumerable: true,
  43690. configurable: true
  43691. });
  43692. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43693. get: function () {
  43694. return ActionManager._OnLongPressTrigger;
  43695. },
  43696. enumerable: true,
  43697. configurable: true
  43698. });
  43699. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43700. get: function () {
  43701. return ActionManager._OnPointerOverTrigger;
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43707. get: function () {
  43708. return ActionManager._OnPointerOutTrigger;
  43709. },
  43710. enumerable: true,
  43711. configurable: true
  43712. });
  43713. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43714. get: function () {
  43715. return ActionManager._OnEveryFrameTrigger;
  43716. },
  43717. enumerable: true,
  43718. configurable: true
  43719. });
  43720. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43721. get: function () {
  43722. return ActionManager._OnIntersectionEnterTrigger;
  43723. },
  43724. enumerable: true,
  43725. configurable: true
  43726. });
  43727. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43728. get: function () {
  43729. return ActionManager._OnIntersectionExitTrigger;
  43730. },
  43731. enumerable: true,
  43732. configurable: true
  43733. });
  43734. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43735. get: function () {
  43736. return ActionManager._OnKeyDownTrigger;
  43737. },
  43738. enumerable: true,
  43739. configurable: true
  43740. });
  43741. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43742. get: function () {
  43743. return ActionManager._OnKeyUpTrigger;
  43744. },
  43745. enumerable: true,
  43746. configurable: true
  43747. });
  43748. // Methods
  43749. ActionManager.prototype.dispose = function () {
  43750. var index = this._scene._actionManagers.indexOf(this);
  43751. for (var i = 0; i < this.actions.length; i++) {
  43752. var action = this.actions[i];
  43753. ActionManager.Triggers[action.trigger]--;
  43754. if (ActionManager.Triggers[action.trigger] === 0) {
  43755. delete ActionManager.Triggers[action.trigger];
  43756. }
  43757. }
  43758. if (index > -1) {
  43759. this._scene._actionManagers.splice(index, 1);
  43760. }
  43761. };
  43762. ActionManager.prototype.getScene = function () {
  43763. return this._scene;
  43764. };
  43765. /**
  43766. * Does this action manager handles actions of any of the given triggers
  43767. * @param {number[]} triggers - the triggers to be tested
  43768. * @return {boolean} whether one (or more) of the triggers is handeled
  43769. */
  43770. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43771. for (var index = 0; index < this.actions.length; index++) {
  43772. var action = this.actions[index];
  43773. if (triggers.indexOf(action.trigger) > -1) {
  43774. return true;
  43775. }
  43776. }
  43777. return false;
  43778. };
  43779. /**
  43780. * Does this action manager handles actions of a given trigger
  43781. * @param {number} trigger - the trigger to be tested
  43782. * @return {boolean} whether the trigger is handeled
  43783. */
  43784. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43785. for (var index = 0; index < this.actions.length; index++) {
  43786. var action = this.actions[index];
  43787. if (action.trigger === trigger) {
  43788. return true;
  43789. }
  43790. }
  43791. return false;
  43792. };
  43793. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43794. /**
  43795. * Does this action manager has pointer triggers
  43796. * @return {boolean} whether or not it has pointer triggers
  43797. */
  43798. get: function () {
  43799. for (var index = 0; index < this.actions.length; index++) {
  43800. var action = this.actions[index];
  43801. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43802. return true;
  43803. }
  43804. }
  43805. return false;
  43806. },
  43807. enumerable: true,
  43808. configurable: true
  43809. });
  43810. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43811. /**
  43812. * Does this action manager has pick triggers
  43813. * @return {boolean} whether or not it has pick triggers
  43814. */
  43815. get: function () {
  43816. for (var index = 0; index < this.actions.length; index++) {
  43817. var action = this.actions[index];
  43818. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43819. return true;
  43820. }
  43821. }
  43822. return false;
  43823. },
  43824. enumerable: true,
  43825. configurable: true
  43826. });
  43827. Object.defineProperty(ActionManager, "HasTriggers", {
  43828. /**
  43829. * Does exist one action manager with at least one trigger
  43830. * @return {boolean} whether or not it exists one action manager with one trigger
  43831. **/
  43832. get: function () {
  43833. for (var t in ActionManager.Triggers) {
  43834. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43835. return true;
  43836. }
  43837. }
  43838. return false;
  43839. },
  43840. enumerable: true,
  43841. configurable: true
  43842. });
  43843. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43844. /**
  43845. * Does exist one action manager with at least one pick trigger
  43846. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43847. **/
  43848. get: function () {
  43849. for (var t in ActionManager.Triggers) {
  43850. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43851. var t_int = parseInt(t);
  43852. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43853. return true;
  43854. }
  43855. }
  43856. }
  43857. return false;
  43858. },
  43859. enumerable: true,
  43860. configurable: true
  43861. });
  43862. /**
  43863. * Does exist one action manager that handles actions of a given trigger
  43864. * @param {number} trigger - the trigger to be tested
  43865. * @return {boolean} whether the trigger is handeled by at least one action manager
  43866. **/
  43867. ActionManager.HasSpecificTrigger = function (trigger) {
  43868. for (var t in ActionManager.Triggers) {
  43869. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43870. var t_int = parseInt(t);
  43871. if (t_int === trigger) {
  43872. return true;
  43873. }
  43874. }
  43875. }
  43876. return false;
  43877. };
  43878. /**
  43879. * Registers an action to this action manager
  43880. * @param {BABYLON.Action} action - the action to be registered
  43881. * @return {BABYLON.Action} the action amended (prepared) after registration
  43882. */
  43883. ActionManager.prototype.registerAction = function (action) {
  43884. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43885. if (this.getScene().actionManager !== this) {
  43886. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43887. return null;
  43888. }
  43889. }
  43890. this.actions.push(action);
  43891. if (ActionManager.Triggers[action.trigger]) {
  43892. ActionManager.Triggers[action.trigger]++;
  43893. }
  43894. else {
  43895. ActionManager.Triggers[action.trigger] = 1;
  43896. }
  43897. action._actionManager = this;
  43898. action._prepare();
  43899. return action;
  43900. };
  43901. /**
  43902. * Process a specific trigger
  43903. * @param {number} trigger - the trigger to process
  43904. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43905. */
  43906. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43907. for (var index = 0; index < this.actions.length; index++) {
  43908. var action = this.actions[index];
  43909. if (action.trigger === trigger) {
  43910. if (trigger === ActionManager.OnKeyUpTrigger
  43911. || trigger === ActionManager.OnKeyDownTrigger) {
  43912. var parameter = action.getTriggerParameter();
  43913. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43914. if (!parameter.toLowerCase) {
  43915. continue;
  43916. }
  43917. var lowerCase = parameter.toLowerCase();
  43918. if (lowerCase !== evt.sourceEvent.key) {
  43919. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43920. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43921. if (actualkey !== lowerCase) {
  43922. continue;
  43923. }
  43924. }
  43925. }
  43926. }
  43927. action._executeCurrent(evt);
  43928. }
  43929. }
  43930. };
  43931. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43932. var properties = propertyPath.split(".");
  43933. for (var index = 0; index < properties.length - 1; index++) {
  43934. target = target[properties[index]];
  43935. }
  43936. return target;
  43937. };
  43938. ActionManager.prototype._getProperty = function (propertyPath) {
  43939. var properties = propertyPath.split(".");
  43940. return properties[properties.length - 1];
  43941. };
  43942. ActionManager.prototype.serialize = function (name) {
  43943. var root = {
  43944. children: [],
  43945. name: name,
  43946. type: 3,
  43947. properties: [] // Empty for root but required
  43948. };
  43949. for (var i = 0; i < this.actions.length; i++) {
  43950. var triggerObject = {
  43951. type: 0,
  43952. children: [],
  43953. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43954. properties: []
  43955. };
  43956. var triggerOptions = this.actions[i].triggerOptions;
  43957. if (triggerOptions && typeof triggerOptions !== "number") {
  43958. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43959. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43960. }
  43961. else {
  43962. var parameter = {};
  43963. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43964. if (triggerOptions.parameter.mesh) {
  43965. parameter._meshId = triggerOptions.parameter.mesh.id;
  43966. }
  43967. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43968. }
  43969. }
  43970. // Serialize child action, recursively
  43971. this.actions[i].serialize(triggerObject);
  43972. // Add serialized trigger
  43973. root.children.push(triggerObject);
  43974. }
  43975. return root;
  43976. };
  43977. ActionManager.Parse = function (parsedActions, object, scene) {
  43978. var actionManager = new BABYLON.ActionManager(scene);
  43979. if (object === null)
  43980. scene.actionManager = actionManager;
  43981. else
  43982. object.actionManager = actionManager;
  43983. // instanciate a new object
  43984. var instanciate = function (name, params) {
  43985. var newInstance = Object.create(BABYLON[name].prototype);
  43986. newInstance.constructor.apply(newInstance, params);
  43987. return newInstance;
  43988. };
  43989. var parseParameter = function (name, value, target, propertyPath) {
  43990. if (propertyPath === null) {
  43991. // String, boolean or float
  43992. var floatValue = parseFloat(value);
  43993. if (value === "true" || value === "false")
  43994. return value === "true";
  43995. else
  43996. return isNaN(floatValue) ? value : floatValue;
  43997. }
  43998. var effectiveTarget = propertyPath.split(".");
  43999. var values = value.split(",");
  44000. // Get effective Target
  44001. for (var i = 0; i < effectiveTarget.length; i++) {
  44002. target = target[effectiveTarget[i]];
  44003. }
  44004. // Return appropriate value with its type
  44005. if (typeof (target) === "boolean")
  44006. return values[0] === "true";
  44007. if (typeof (target) === "string")
  44008. return values[0];
  44009. // Parameters with multiple values such as Vector3 etc.
  44010. var split = new Array();
  44011. for (var i = 0; i < values.length; i++)
  44012. split.push(parseFloat(values[i]));
  44013. if (target instanceof BABYLON.Vector3)
  44014. return BABYLON.Vector3.FromArray(split);
  44015. if (target instanceof BABYLON.Vector4)
  44016. return BABYLON.Vector4.FromArray(split);
  44017. if (target instanceof BABYLON.Color3)
  44018. return BABYLON.Color3.FromArray(split);
  44019. if (target instanceof BABYLON.Color4)
  44020. return BABYLON.Color4.FromArray(split);
  44021. return parseFloat(values[0]);
  44022. };
  44023. // traverse graph per trigger
  44024. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44025. if (combineArray === void 0) { combineArray = null; }
  44026. if (parsedAction.detached)
  44027. return;
  44028. var parameters = new Array();
  44029. var target = null;
  44030. var propertyPath = null;
  44031. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44032. // Parameters
  44033. if (parsedAction.type === 2)
  44034. parameters.push(actionManager);
  44035. else
  44036. parameters.push(trigger);
  44037. if (combine) {
  44038. var actions = new Array();
  44039. for (var j = 0; j < parsedAction.combine.length; j++) {
  44040. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44041. }
  44042. parameters.push(actions);
  44043. }
  44044. else {
  44045. for (var i = 0; i < parsedAction.properties.length; i++) {
  44046. var value = parsedAction.properties[i].value;
  44047. var name = parsedAction.properties[i].name;
  44048. var targetType = parsedAction.properties[i].targetType;
  44049. if (name === "target")
  44050. if (targetType !== null && targetType === "SceneProperties")
  44051. value = target = scene;
  44052. else
  44053. value = target = scene.getNodeByName(value);
  44054. else if (name === "parent")
  44055. value = scene.getNodeByName(value);
  44056. else if (name === "sound")
  44057. value = scene.getSoundByName(value);
  44058. else if (name !== "propertyPath") {
  44059. if (parsedAction.type === 2 && name === "operator")
  44060. value = BABYLON.ValueCondition[value];
  44061. else
  44062. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44063. }
  44064. else {
  44065. propertyPath = value;
  44066. }
  44067. parameters.push(value);
  44068. }
  44069. }
  44070. if (combineArray === null) {
  44071. parameters.push(condition);
  44072. }
  44073. else {
  44074. parameters.push(null);
  44075. }
  44076. // If interpolate value action
  44077. if (parsedAction.name === "InterpolateValueAction") {
  44078. var param = parameters[parameters.length - 2];
  44079. parameters[parameters.length - 1] = param;
  44080. parameters[parameters.length - 2] = condition;
  44081. }
  44082. // Action or condition(s) and not CombineAction
  44083. var newAction = instanciate(parsedAction.name, parameters);
  44084. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44085. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44086. if (action)
  44087. action.then(nothing);
  44088. else
  44089. actionManager.registerAction(nothing);
  44090. action = nothing;
  44091. }
  44092. if (combineArray === null) {
  44093. if (newAction instanceof BABYLON.Condition) {
  44094. condition = newAction;
  44095. newAction = action;
  44096. }
  44097. else {
  44098. condition = null;
  44099. if (action)
  44100. action.then(newAction);
  44101. else
  44102. actionManager.registerAction(newAction);
  44103. }
  44104. }
  44105. else {
  44106. combineArray.push(newAction);
  44107. }
  44108. for (var i = 0; i < parsedAction.children.length; i++)
  44109. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44110. };
  44111. // triggers
  44112. for (var i = 0; i < parsedActions.children.length; i++) {
  44113. var triggerParams;
  44114. var trigger = parsedActions.children[i];
  44115. if (trigger.properties.length > 0) {
  44116. var param = trigger.properties[0].value;
  44117. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44118. if (value._meshId) {
  44119. value.mesh = scene.getMeshByID(value._meshId);
  44120. }
  44121. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  44122. }
  44123. else
  44124. triggerParams = BABYLON.ActionManager[trigger.name];
  44125. for (var j = 0; j < trigger.children.length; j++) {
  44126. if (!trigger.detached)
  44127. traverse(trigger.children[j], triggerParams, null, null);
  44128. }
  44129. }
  44130. };
  44131. ActionManager.GetTriggerName = function (trigger) {
  44132. switch (trigger) {
  44133. case 0: return "NothingTrigger";
  44134. case 1: return "OnPickTrigger";
  44135. case 2: return "OnLeftPickTrigger";
  44136. case 3: return "OnRightPickTrigger";
  44137. case 4: return "OnCenterPickTrigger";
  44138. case 5: return "OnPickDownTrigger";
  44139. case 6: return "OnPickUpTrigger";
  44140. case 7: return "OnLongPressTrigger";
  44141. case 8: return "OnPointerOverTrigger";
  44142. case 9: return "OnPointerOutTrigger";
  44143. case 10: return "OnEveryFrameTrigger";
  44144. case 11: return "OnIntersectionEnterTrigger";
  44145. case 12: return "OnIntersectionExitTrigger";
  44146. case 13: return "OnKeyDownTrigger";
  44147. case 14: return "OnKeyUpTrigger";
  44148. case 15: return "OnPickOutTrigger";
  44149. default: return "";
  44150. }
  44151. };
  44152. return ActionManager;
  44153. }());
  44154. // Statics
  44155. ActionManager._NothingTrigger = 0;
  44156. ActionManager._OnPickTrigger = 1;
  44157. ActionManager._OnLeftPickTrigger = 2;
  44158. ActionManager._OnRightPickTrigger = 3;
  44159. ActionManager._OnCenterPickTrigger = 4;
  44160. ActionManager._OnPickDownTrigger = 5;
  44161. ActionManager._OnDoublePickTrigger = 6;
  44162. ActionManager._OnPickUpTrigger = 7;
  44163. ActionManager._OnLongPressTrigger = 8;
  44164. ActionManager._OnPointerOverTrigger = 9;
  44165. ActionManager._OnPointerOutTrigger = 10;
  44166. ActionManager._OnEveryFrameTrigger = 11;
  44167. ActionManager._OnIntersectionEnterTrigger = 12;
  44168. ActionManager._OnIntersectionExitTrigger = 13;
  44169. ActionManager._OnKeyDownTrigger = 14;
  44170. ActionManager._OnKeyUpTrigger = 15;
  44171. ActionManager._OnPickOutTrigger = 16;
  44172. ActionManager.Triggers = {};
  44173. BABYLON.ActionManager = ActionManager;
  44174. })(BABYLON || (BABYLON = {}));
  44175. //# sourceMappingURL=babylon.actionManager.js.map
  44176. var BABYLON;
  44177. (function (BABYLON) {
  44178. var InterpolateValueAction = (function (_super) {
  44179. __extends(InterpolateValueAction, _super);
  44180. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44181. if (duration === void 0) { duration = 1000; }
  44182. var _this = _super.call(this, triggerOptions, condition) || this;
  44183. _this.propertyPath = propertyPath;
  44184. _this.value = value;
  44185. _this.duration = duration;
  44186. _this.stopOtherAnimations = stopOtherAnimations;
  44187. _this.onInterpolationDone = onInterpolationDone;
  44188. _this._target = _this._effectiveTarget = target;
  44189. return _this;
  44190. }
  44191. InterpolateValueAction.prototype._prepare = function () {
  44192. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44193. this._property = this._getProperty(this.propertyPath);
  44194. };
  44195. InterpolateValueAction.prototype.execute = function () {
  44196. var scene = this._actionManager.getScene();
  44197. var keys = [
  44198. {
  44199. frame: 0,
  44200. value: this._effectiveTarget[this._property]
  44201. }, {
  44202. frame: 100,
  44203. value: this.value
  44204. }
  44205. ];
  44206. var dataType;
  44207. if (typeof this.value === "number") {
  44208. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44209. }
  44210. else if (this.value instanceof BABYLON.Color3) {
  44211. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44212. }
  44213. else if (this.value instanceof BABYLON.Vector3) {
  44214. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44215. }
  44216. else if (this.value instanceof BABYLON.Matrix) {
  44217. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44218. }
  44219. else if (this.value instanceof BABYLON.Quaternion) {
  44220. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44221. }
  44222. else {
  44223. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44224. return;
  44225. }
  44226. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44227. animation.setKeys(keys);
  44228. if (this.stopOtherAnimations) {
  44229. scene.stopAnimation(this._effectiveTarget);
  44230. }
  44231. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  44232. };
  44233. InterpolateValueAction.prototype.serialize = function (parent) {
  44234. return _super.prototype._serialize.call(this, {
  44235. name: "InterpolateValueAction",
  44236. properties: [
  44237. BABYLON.Action._GetTargetProperty(this._target),
  44238. { name: "propertyPath", value: this.propertyPath },
  44239. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44240. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44241. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44242. ]
  44243. }, parent);
  44244. };
  44245. return InterpolateValueAction;
  44246. }(BABYLON.Action));
  44247. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44248. })(BABYLON || (BABYLON = {}));
  44249. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44250. var BABYLON;
  44251. (function (BABYLON) {
  44252. var SwitchBooleanAction = (function (_super) {
  44253. __extends(SwitchBooleanAction, _super);
  44254. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44255. var _this = _super.call(this, triggerOptions, condition) || this;
  44256. _this.propertyPath = propertyPath;
  44257. _this._target = _this._effectiveTarget = target;
  44258. return _this;
  44259. }
  44260. SwitchBooleanAction.prototype._prepare = function () {
  44261. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44262. this._property = this._getProperty(this.propertyPath);
  44263. };
  44264. SwitchBooleanAction.prototype.execute = function () {
  44265. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44266. };
  44267. SwitchBooleanAction.prototype.serialize = function (parent) {
  44268. return _super.prototype._serialize.call(this, {
  44269. name: "SwitchBooleanAction",
  44270. properties: [
  44271. BABYLON.Action._GetTargetProperty(this._target),
  44272. { name: "propertyPath", value: this.propertyPath }
  44273. ]
  44274. }, parent);
  44275. };
  44276. return SwitchBooleanAction;
  44277. }(BABYLON.Action));
  44278. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44279. var SetStateAction = (function (_super) {
  44280. __extends(SetStateAction, _super);
  44281. function SetStateAction(triggerOptions, target, value, condition) {
  44282. var _this = _super.call(this, triggerOptions, condition) || this;
  44283. _this.value = value;
  44284. _this._target = target;
  44285. return _this;
  44286. }
  44287. SetStateAction.prototype.execute = function () {
  44288. this._target.state = this.value;
  44289. };
  44290. SetStateAction.prototype.serialize = function (parent) {
  44291. return _super.prototype._serialize.call(this, {
  44292. name: "SetStateAction",
  44293. properties: [
  44294. BABYLON.Action._GetTargetProperty(this._target),
  44295. { name: "value", value: this.value }
  44296. ]
  44297. }, parent);
  44298. };
  44299. return SetStateAction;
  44300. }(BABYLON.Action));
  44301. BABYLON.SetStateAction = SetStateAction;
  44302. var SetValueAction = (function (_super) {
  44303. __extends(SetValueAction, _super);
  44304. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44305. var _this = _super.call(this, triggerOptions, condition) || this;
  44306. _this.propertyPath = propertyPath;
  44307. _this.value = value;
  44308. _this._target = _this._effectiveTarget = target;
  44309. return _this;
  44310. }
  44311. SetValueAction.prototype._prepare = function () {
  44312. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44313. this._property = this._getProperty(this.propertyPath);
  44314. };
  44315. SetValueAction.prototype.execute = function () {
  44316. this._effectiveTarget[this._property] = this.value;
  44317. if (this._target.markAsDirty) {
  44318. this._target.markAsDirty(this._property);
  44319. }
  44320. };
  44321. SetValueAction.prototype.serialize = function (parent) {
  44322. return _super.prototype._serialize.call(this, {
  44323. name: "SetValueAction",
  44324. properties: [
  44325. BABYLON.Action._GetTargetProperty(this._target),
  44326. { name: "propertyPath", value: this.propertyPath },
  44327. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44328. ]
  44329. }, parent);
  44330. };
  44331. return SetValueAction;
  44332. }(BABYLON.Action));
  44333. BABYLON.SetValueAction = SetValueAction;
  44334. var IncrementValueAction = (function (_super) {
  44335. __extends(IncrementValueAction, _super);
  44336. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44337. var _this = _super.call(this, triggerOptions, condition) || this;
  44338. _this.propertyPath = propertyPath;
  44339. _this.value = value;
  44340. _this._target = _this._effectiveTarget = target;
  44341. return _this;
  44342. }
  44343. IncrementValueAction.prototype._prepare = function () {
  44344. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44345. this._property = this._getProperty(this.propertyPath);
  44346. if (typeof this._effectiveTarget[this._property] !== "number") {
  44347. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44348. }
  44349. };
  44350. IncrementValueAction.prototype.execute = function () {
  44351. this._effectiveTarget[this._property] += this.value;
  44352. if (this._target.markAsDirty) {
  44353. this._target.markAsDirty(this._property);
  44354. }
  44355. };
  44356. IncrementValueAction.prototype.serialize = function (parent) {
  44357. return _super.prototype._serialize.call(this, {
  44358. name: "IncrementValueAction",
  44359. properties: [
  44360. BABYLON.Action._GetTargetProperty(this._target),
  44361. { name: "propertyPath", value: this.propertyPath },
  44362. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44363. ]
  44364. }, parent);
  44365. };
  44366. return IncrementValueAction;
  44367. }(BABYLON.Action));
  44368. BABYLON.IncrementValueAction = IncrementValueAction;
  44369. var PlayAnimationAction = (function (_super) {
  44370. __extends(PlayAnimationAction, _super);
  44371. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44372. var _this = _super.call(this, triggerOptions, condition) || this;
  44373. _this.from = from;
  44374. _this.to = to;
  44375. _this.loop = loop;
  44376. _this._target = target;
  44377. return _this;
  44378. }
  44379. PlayAnimationAction.prototype._prepare = function () {
  44380. };
  44381. PlayAnimationAction.prototype.execute = function () {
  44382. var scene = this._actionManager.getScene();
  44383. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44384. };
  44385. PlayAnimationAction.prototype.serialize = function (parent) {
  44386. return _super.prototype._serialize.call(this, {
  44387. name: "PlayAnimationAction",
  44388. properties: [
  44389. BABYLON.Action._GetTargetProperty(this._target),
  44390. { name: "from", value: String(this.from) },
  44391. { name: "to", value: String(this.to) },
  44392. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44393. ]
  44394. }, parent);
  44395. };
  44396. return PlayAnimationAction;
  44397. }(BABYLON.Action));
  44398. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44399. var StopAnimationAction = (function (_super) {
  44400. __extends(StopAnimationAction, _super);
  44401. function StopAnimationAction(triggerOptions, target, condition) {
  44402. var _this = _super.call(this, triggerOptions, condition) || this;
  44403. _this._target = target;
  44404. return _this;
  44405. }
  44406. StopAnimationAction.prototype._prepare = function () {
  44407. };
  44408. StopAnimationAction.prototype.execute = function () {
  44409. var scene = this._actionManager.getScene();
  44410. scene.stopAnimation(this._target);
  44411. };
  44412. StopAnimationAction.prototype.serialize = function (parent) {
  44413. return _super.prototype._serialize.call(this, {
  44414. name: "StopAnimationAction",
  44415. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44416. }, parent);
  44417. };
  44418. return StopAnimationAction;
  44419. }(BABYLON.Action));
  44420. BABYLON.StopAnimationAction = StopAnimationAction;
  44421. var DoNothingAction = (function (_super) {
  44422. __extends(DoNothingAction, _super);
  44423. function DoNothingAction(triggerOptions, condition) {
  44424. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44425. return _super.call(this, triggerOptions, condition) || this;
  44426. }
  44427. DoNothingAction.prototype.execute = function () {
  44428. };
  44429. DoNothingAction.prototype.serialize = function (parent) {
  44430. return _super.prototype._serialize.call(this, {
  44431. name: "DoNothingAction",
  44432. properties: []
  44433. }, parent);
  44434. };
  44435. return DoNothingAction;
  44436. }(BABYLON.Action));
  44437. BABYLON.DoNothingAction = DoNothingAction;
  44438. var CombineAction = (function (_super) {
  44439. __extends(CombineAction, _super);
  44440. function CombineAction(triggerOptions, children, condition) {
  44441. var _this = _super.call(this, triggerOptions, condition) || this;
  44442. _this.children = children;
  44443. return _this;
  44444. }
  44445. CombineAction.prototype._prepare = function () {
  44446. for (var index = 0; index < this.children.length; index++) {
  44447. this.children[index]._actionManager = this._actionManager;
  44448. this.children[index]._prepare();
  44449. }
  44450. };
  44451. CombineAction.prototype.execute = function (evt) {
  44452. for (var index = 0; index < this.children.length; index++) {
  44453. this.children[index].execute(evt);
  44454. }
  44455. };
  44456. CombineAction.prototype.serialize = function (parent) {
  44457. var serializationObject = _super.prototype._serialize.call(this, {
  44458. name: "CombineAction",
  44459. properties: [],
  44460. combine: []
  44461. }, parent);
  44462. for (var i = 0; i < this.children.length; i++) {
  44463. serializationObject.combine.push(this.children[i].serialize(null));
  44464. }
  44465. return serializationObject;
  44466. };
  44467. return CombineAction;
  44468. }(BABYLON.Action));
  44469. BABYLON.CombineAction = CombineAction;
  44470. var ExecuteCodeAction = (function (_super) {
  44471. __extends(ExecuteCodeAction, _super);
  44472. function ExecuteCodeAction(triggerOptions, func, condition) {
  44473. var _this = _super.call(this, triggerOptions, condition) || this;
  44474. _this.func = func;
  44475. return _this;
  44476. }
  44477. ExecuteCodeAction.prototype.execute = function (evt) {
  44478. this.func(evt);
  44479. };
  44480. return ExecuteCodeAction;
  44481. }(BABYLON.Action));
  44482. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44483. var SetParentAction = (function (_super) {
  44484. __extends(SetParentAction, _super);
  44485. function SetParentAction(triggerOptions, target, parent, condition) {
  44486. var _this = _super.call(this, triggerOptions, condition) || this;
  44487. _this._target = target;
  44488. _this._parent = parent;
  44489. return _this;
  44490. }
  44491. SetParentAction.prototype._prepare = function () {
  44492. };
  44493. SetParentAction.prototype.execute = function () {
  44494. if (this._target.parent === this._parent) {
  44495. return;
  44496. }
  44497. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44498. invertParentWorldMatrix.invert();
  44499. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44500. this._target.parent = this._parent;
  44501. };
  44502. SetParentAction.prototype.serialize = function (parent) {
  44503. return _super.prototype._serialize.call(this, {
  44504. name: "SetParentAction",
  44505. properties: [
  44506. BABYLON.Action._GetTargetProperty(this._target),
  44507. BABYLON.Action._GetTargetProperty(this._parent),
  44508. ]
  44509. }, parent);
  44510. };
  44511. return SetParentAction;
  44512. }(BABYLON.Action));
  44513. BABYLON.SetParentAction = SetParentAction;
  44514. var PlaySoundAction = (function (_super) {
  44515. __extends(PlaySoundAction, _super);
  44516. function PlaySoundAction(triggerOptions, sound, condition) {
  44517. var _this = _super.call(this, triggerOptions, condition) || this;
  44518. _this._sound = sound;
  44519. return _this;
  44520. }
  44521. PlaySoundAction.prototype._prepare = function () {
  44522. };
  44523. PlaySoundAction.prototype.execute = function () {
  44524. if (this._sound !== undefined)
  44525. this._sound.play();
  44526. };
  44527. PlaySoundAction.prototype.serialize = function (parent) {
  44528. return _super.prototype._serialize.call(this, {
  44529. name: "PlaySoundAction",
  44530. properties: [{ name: "sound", value: this._sound.name }]
  44531. }, parent);
  44532. };
  44533. return PlaySoundAction;
  44534. }(BABYLON.Action));
  44535. BABYLON.PlaySoundAction = PlaySoundAction;
  44536. var StopSoundAction = (function (_super) {
  44537. __extends(StopSoundAction, _super);
  44538. function StopSoundAction(triggerOptions, sound, condition) {
  44539. var _this = _super.call(this, triggerOptions, condition) || this;
  44540. _this._sound = sound;
  44541. return _this;
  44542. }
  44543. StopSoundAction.prototype._prepare = function () {
  44544. };
  44545. StopSoundAction.prototype.execute = function () {
  44546. if (this._sound !== undefined)
  44547. this._sound.stop();
  44548. };
  44549. StopSoundAction.prototype.serialize = function (parent) {
  44550. return _super.prototype._serialize.call(this, {
  44551. name: "StopSoundAction",
  44552. properties: [{ name: "sound", value: this._sound.name }]
  44553. }, parent);
  44554. };
  44555. return StopSoundAction;
  44556. }(BABYLON.Action));
  44557. BABYLON.StopSoundAction = StopSoundAction;
  44558. })(BABYLON || (BABYLON = {}));
  44559. //# sourceMappingURL=babylon.directActions.js.map
  44560. var BABYLON;
  44561. (function (BABYLON) {
  44562. var Debug;
  44563. (function (Debug) {
  44564. /**
  44565. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44566. */
  44567. var SkeletonViewer = (function () {
  44568. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44569. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44570. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44571. this.skeleton = skeleton;
  44572. this.mesh = mesh;
  44573. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44574. this.renderingGroupId = renderingGroupId;
  44575. this.color = BABYLON.Color3.White();
  44576. this._debugLines = [];
  44577. this._isEnabled = false;
  44578. this._scene = scene;
  44579. this.update();
  44580. this._renderFunction = this.update.bind(this);
  44581. }
  44582. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44583. get: function () {
  44584. return this._isEnabled;
  44585. },
  44586. set: function (value) {
  44587. if (this._isEnabled === value) {
  44588. return;
  44589. }
  44590. this._isEnabled = value;
  44591. if (value) {
  44592. this._scene.registerBeforeRender(this._renderFunction);
  44593. }
  44594. else {
  44595. this._scene.unregisterBeforeRender(this._renderFunction);
  44596. }
  44597. },
  44598. enumerable: true,
  44599. configurable: true
  44600. });
  44601. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44602. if (x === void 0) { x = 0; }
  44603. if (y === void 0) { y = 0; }
  44604. if (z === void 0) { z = 0; }
  44605. var tmat = BABYLON.Tmp.Matrix[0];
  44606. var parentBone = bone.getParent();
  44607. tmat.copyFrom(bone.getLocalMatrix());
  44608. if (x !== 0 || y !== 0 || z !== 0) {
  44609. var tmat2 = BABYLON.Tmp.Matrix[1];
  44610. BABYLON.Matrix.IdentityToRef(tmat2);
  44611. tmat2.m[12] = x;
  44612. tmat2.m[13] = y;
  44613. tmat2.m[14] = z;
  44614. tmat2.multiplyToRef(tmat, tmat);
  44615. }
  44616. if (parentBone) {
  44617. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44618. }
  44619. tmat.multiplyToRef(meshMat, tmat);
  44620. position.x = tmat.m[12];
  44621. position.y = tmat.m[13];
  44622. position.z = tmat.m[14];
  44623. };
  44624. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44625. var len = bones.length;
  44626. var meshPos = this.mesh.position;
  44627. for (var i = 0; i < len; i++) {
  44628. var bone = bones[i];
  44629. var points = this._debugLines[i];
  44630. if (!points) {
  44631. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44632. this._debugLines[i] = points;
  44633. }
  44634. this._getBonePosition(points[0], bone, meshMat);
  44635. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44636. points[0].subtractInPlace(meshPos);
  44637. points[1].subtractInPlace(meshPos);
  44638. }
  44639. };
  44640. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44641. var len = bones.length;
  44642. var boneNum = 0;
  44643. var meshPos = this.mesh.position;
  44644. for (var i = len - 1; i >= 0; i--) {
  44645. var childBone = bones[i];
  44646. var parentBone = childBone.getParent();
  44647. if (!parentBone) {
  44648. continue;
  44649. }
  44650. var points = this._debugLines[boneNum];
  44651. if (!points) {
  44652. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44653. this._debugLines[boneNum] = points;
  44654. }
  44655. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  44656. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  44657. points[0].subtractInPlace(meshPos);
  44658. points[1].subtractInPlace(meshPos);
  44659. boneNum++;
  44660. }
  44661. };
  44662. SkeletonViewer.prototype.update = function () {
  44663. if (this.autoUpdateBonesMatrices) {
  44664. this.skeleton.computeAbsoluteTransforms();
  44665. }
  44666. if (this.skeleton.bones[0].length === undefined) {
  44667. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44668. }
  44669. else {
  44670. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44671. }
  44672. if (!this._debugMesh) {
  44673. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44674. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44675. }
  44676. else {
  44677. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44678. }
  44679. this._debugMesh.position.copyFrom(this.mesh.position);
  44680. this._debugMesh.color = this.color;
  44681. };
  44682. SkeletonViewer.prototype.dispose = function () {
  44683. if (this._debugMesh) {
  44684. this.isEnabled = false;
  44685. this._debugMesh.dispose();
  44686. this._debugMesh = null;
  44687. }
  44688. };
  44689. return SkeletonViewer;
  44690. }());
  44691. Debug.SkeletonViewer = SkeletonViewer;
  44692. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44693. })(BABYLON || (BABYLON = {}));
  44694. //# sourceMappingURL=babylon.skeletonViewer.js.map
  44695. var BABYLON;
  44696. (function (BABYLON) {
  44697. var Debug;
  44698. (function (Debug) {
  44699. var AxesViewer = (function () {
  44700. function AxesViewer(scene, scaleLines) {
  44701. if (scaleLines === void 0) { scaleLines = 1; }
  44702. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44703. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44704. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44705. this.scaleLines = 1;
  44706. this.scaleLines = scaleLines;
  44707. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  44708. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  44709. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  44710. this._xmesh.renderingGroupId = 2;
  44711. this._ymesh.renderingGroupId = 2;
  44712. this._zmesh.renderingGroupId = 2;
  44713. this._xmesh.material.checkReadyOnlyOnce = true;
  44714. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  44715. this._ymesh.material.checkReadyOnlyOnce = true;
  44716. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  44717. this._zmesh.material.checkReadyOnlyOnce = true;
  44718. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  44719. this.scene = scene;
  44720. }
  44721. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  44722. var scaleLines = this.scaleLines;
  44723. this._xmesh.position.copyFrom(position);
  44724. this._ymesh.position.copyFrom(position);
  44725. this._zmesh.position.copyFrom(position);
  44726. var point2 = this._xline[1];
  44727. point2.x = xaxis.x * scaleLines;
  44728. point2.y = xaxis.y * scaleLines;
  44729. point2.z = xaxis.z * scaleLines;
  44730. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  44731. point2 = this._yline[1];
  44732. point2.x = yaxis.x * scaleLines;
  44733. point2.y = yaxis.y * scaleLines;
  44734. point2.z = yaxis.z * scaleLines;
  44735. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  44736. point2 = this._zline[1];
  44737. point2.x = zaxis.x * scaleLines;
  44738. point2.y = zaxis.y * scaleLines;
  44739. point2.z = zaxis.z * scaleLines;
  44740. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  44741. };
  44742. AxesViewer.prototype.dispose = function () {
  44743. if (this._xmesh) {
  44744. this._xmesh.dispose();
  44745. this._ymesh.dispose();
  44746. this._zmesh.dispose();
  44747. this._xmesh = null;
  44748. this._ymesh = null;
  44749. this._zmesh = null;
  44750. this._xline = null;
  44751. this._yline = null;
  44752. this._zline = null;
  44753. this.scene = null;
  44754. }
  44755. };
  44756. return AxesViewer;
  44757. }());
  44758. Debug.AxesViewer = AxesViewer;
  44759. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44760. })(BABYLON || (BABYLON = {}));
  44761. //# sourceMappingURL=babylon.axesViewer.js.map
  44762. var BABYLON;
  44763. (function (BABYLON) {
  44764. var Debug;
  44765. (function (Debug) {
  44766. var BoneAxesViewer = (function (_super) {
  44767. __extends(BoneAxesViewer, _super);
  44768. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  44769. if (scaleLines === void 0) { scaleLines = 1; }
  44770. var _this = _super.call(this, scene, scaleLines) || this;
  44771. _this.pos = BABYLON.Vector3.Zero();
  44772. _this.xaxis = BABYLON.Vector3.Zero();
  44773. _this.yaxis = BABYLON.Vector3.Zero();
  44774. _this.zaxis = BABYLON.Vector3.Zero();
  44775. _this.mesh = mesh;
  44776. _this.bone = bone;
  44777. return _this;
  44778. }
  44779. BoneAxesViewer.prototype.update = function () {
  44780. var bone = this.bone;
  44781. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  44782. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  44783. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  44784. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  44785. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  44786. };
  44787. BoneAxesViewer.prototype.dispose = function () {
  44788. if (this.pos) {
  44789. this.pos = null;
  44790. this.xaxis = null;
  44791. this.yaxis = null;
  44792. this.zaxis = null;
  44793. this.mesh = null;
  44794. this.bone = null;
  44795. _super.prototype.dispose.call(this);
  44796. }
  44797. };
  44798. return BoneAxesViewer;
  44799. }(Debug.AxesViewer));
  44800. Debug.BoneAxesViewer = BoneAxesViewer;
  44801. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44802. })(BABYLON || (BABYLON = {}));
  44803. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  44804. var BABYLON;
  44805. (function (BABYLON) {
  44806. var RayHelper = (function () {
  44807. function RayHelper(ray) {
  44808. this.ray = ray;
  44809. }
  44810. RayHelper.CreateAndShow = function (ray, scene, color) {
  44811. var helper = new RayHelper(ray);
  44812. helper.show(scene, color);
  44813. return helper;
  44814. };
  44815. RayHelper.prototype.show = function (scene, color) {
  44816. if (!this._renderFunction) {
  44817. var ray = this.ray;
  44818. this._renderFunction = this._render.bind(this);
  44819. this._scene = scene;
  44820. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  44821. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  44822. this._scene.registerBeforeRender(this._renderFunction);
  44823. }
  44824. if (color) {
  44825. this._renderLine.color.copyFrom(color);
  44826. }
  44827. };
  44828. RayHelper.prototype.hide = function () {
  44829. if (this._renderFunction) {
  44830. this._scene.unregisterBeforeRender(this._renderFunction);
  44831. this._scene = null;
  44832. this._renderFunction = null;
  44833. this._renderLine.dispose();
  44834. this._renderLine = null;
  44835. this._renderPoints = null;
  44836. }
  44837. };
  44838. RayHelper.prototype._render = function () {
  44839. var ray = this.ray;
  44840. var point = this._renderPoints[1];
  44841. var len = Math.min(ray.length, 1000000);
  44842. point.copyFrom(ray.direction);
  44843. point.scaleInPlace(len);
  44844. point.addInPlace(ray.origin);
  44845. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  44846. };
  44847. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  44848. this._attachedToMesh = mesh;
  44849. var ray = this.ray;
  44850. if (!ray.direction) {
  44851. ray.direction = BABYLON.Vector3.Zero();
  44852. }
  44853. if (!ray.origin) {
  44854. ray.origin = BABYLON.Vector3.Zero();
  44855. }
  44856. if (length) {
  44857. ray.length = length;
  44858. }
  44859. if (!meshSpaceOrigin) {
  44860. meshSpaceOrigin = BABYLON.Vector3.Zero();
  44861. }
  44862. if (!meshSpaceDirection) {
  44863. // -1 so that this will work with Mesh.lookAt
  44864. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  44865. }
  44866. if (!this._meshSpaceDirection) {
  44867. this._meshSpaceDirection = meshSpaceDirection.clone();
  44868. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  44869. }
  44870. else {
  44871. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  44872. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  44873. }
  44874. if (!this._updateToMeshFunction) {
  44875. this._updateToMeshFunction = this._updateToMesh.bind(this);
  44876. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  44877. }
  44878. this._updateToMesh();
  44879. };
  44880. RayHelper.prototype.detachFromMesh = function () {
  44881. if (this._attachedToMesh) {
  44882. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  44883. this._attachedToMesh = null;
  44884. this._updateToMeshFunction = null;
  44885. }
  44886. };
  44887. RayHelper.prototype._updateToMesh = function () {
  44888. var ray = this.ray;
  44889. if (this._attachedToMesh._isDisposed) {
  44890. this.detachFromMesh();
  44891. return;
  44892. }
  44893. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  44894. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  44895. };
  44896. RayHelper.prototype.dispose = function () {
  44897. this.hide();
  44898. this.detachFromMesh();
  44899. this.ray = null;
  44900. };
  44901. return RayHelper;
  44902. }());
  44903. BABYLON.RayHelper = RayHelper;
  44904. })(BABYLON || (BABYLON = {}));
  44905. //# sourceMappingURL=babylon.rayHelper.js.map
  44906. var BABYLON;
  44907. (function (BABYLON) {
  44908. var DebugLayer = (function () {
  44909. function DebugLayer(scene) {
  44910. this._scene = scene;
  44911. }
  44912. /** Creates the inspector window. */
  44913. DebugLayer.prototype._createInspector = function (config) {
  44914. if (config === void 0) { config = {}; }
  44915. var popup = config.popup || false;
  44916. var initialTab = config.initialTab || 0;
  44917. var parentElement = config.parentElement || null;
  44918. if (!this._inspector) {
  44919. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  44920. } // else nothing to do,; instance is already existing
  44921. };
  44922. DebugLayer.prototype.isVisible = function () {
  44923. if (!this._inspector) {
  44924. return false;
  44925. }
  44926. return true;
  44927. };
  44928. DebugLayer.prototype.hide = function () {
  44929. if (this._inspector) {
  44930. try {
  44931. this._inspector.dispose();
  44932. }
  44933. catch (e) {
  44934. // If the inspector has been removed directly from the inspector tool
  44935. }
  44936. this._inspector = null;
  44937. }
  44938. };
  44939. DebugLayer.prototype.show = function (config) {
  44940. if (config === void 0) { config = {}; }
  44941. if (typeof INSPECTOR == 'undefined') {
  44942. // Load inspector and add it to the DOM
  44943. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  44944. }
  44945. else {
  44946. // Otherwise creates the inspector
  44947. this._createInspector(config);
  44948. }
  44949. };
  44950. return DebugLayer;
  44951. }());
  44952. // Get protocol used - http or https
  44953. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  44954. BABYLON.DebugLayer = DebugLayer;
  44955. })(BABYLON || (BABYLON = {}));
  44956. //# sourceMappingURL=babylon.debugLayer.js.map
  44957. var BABYLON;
  44958. (function (BABYLON) {
  44959. var Debug;
  44960. (function (Debug) {
  44961. var PhysicsViewer = (function () {
  44962. function PhysicsViewer(scene) {
  44963. this._impostors = [];
  44964. this._meshes = [];
  44965. this._numMeshes = 0;
  44966. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44967. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  44968. }
  44969. PhysicsViewer.prototype._updateDebugMeshes = function () {
  44970. var plugin = this._physicsEnginePlugin;
  44971. for (var i = 0; i < this._numMeshes; i++) {
  44972. if (this._impostors[i].isDisposed) {
  44973. this.hideImpostor(this._impostors[i--]);
  44974. }
  44975. else {
  44976. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  44977. }
  44978. }
  44979. };
  44980. PhysicsViewer.prototype.showImpostor = function (impostor) {
  44981. for (var i = 0; i < this._numMeshes; i++) {
  44982. if (this._impostors[i] == impostor) {
  44983. return;
  44984. }
  44985. }
  44986. var debugMesh = this._physicsEnginePlugin.getDebugMesh(impostor, this._scene);
  44987. if (debugMesh) {
  44988. this._impostors[this._numMeshes] = impostor;
  44989. this._meshes[this._numMeshes] = debugMesh;
  44990. if (this._numMeshes === 0) {
  44991. this._renderFunction = this._updateDebugMeshes.bind(this);
  44992. this._scene.registerBeforeRender(this._renderFunction);
  44993. }
  44994. this._numMeshes++;
  44995. }
  44996. };
  44997. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  44998. var removed = false;
  44999. for (var i = 0; i < this._numMeshes; i++) {
  45000. if (this._impostors[i] == impostor) {
  45001. this._scene.removeMesh(this._meshes[i]);
  45002. this._meshes[i].dispose();
  45003. this._numMeshes--;
  45004. if (this._numMeshes > 0) {
  45005. this._meshes[i] = this._meshes[this._numMeshes];
  45006. this._impostors[i] = this._impostors[this._numMeshes];
  45007. this._meshes[this._numMeshes] = null;
  45008. this._impostors[this._numMeshes] = null;
  45009. }
  45010. else {
  45011. this._meshes[0] = null;
  45012. this._impostors[0] = null;
  45013. }
  45014. removed = true;
  45015. break;
  45016. }
  45017. }
  45018. if (removed && this._numMeshes === 0) {
  45019. this._scene.unregisterBeforeRender(this._renderFunction);
  45020. }
  45021. };
  45022. PhysicsViewer.prototype.dispose = function () {
  45023. for (var i = 0; i < this._numMeshes; i++) {
  45024. this.hideImpostor(this._impostors[i]);
  45025. }
  45026. this._impostors.length = 0;
  45027. this._scene = null;
  45028. this._physicsEnginePlugin = null;
  45029. };
  45030. return PhysicsViewer;
  45031. }());
  45032. Debug.PhysicsViewer = PhysicsViewer;
  45033. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  45034. })(BABYLON || (BABYLON = {}));
  45035. //# sourceMappingURL=babylon.physicsViewer.js.map
  45036. var BABYLON;
  45037. (function (BABYLON) {
  45038. var BoundingBoxRenderer = (function () {
  45039. function BoundingBoxRenderer(scene) {
  45040. this.frontColor = new BABYLON.Color3(1, 1, 1);
  45041. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  45042. this.showBackLines = true;
  45043. this.renderList = new BABYLON.SmartArray(32);
  45044. this._vertexBuffers = {};
  45045. this._scene = scene;
  45046. }
  45047. BoundingBoxRenderer.prototype._prepareRessources = function () {
  45048. if (this._colorShader) {
  45049. return;
  45050. }
  45051. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  45052. attributes: [BABYLON.VertexBuffer.PositionKind],
  45053. uniforms: ["world", "viewProjection", "color"]
  45054. });
  45055. var engine = this._scene.getEngine();
  45056. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  45057. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  45058. 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]);
  45059. };
  45060. BoundingBoxRenderer.prototype.reset = function () {
  45061. this.renderList.reset();
  45062. };
  45063. BoundingBoxRenderer.prototype.render = function () {
  45064. if (this.renderList.length === 0) {
  45065. return;
  45066. }
  45067. this._prepareRessources();
  45068. if (!this._colorShader.isReady()) {
  45069. return;
  45070. }
  45071. var engine = this._scene.getEngine();
  45072. engine.setDepthWrite(false);
  45073. this._colorShader._preBind();
  45074. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  45075. var boundingBox = this.renderList.data[boundingBoxIndex];
  45076. var min = boundingBox.minimum;
  45077. var max = boundingBox.maximum;
  45078. var diff = max.subtract(min);
  45079. var median = min.add(diff.scale(0.5));
  45080. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  45081. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  45082. .multiply(boundingBox.getWorldMatrix());
  45083. // VBOs
  45084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  45085. if (this.showBackLines) {
  45086. // Back
  45087. engine.setDepthFunctionToGreaterOrEqual();
  45088. this._scene.resetCachedMaterial();
  45089. this._colorShader.setColor4("color", this.backColor.toColor4());
  45090. this._colorShader.bind(worldMatrix);
  45091. // Draw order
  45092. engine.draw(false, 0, 24);
  45093. }
  45094. // Front
  45095. engine.setDepthFunctionToLess();
  45096. this._scene.resetCachedMaterial();
  45097. this._colorShader.setColor4("color", this.frontColor.toColor4());
  45098. this._colorShader.bind(worldMatrix);
  45099. // Draw order
  45100. engine.draw(false, 0, 24);
  45101. }
  45102. this._colorShader.unbind();
  45103. engine.setDepthFunctionToLessOrEqual();
  45104. engine.setDepthWrite(true);
  45105. };
  45106. BoundingBoxRenderer.prototype.dispose = function () {
  45107. if (!this._colorShader) {
  45108. return;
  45109. }
  45110. this.renderList.dispose();
  45111. this._colorShader.dispose();
  45112. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45113. if (buffer) {
  45114. buffer.dispose();
  45115. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45116. }
  45117. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  45118. };
  45119. return BoundingBoxRenderer;
  45120. }());
  45121. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  45122. })(BABYLON || (BABYLON = {}));
  45123. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  45124. var BABYLON;
  45125. (function (BABYLON) {
  45126. var TextureTools = (function () {
  45127. function TextureTools() {
  45128. }
  45129. /**
  45130. * Uses the GPU to create a copy texture rescaled at a given size
  45131. * @param texture Texture to copy from
  45132. * @param width Desired width
  45133. * @param height Desired height
  45134. * @return Generated texture
  45135. */
  45136. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  45137. if (useBilinearMode === void 0) { useBilinearMode = true; }
  45138. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  45139. var scene = texture.getScene();
  45140. var engine = scene.getEngine();
  45141. rtt.wrapU = texture.wrapU;
  45142. rtt.wrapV = texture.wrapV;
  45143. rtt.uOffset = texture.uOffset;
  45144. rtt.vOffset = texture.vOffset;
  45145. rtt.uScale = texture.uScale;
  45146. rtt.vScale = texture.vScale;
  45147. rtt.uAng = texture.uAng;
  45148. rtt.vAng = texture.vAng;
  45149. rtt.wAng = texture.wAng;
  45150. rtt.coordinatesIndex = texture.coordinatesIndex;
  45151. rtt.level = texture.level;
  45152. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  45153. rtt._texture.isReady = false;
  45154. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45155. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45156. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  45157. passPostProcess.getEffect().executeWhenCompiled(function () {
  45158. passPostProcess.onApply = function (effect) {
  45159. effect.setTexture("textureSampler", texture);
  45160. };
  45161. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  45162. engine.unBindFramebuffer(rtt.getInternalTexture());
  45163. rtt.disposeFramebufferObjects();
  45164. passPostProcess.dispose();
  45165. rtt._texture.isReady = true;
  45166. });
  45167. return rtt;
  45168. };
  45169. return TextureTools;
  45170. }());
  45171. BABYLON.TextureTools = TextureTools;
  45172. })(BABYLON || (BABYLON = {}));
  45173. //# sourceMappingURL=babylon.textureTools.js.map
  45174. var BABYLON;
  45175. (function (BABYLON) {
  45176. var Internals;
  45177. (function (Internals) {
  45178. var FileFaceOrientation = (function () {
  45179. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  45180. this.name = name;
  45181. this.worldAxisForNormal = worldAxisForNormal;
  45182. this.worldAxisForFileX = worldAxisForFileX;
  45183. this.worldAxisForFileY = worldAxisForFileY;
  45184. }
  45185. return FileFaceOrientation;
  45186. }());
  45187. ;
  45188. /**
  45189. * Helper class dealing with the extraction of spherical polynomial dataArray
  45190. * from a cube map.
  45191. */
  45192. var CubeMapToSphericalPolynomialTools = (function () {
  45193. function CubeMapToSphericalPolynomialTools() {
  45194. }
  45195. /**
  45196. * Converts a cubemap to the according Spherical Polynomial data.
  45197. * This extracts the first 3 orders only as they are the only one used in the lighting.
  45198. *
  45199. * @param cubeInfo The Cube map to extract the information from.
  45200. * @return The Spherical Polynomial data.
  45201. */
  45202. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  45203. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  45204. var totalSolidAngle = 0.0;
  45205. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  45206. var du = 2.0 / cubeInfo.size;
  45207. var dv = du;
  45208. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  45209. var minUV = du * 0.5 - 1.0;
  45210. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  45211. var fileFace = this.FileFaces[faceIndex];
  45212. var dataArray = cubeInfo[fileFace.name];
  45213. var v = minUV;
  45214. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  45215. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  45216. // Because SP is still linear, so summation is fine in that basis.
  45217. for (var y = 0; y < cubeInfo.size; y++) {
  45218. var u = minUV;
  45219. for (var x = 0; x < cubeInfo.size; x++) {
  45220. // World direction (not normalised)
  45221. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  45222. worldDirection.normalize();
  45223. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  45224. if (1) {
  45225. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  45226. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  45227. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  45228. var color = new BABYLON.Color3(r, g, b);
  45229. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45230. }
  45231. else {
  45232. if (faceIndex == 0) {
  45233. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45234. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45235. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45236. }
  45237. else if (faceIndex == 1) {
  45238. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45239. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45240. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45241. }
  45242. else if (faceIndex == 2) {
  45243. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45244. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45245. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45246. }
  45247. else if (faceIndex == 3) {
  45248. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45249. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45250. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  45251. }
  45252. else if (faceIndex == 4) {
  45253. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  45254. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  45255. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45256. }
  45257. else if (faceIndex == 5) {
  45258. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  45259. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  45260. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  45261. }
  45262. var color = new BABYLON.Color3(dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1], dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2]);
  45263. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  45264. }
  45265. totalSolidAngle += deltaSolidAngle;
  45266. u += du;
  45267. }
  45268. v += dv;
  45269. }
  45270. }
  45271. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  45272. var correction = correctSolidAngle / totalSolidAngle;
  45273. sphericalHarmonics.scale(correction);
  45274. // Additionally scale by pi -- audit needed
  45275. sphericalHarmonics.scale(1.0 / Math.PI);
  45276. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  45277. };
  45278. return CubeMapToSphericalPolynomialTools;
  45279. }());
  45280. CubeMapToSphericalPolynomialTools.FileFaces = [
  45281. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  45282. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  45283. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  45284. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  45285. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  45286. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  45287. ];
  45288. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  45289. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45290. })(BABYLON || (BABYLON = {}));
  45291. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  45292. var BABYLON;
  45293. (function (BABYLON) {
  45294. var Internals;
  45295. (function (Internals) {
  45296. /**
  45297. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  45298. */
  45299. var PanoramaToCubeMapTools = (function () {
  45300. function PanoramaToCubeMapTools() {
  45301. }
  45302. /**
  45303. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  45304. *
  45305. * @param float32Array The source data.
  45306. * @param inputWidth The width of the input panorama.
  45307. * @param inputhHeight The height of the input panorama.
  45308. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  45309. * @return The cubemap data
  45310. */
  45311. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  45312. if (!float32Array) {
  45313. throw "ConvertPanoramaToCubemap: input cannot be null";
  45314. }
  45315. if (float32Array.length != inputWidth * inputHeight * 3) {
  45316. throw "ConvertPanoramaToCubemap: input size is wrong";
  45317. }
  45318. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  45319. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  45320. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  45321. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  45322. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  45323. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  45324. return {
  45325. front: textureFront,
  45326. back: textureBack,
  45327. left: textureLeft,
  45328. right: textureRight,
  45329. up: textureUp,
  45330. down: textureDown,
  45331. size: size
  45332. };
  45333. };
  45334. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  45335. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  45336. var textureArray = new Float32Array(buffer);
  45337. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  45338. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  45339. var dy = 1 / texSize;
  45340. var fy = 0;
  45341. for (var y = 0; y < texSize; y++) {
  45342. var xv1 = faceData[0];
  45343. var xv2 = faceData[2];
  45344. for (var x = 0; x < texSize; x++) {
  45345. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  45346. v.normalize();
  45347. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  45348. // 3 channels per pixels
  45349. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  45350. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  45351. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  45352. xv1 = xv1.add(rotDX1);
  45353. xv2 = xv2.add(rotDX2);
  45354. }
  45355. fy += dy;
  45356. }
  45357. return textureArray;
  45358. };
  45359. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  45360. var theta = Math.atan2(vDir.z, vDir.x);
  45361. var phi = Math.acos(vDir.y);
  45362. while (theta < -Math.PI)
  45363. theta += 2 * Math.PI;
  45364. while (theta > Math.PI)
  45365. theta -= 2 * Math.PI;
  45366. var dx = theta / Math.PI;
  45367. var dy = phi / Math.PI;
  45368. // recenter.
  45369. dx = dx * 0.5 + 0.5;
  45370. var px = Math.round(dx * inputWidth);
  45371. if (px < 0)
  45372. px = 0;
  45373. else if (px >= inputWidth)
  45374. px = inputWidth - 1;
  45375. var py = Math.round(dy * inputHeight);
  45376. if (py < 0)
  45377. py = 0;
  45378. else if (py >= inputHeight)
  45379. py = inputHeight - 1;
  45380. var inputY = (inputHeight - py - 1);
  45381. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  45382. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  45383. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  45384. return {
  45385. r: r,
  45386. g: g,
  45387. b: b
  45388. };
  45389. };
  45390. return PanoramaToCubeMapTools;
  45391. }());
  45392. PanoramaToCubeMapTools.FACE_FRONT = [
  45393. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45394. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45395. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45396. new BABYLON.Vector3(1.0, 1.0, -1.0)
  45397. ];
  45398. PanoramaToCubeMapTools.FACE_BACK = [
  45399. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45400. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45401. new BABYLON.Vector3(1.0, 1.0, 1.0),
  45402. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  45403. ];
  45404. PanoramaToCubeMapTools.FACE_RIGHT = [
  45405. new BABYLON.Vector3(1.0, -1.0, -1.0),
  45406. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45407. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45408. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45409. ];
  45410. PanoramaToCubeMapTools.FACE_LEFT = [
  45411. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45412. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45413. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45414. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  45415. ];
  45416. PanoramaToCubeMapTools.FACE_DOWN = [
  45417. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  45418. new BABYLON.Vector3(1.0, 1.0, -1.0),
  45419. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  45420. new BABYLON.Vector3(1.0, 1.0, 1.0)
  45421. ];
  45422. PanoramaToCubeMapTools.FACE_UP = [
  45423. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  45424. new BABYLON.Vector3(1.0, -1.0, 1.0),
  45425. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  45426. new BABYLON.Vector3(1.0, -1.0, -1.0)
  45427. ];
  45428. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  45429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45430. })(BABYLON || (BABYLON = {}));
  45431. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  45432. var BABYLON;
  45433. (function (BABYLON) {
  45434. var Internals;
  45435. (function (Internals) {
  45436. ;
  45437. /**
  45438. * This groups tools to convert HDR texture to native colors array.
  45439. */
  45440. var HDRTools = (function () {
  45441. function HDRTools() {
  45442. }
  45443. HDRTools.Ldexp = function (mantissa, exponent) {
  45444. if (exponent > 1023) {
  45445. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  45446. }
  45447. if (exponent < -1074) {
  45448. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  45449. }
  45450. return mantissa * Math.pow(2, exponent);
  45451. };
  45452. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  45453. if (exponent > 0) {
  45454. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  45455. float32array[index + 0] = red * exponent;
  45456. float32array[index + 1] = green * exponent;
  45457. float32array[index + 2] = blue * exponent;
  45458. }
  45459. else {
  45460. float32array[index + 0] = 0;
  45461. float32array[index + 1] = 0;
  45462. float32array[index + 2] = 0;
  45463. }
  45464. };
  45465. HDRTools.readStringLine = function (uint8array, startIndex) {
  45466. var line = "";
  45467. var character = "";
  45468. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  45469. character = String.fromCharCode(uint8array[i]);
  45470. if (character == "\n") {
  45471. break;
  45472. }
  45473. line += character;
  45474. }
  45475. return line;
  45476. };
  45477. /**
  45478. * Reads header information from an RGBE texture stored in a native array.
  45479. * More information on this format are available here:
  45480. * https://en.wikipedia.org/wiki/RGBE_image_format
  45481. *
  45482. * @param uint8array The binary file stored in native array.
  45483. * @return The header information.
  45484. */
  45485. HDRTools.RGBE_ReadHeader = function (uint8array) {
  45486. var height = 0;
  45487. var width = 0;
  45488. var line = this.readStringLine(uint8array, 0);
  45489. if (line[0] != '#' || line[1] != '?') {
  45490. throw "Bad HDR Format.";
  45491. }
  45492. var endOfHeader = false;
  45493. var findFormat = false;
  45494. var lineIndex = 0;
  45495. do {
  45496. lineIndex += (line.length + 1);
  45497. line = this.readStringLine(uint8array, lineIndex);
  45498. if (line == "FORMAT=32-bit_rle_rgbe") {
  45499. findFormat = true;
  45500. }
  45501. else if (line.length == 0) {
  45502. endOfHeader = true;
  45503. }
  45504. } while (!endOfHeader);
  45505. if (!findFormat) {
  45506. throw "HDR Bad header format, unsupported FORMAT";
  45507. }
  45508. lineIndex += (line.length + 1);
  45509. line = this.readStringLine(uint8array, lineIndex);
  45510. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  45511. var match = sizeRegexp.exec(line);
  45512. // TODO. Support +Y and -X if needed.
  45513. if (match.length < 3) {
  45514. throw "HDR Bad header format, no size";
  45515. }
  45516. width = parseInt(match[2]);
  45517. height = parseInt(match[1]);
  45518. if (width < 8 || width > 0x7fff) {
  45519. throw "HDR Bad header format, unsupported size";
  45520. }
  45521. lineIndex += (line.length + 1);
  45522. return {
  45523. height: height,
  45524. width: width,
  45525. dataPosition: lineIndex
  45526. };
  45527. };
  45528. /**
  45529. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  45530. * This RGBE texture needs to store the information as a panorama.
  45531. *
  45532. * More information on this format are available here:
  45533. * https://en.wikipedia.org/wiki/RGBE_image_format
  45534. *
  45535. * @param buffer The binary file stored in an array buffer.
  45536. * @param size The expected size of the extracted cubemap.
  45537. * @return The Cube Map information.
  45538. */
  45539. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  45540. var uint8array = new Uint8Array(buffer);
  45541. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  45542. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45543. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  45544. return cubeMapData;
  45545. };
  45546. /**
  45547. * Returns the pixels data extracted from an RGBE texture.
  45548. * This pixels will be stored left to right up to down in the R G B order in one array.
  45549. *
  45550. * More information on this format are available here:
  45551. * https://en.wikipedia.org/wiki/RGBE_image_format
  45552. *
  45553. * @param uint8array The binary file stored in an array buffer.
  45554. * @param hdrInfo The header information of the file.
  45555. * @return The pixels data in RGB right to left up to down order.
  45556. */
  45557. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  45558. // Keep for multi format supports.
  45559. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  45560. };
  45561. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  45562. var num_scanlines = hdrInfo.height;
  45563. var scanline_width = hdrInfo.width;
  45564. var a, b, c, d, count;
  45565. var dataIndex = hdrInfo.dataPosition;
  45566. var index = 0, endIndex = 0, i = 0;
  45567. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  45568. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  45569. // 3 channels of 4 bytes per pixel in float.
  45570. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  45571. var resultArray = new Float32Array(resultBuffer);
  45572. // read in each successive scanline
  45573. while (num_scanlines > 0) {
  45574. a = uint8array[dataIndex++];
  45575. b = uint8array[dataIndex++];
  45576. c = uint8array[dataIndex++];
  45577. d = uint8array[dataIndex++];
  45578. if (a != 2 || b != 2 || (c & 0x80)) {
  45579. // this file is not run length encoded
  45580. throw "HDR Bad header format, not RLE";
  45581. }
  45582. if (((c << 8) | d) != scanline_width) {
  45583. throw "HDR Bad header format, wrong scan line width";
  45584. }
  45585. index = 0;
  45586. // read each of the four channels for the scanline into the buffer
  45587. for (i = 0; i < 4; i++) {
  45588. endIndex = (i + 1) * scanline_width;
  45589. while (index < endIndex) {
  45590. a = uint8array[dataIndex++];
  45591. b = uint8array[dataIndex++];
  45592. if (a > 128) {
  45593. // a run of the same value
  45594. count = a - 128;
  45595. if ((count == 0) || (count > endIndex - index)) {
  45596. throw "HDR Bad Format, bad scanline data (run)";
  45597. }
  45598. while (count-- > 0) {
  45599. scanLineArray[index++] = b;
  45600. }
  45601. }
  45602. else {
  45603. // a non-run
  45604. count = a;
  45605. if ((count == 0) || (count > endIndex - index)) {
  45606. throw "HDR Bad Format, bad scanline data (non-run)";
  45607. }
  45608. scanLineArray[index++] = b;
  45609. if (--count > 0) {
  45610. for (var j = 0; j < count; j++) {
  45611. scanLineArray[index++] = uint8array[dataIndex++];
  45612. }
  45613. }
  45614. }
  45615. }
  45616. }
  45617. // now convert data from buffer into floats
  45618. for (i = 0; i < scanline_width; i++) {
  45619. a = scanLineArray[i];
  45620. b = scanLineArray[i + scanline_width];
  45621. c = scanLineArray[i + 2 * scanline_width];
  45622. d = scanLineArray[i + 3 * scanline_width];
  45623. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  45624. }
  45625. num_scanlines--;
  45626. }
  45627. return resultArray;
  45628. };
  45629. return HDRTools;
  45630. }());
  45631. Internals.HDRTools = HDRTools;
  45632. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45633. })(BABYLON || (BABYLON = {}));
  45634. //# sourceMappingURL=babylon.hdr.js.map
  45635. //_______________________________________________________________
  45636. // Extracted from CubeMapGen:
  45637. // https://code.google.com/archive/p/cubemapgen/
  45638. //
  45639. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45640. //_______________________________________________________________
  45641. var BABYLON;
  45642. (function (BABYLON) {
  45643. var Internals;
  45644. (function (Internals) {
  45645. /**
  45646. * The bounding box information used during the conversion process.
  45647. */
  45648. var CMGBoundinBox = (function () {
  45649. function CMGBoundinBox() {
  45650. this.min = new BABYLON.Vector3(0, 0, 0);
  45651. this.max = new BABYLON.Vector3(0, 0, 0);
  45652. this.clear();
  45653. }
  45654. CMGBoundinBox.prototype.clear = function () {
  45655. this.min.x = CMGBoundinBox.MAX;
  45656. this.min.y = CMGBoundinBox.MAX;
  45657. this.min.z = CMGBoundinBox.MAX;
  45658. this.max.x = CMGBoundinBox.MIN;
  45659. this.max.y = CMGBoundinBox.MIN;
  45660. this.max.z = CMGBoundinBox.MIN;
  45661. };
  45662. CMGBoundinBox.prototype.augment = function (x, y, z) {
  45663. this.min.x = Math.min(this.min.x, x);
  45664. this.min.y = Math.min(this.min.y, y);
  45665. this.min.z = Math.min(this.min.z, z);
  45666. this.max.x = Math.max(this.max.x, x);
  45667. this.max.y = Math.max(this.max.y, y);
  45668. this.max.z = Math.max(this.max.z, z);
  45669. };
  45670. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  45671. this.min.x = Math.max(this.min.x, x);
  45672. this.min.y = Math.max(this.min.y, y);
  45673. this.min.z = Math.max(this.min.z, z);
  45674. };
  45675. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  45676. this.max.x = Math.min(this.max.x, x);
  45677. this.max.y = Math.min(this.max.y, y);
  45678. this.max.z = Math.min(this.max.z, z);
  45679. };
  45680. CMGBoundinBox.prototype.empty = function () {
  45681. if ((this.min.x > this.max.y) ||
  45682. (this.min.y > this.max.y) ||
  45683. (this.min.z > this.max.y)) {
  45684. return true;
  45685. }
  45686. else {
  45687. return false;
  45688. }
  45689. };
  45690. return CMGBoundinBox;
  45691. }());
  45692. CMGBoundinBox.MAX = Number.MAX_VALUE;
  45693. CMGBoundinBox.MIN = Number.MIN_VALUE;
  45694. /**
  45695. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  45696. * required by the glossinees of a material.
  45697. *
  45698. * This only supports the cosine drop power as well as Warp fixup generation method.
  45699. *
  45700. * This is using the process from CubeMapGen described here:
  45701. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  45702. */
  45703. var PMREMGenerator = (function () {
  45704. /**
  45705. * Constructor of the generator.
  45706. *
  45707. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  45708. * @param inputSize The size of the cubemap faces
  45709. * @param outputSize The size of the output cubemap faces
  45710. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  45711. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  45712. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  45713. * @param specularPower The max specular level of the desired cubemap
  45714. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  45715. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  45716. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  45717. */
  45718. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  45719. this.input = input;
  45720. this.inputSize = inputSize;
  45721. this.outputSize = outputSize;
  45722. this.maxNumMipLevels = maxNumMipLevels;
  45723. this.numChannels = numChannels;
  45724. this.isFloat = isFloat;
  45725. this.specularPower = specularPower;
  45726. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  45727. this.excludeBase = excludeBase;
  45728. this.fixup = fixup;
  45729. this._outputSurface = [];
  45730. this._numMipLevels = 0;
  45731. }
  45732. /**
  45733. * Launches the filter process and return the result.
  45734. *
  45735. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  45736. */
  45737. PMREMGenerator.prototype.filterCubeMap = function () {
  45738. // Init cubemap processor
  45739. this.init();
  45740. // Filters the cubemap
  45741. this.filterCubeMapMipChain();
  45742. // Returns the filtered mips.
  45743. return this._outputSurface;
  45744. };
  45745. PMREMGenerator.prototype.init = function () {
  45746. var i;
  45747. var j;
  45748. var mipLevelSize;
  45749. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  45750. if (this.maxNumMipLevels == 0) {
  45751. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  45752. }
  45753. //first miplevel size
  45754. mipLevelSize = this.outputSize;
  45755. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  45756. for (j = 0; j < this.maxNumMipLevels; j++) {
  45757. this._outputSurface.length++;
  45758. this._outputSurface[j] = [];
  45759. //Iterate over faces for output images
  45760. for (i = 0; i < 6; i++) {
  45761. this._outputSurface[j].length++;
  45762. // Initializes a new array for the output.
  45763. if (this.isFloat) {
  45764. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45765. }
  45766. else {
  45767. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  45768. }
  45769. }
  45770. //next mip level is half size
  45771. mipLevelSize >>= 1;
  45772. this._numMipLevels++;
  45773. //terminate if mip chain becomes too small
  45774. if (mipLevelSize == 0) {
  45775. this.maxNumMipLevels = j;
  45776. return;
  45777. }
  45778. }
  45779. };
  45780. //--------------------------------------------------------------------------------------
  45781. //Cube map filtering and mip chain generation.
  45782. // the cube map filtereing is specified using a number of parameters:
  45783. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  45784. // indicates the region of the hemisphere to filter over for each tap.
  45785. //
  45786. // Note that the top mip level is also a filtered version of the original input images
  45787. // as well in order to create mip chains for diffuse environment illumination.
  45788. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  45789. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  45790. //
  45791. // Then the mip angle used to genreate the next level of the mip chain from the first level
  45792. // is a_InitialMipAngle
  45793. //
  45794. // The angle for the subsequent levels of the mip chain are specified by their parents
  45795. // filtering angle and a per-level scale and bias
  45796. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  45797. //
  45798. //--------------------------------------------------------------------------------------
  45799. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  45800. // First, take count of the lighting model to modify SpecularPower
  45801. // var refSpecularPower = (a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN || a_MCO.LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? a_MCO.SpecularPower / GetSpecularPowerFactorToMatchPhong(a_MCO.SpecularPower) : a_MCO.SpecularPower;
  45802. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  45803. //Cone angle start (for generating subsequent mip levels)
  45804. var currentSpecularPower = this.specularPower;
  45805. //Build filter lookup tables based on the source miplevel size
  45806. this.precomputeFilterLookupTables(this.inputSize);
  45807. // Note that we need to filter the first level before generating mipmap
  45808. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  45809. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  45810. // TODO : Write a function to copy and scale the base mipmap in output
  45811. // I am just lazy here and just put a high specular power value, and do some if.
  45812. if (this.excludeBase && (levelIndex == 0)) {
  45813. // If we don't want to process the base mipmap, just put a very high specular power (this allow to handle scale of the texture).
  45814. currentSpecularPower = 100000.0;
  45815. }
  45816. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  45817. var srcCubeImage = this.input;
  45818. var dstCubeImage = this._outputSurface[levelIndex];
  45819. var dstSize = this.outputSize >> levelIndex;
  45820. // Compute required angle.
  45821. var angle = this.getBaseFilterAngle(currentSpecularPower);
  45822. // filter cube surfaces
  45823. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  45824. // fix seams
  45825. if (this.fixup) {
  45826. this.fixupCubeEdges(dstCubeImage, dstSize);
  45827. }
  45828. // Decrease the specular power to generate the mipmap chain
  45829. // TODO : Use another method for Exclude (see first comment at start of the function
  45830. if (this.excludeBase && (levelIndex == 0)) {
  45831. currentSpecularPower = this.specularPower;
  45832. }
  45833. currentSpecularPower *= this.cosinePowerDropPerMip;
  45834. }
  45835. };
  45836. //--------------------------------------------------------------------------------------
  45837. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  45838. // It allow to optimize the texel to access base on the specular power.
  45839. //--------------------------------------------------------------------------------------
  45840. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  45841. // We want to find the alpha such that:
  45842. // cos(alpha)^cosinePower = epsilon
  45843. // That's: acos(epsilon^(1/cosinePower))
  45844. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  45845. var angle = 180.0;
  45846. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  45847. angle *= 180.0 / Math.PI; // Convert to degree
  45848. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  45849. return angle;
  45850. };
  45851. //--------------------------------------------------------------------------------------
  45852. //Builds the following lookup tables prior to filtering:
  45853. // -normalizer cube map
  45854. // -tap weight lookup table
  45855. //
  45856. //--------------------------------------------------------------------------------------
  45857. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  45858. var srcTexelAngle;
  45859. var iCubeFace;
  45860. //clear pre-existing normalizer cube map
  45861. this._normCubeMap = [];
  45862. //Normalized vectors per cubeface and per-texel solid angle
  45863. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  45864. };
  45865. //--------------------------------------------------------------------------------------
  45866. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  45867. //
  45868. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  45869. //
  45870. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  45871. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  45872. // below
  45873. //--------------------------------------------------------------------------------------
  45874. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  45875. var iCubeFace;
  45876. var u;
  45877. var v;
  45878. //iterate over cube faces
  45879. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  45880. //First three channels for norm cube, and last channel for solid angle
  45881. this._normCubeMap.push(new Float32Array(size * size * 4));
  45882. //fast texture walk, build normalizer cube map
  45883. var facesData = this.input[iCubeFace];
  45884. for (v = 0; v < size; v++) {
  45885. for (u = 0; u < size; u++) {
  45886. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  45887. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  45888. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  45889. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  45890. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  45891. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  45892. }
  45893. }
  45894. }
  45895. };
  45896. //--------------------------------------------------------------------------------------
  45897. // Convert cubemap face texel coordinates and face idx to 3D vector
  45898. // note the U and V coords are integer coords and range from 0 to size-1
  45899. // this routine can be used to generate a normalizer cube map
  45900. //--------------------------------------------------------------------------------------
  45901. // SL BEGIN
  45902. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  45903. var nvcU;
  45904. var nvcV;
  45905. var tempVec;
  45906. // Change from original AMD code
  45907. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  45908. // + 0.5f is for texel center addressing
  45909. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  45910. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  45911. // warp fixup
  45912. if (fixup && size > 1) {
  45913. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  45914. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  45915. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  45916. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  45917. }
  45918. // Get current vector
  45919. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  45920. // U contribution
  45921. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  45922. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  45923. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  45924. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  45925. // V contribution and Sum
  45926. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  45927. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  45928. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  45929. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  45930. //add face axis
  45931. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  45932. PMREMGenerator._vectorTemp.x += faceAxis[0];
  45933. PMREMGenerator._vectorTemp.y += faceAxis[1];
  45934. PMREMGenerator._vectorTemp.z += faceAxis[2];
  45935. //normalize vector
  45936. PMREMGenerator._vectorTemp.normalize();
  45937. return PMREMGenerator._vectorTemp;
  45938. };
  45939. //--------------------------------------------------------------------------------------
  45940. // Convert 3D vector to cubemap face texel coordinates and face idx
  45941. // note the U and V coords are integer coords and range from 0 to size-1
  45942. // this routine can be used to generate a normalizer cube map
  45943. //
  45944. // returns face IDX and texel coords
  45945. //--------------------------------------------------------------------------------------
  45946. // SL BEGIN
  45947. /*
  45948. Mapping Texture Coordinates to Cube Map Faces
  45949. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  45950. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  45951. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  45952. map arrangement in Pixar's RenderMan package.
  45953. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  45954. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  45955. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  45956. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  45957. the major axis direction). The target column in the table below explains how the major axis direction
  45958. maps to the 2D image of a particular cube map target.
  45959. major axis
  45960. direction target sc tc ma
  45961. ---------- --------------------------------- --- --- ---
  45962. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  45963. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  45964. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  45965. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  45966. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  45967. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  45968. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  45969. an updated (s,t) is calculated as follows
  45970. s = ( sc/|ma| + 1 ) / 2
  45971. t = ( tc/|ma| + 1 ) / 2
  45972. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  45973. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  45974. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  45975. */
  45976. // Note this method return U and V in range from 0 to size-1
  45977. // SL END
  45978. // Store the information in vector3 for convenience (faceindex, u, v)
  45979. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  45980. var maxCoord;
  45981. var faceIdx;
  45982. //absolute value 3
  45983. var absX = Math.abs(x);
  45984. var absY = Math.abs(y);
  45985. var absZ = Math.abs(z);
  45986. if (absX >= absY && absX >= absZ) {
  45987. maxCoord = absX;
  45988. if (x >= 0) {
  45989. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  45990. }
  45991. else {
  45992. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  45993. }
  45994. }
  45995. else if (absY >= absX && absY >= absZ) {
  45996. maxCoord = absY;
  45997. if (y >= 0) {
  45998. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  45999. }
  46000. else {
  46001. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  46002. }
  46003. }
  46004. else {
  46005. maxCoord = absZ;
  46006. if (z >= 0) {
  46007. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  46008. }
  46009. else {
  46010. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  46011. }
  46012. }
  46013. //divide through by max coord so face vector lies on cube face
  46014. var scale = 1 / maxCoord;
  46015. x *= scale;
  46016. y *= scale;
  46017. z *= scale;
  46018. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  46019. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  46020. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  46021. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  46022. // Modify original AMD code to return value from 0 to Size - 1
  46023. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  46024. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  46025. PMREMGenerator._vectorTemp.x = faceIdx;
  46026. PMREMGenerator._vectorTemp.y = u;
  46027. PMREMGenerator._vectorTemp.z = v;
  46028. return PMREMGenerator._vectorTemp;
  46029. };
  46030. //--------------------------------------------------------------------------------------
  46031. //Original code from Ignacio CastaÒo
  46032. // This formula is from Manne ÷hrstrˆm's thesis.
  46033. // Take two coordiantes in the range [-1, 1] that define a portion of a
  46034. // cube face and return the area of the projection of that portion on the
  46035. // surface of the sphere.
  46036. //--------------------------------------------------------------------------------------
  46037. PMREMGenerator.prototype.areaElement = function (x, y) {
  46038. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  46039. };
  46040. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  46041. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  46042. // (+ 0.5f is for texel center addressing)
  46043. u = (2.0 * (u + 0.5) / size) - 1.0;
  46044. v = (2.0 * (v + 0.5) / size) - 1.0;
  46045. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  46046. var invResolution = 1.0 / size;
  46047. // U and V are the -1..1 texture coordinate on the current face.
  46048. // Get projected area for this texel
  46049. var x0 = u - invResolution;
  46050. var y0 = v - invResolution;
  46051. var x1 = u + invResolution;
  46052. var y1 = v + invResolution;
  46053. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  46054. return solidAngle;
  46055. };
  46056. //--------------------------------------------------------------------------------------
  46057. //The key to the speed of these filtering routines is to quickly define a per-face
  46058. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  46059. // Later these pixels are selectively processed based on their dot products to see if
  46060. // they reside within the filtering cone.
  46061. //
  46062. //This is done by computing the smallest per-texel angle to get a conservative estimate
  46063. // of the number of texels needed to be covered in width and height order to filter the
  46064. // region. the bounding box for the center taps face is defined first, and if the
  46065. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  46066. // defined next
  46067. //--------------------------------------------------------------------------------------
  46068. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  46069. // note that pixels within these regions may be rejected
  46070. // based on the anlge
  46071. var iCubeFace;
  46072. var u;
  46073. var v;
  46074. // bounding box per face to specify region to process
  46075. var filterExtents = [];
  46076. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46077. filterExtents.push(new CMGBoundinBox());
  46078. }
  46079. // min angle a src texel can cover (in degrees)
  46080. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  46081. // angle about center tap to define filter cone
  46082. // filter angle is 1/2 the cone angle
  46083. var filterAngle = filterConeAngle / 2.0;
  46084. //ensure filter angle is larger than a texel
  46085. if (filterAngle < srcTexelAngle) {
  46086. filterAngle = srcTexelAngle;
  46087. }
  46088. //ensure filter cone is always smaller than the hemisphere
  46089. if (filterAngle > 90.0) {
  46090. filterAngle = 90.0;
  46091. }
  46092. // the maximum number of texels in 1D the filter cone angle will cover
  46093. // used to determine bounding box size for filter extents
  46094. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  46095. // ensure conservative region always covers at least one texel
  46096. if (filterSize < 1) {
  46097. filterSize = 1;
  46098. }
  46099. // dotProdThresh threshold based on cone angle to determine whether or not taps
  46100. // reside within the cone angle
  46101. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  46102. // process required faces
  46103. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  46104. //iterate over dst cube map face texel
  46105. for (v = 0; v < dstSize; v++) {
  46106. for (u = 0; u < dstSize; u++) {
  46107. //get center tap direction
  46108. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  46109. //clear old per-face filter extents
  46110. this.clearFilterExtents(filterExtents);
  46111. //define per-face filter extents
  46112. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  46113. //perform filtering of src faces using filter extents
  46114. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  46115. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  46116. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  46117. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  46118. }
  46119. }
  46120. }
  46121. };
  46122. //--------------------------------------------------------------------------------------
  46123. //Clear filter extents for the 6 cube map faces
  46124. //--------------------------------------------------------------------------------------
  46125. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  46126. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  46127. filterExtents[iCubeFaces].clear();
  46128. }
  46129. };
  46130. //--------------------------------------------------------------------------------------
  46131. //Define per-face bounding box filter extents
  46132. //
  46133. // These define conservative texel regions in each of the faces the filter can possibly
  46134. // process. When the pixels in the regions are actually processed, the dot product
  46135. // between the tap vector and the center tap vector is used to determine the weight of
  46136. // the tap and whether or not the tap is within the cone.
  46137. //
  46138. //--------------------------------------------------------------------------------------
  46139. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  46140. //neighboring face and bleed over amount, and width of BBOX for
  46141. // left, right, top, and bottom edges of this face
  46142. var bleedOverAmount = [0, 0, 0, 0];
  46143. var bleedOverBBoxMin = [0, 0, 0, 0];
  46144. var bleedOverBBoxMax = [0, 0, 0, 0];
  46145. var neighborFace;
  46146. var neighborEdge;
  46147. var oppositeFaceIdx;
  46148. //get face idx, and u, v info from center tap dir
  46149. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  46150. var faceIdx = result.x;
  46151. var u = result.y;
  46152. var v = result.z;
  46153. //define bbox size within face
  46154. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  46155. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  46156. filterExtents[faceIdx].clampMin(0, 0, 0);
  46157. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  46158. //u and v extent in face corresponding to center tap
  46159. var minU = filterExtents[faceIdx].min.x;
  46160. var minV = filterExtents[faceIdx].min.y;
  46161. var maxU = filterExtents[faceIdx].max.x;
  46162. var maxV = filterExtents[faceIdx].max.y;
  46163. //bleed over amounts for face across u=0 edge (left)
  46164. bleedOverAmount[0] = (bboxSize - u);
  46165. bleedOverBBoxMin[0] = minV;
  46166. bleedOverBBoxMax[0] = maxV;
  46167. //bleed over amounts for face across u=1 edge (right)
  46168. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  46169. bleedOverBBoxMin[1] = minV;
  46170. bleedOverBBoxMax[1] = maxV;
  46171. //bleed over to face across v=0 edge (up)
  46172. bleedOverAmount[2] = (bboxSize - v);
  46173. bleedOverBBoxMin[2] = minU;
  46174. bleedOverBBoxMax[2] = maxU;
  46175. //bleed over to face across v=1 edge (down)
  46176. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  46177. bleedOverBBoxMin[3] = minU;
  46178. bleedOverBBoxMax[3] = maxU;
  46179. //compute bleed over regions in neighboring faces
  46180. for (var i = 0; i < 4; i++) {
  46181. if (bleedOverAmount[i] > 0) {
  46182. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  46183. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  46184. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  46185. // be flipped: the cases are
  46186. // if a left edge mates with a left or bottom edge on the neighbor
  46187. // if a top edge mates with a top or right edge on the neighbor
  46188. // if a right edge mates with a right or top edge on the neighbor
  46189. // if a bottom edge mates with a bottom or left edge on the neighbor
  46190. //Seeing as the edges are enumerated as follows
  46191. // left =0
  46192. // right =1
  46193. // top =2
  46194. // bottom =3
  46195. //
  46196. // so if the edge enums are the same, or the sum of the enums == 3,
  46197. // the bbox needs to be flipped
  46198. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  46199. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  46200. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  46201. }
  46202. //The way the bounding box is extended onto the neighboring face
  46203. // depends on which edge of neighboring face abuts with this one
  46204. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  46205. case PMREMGenerator.CP_EDGE_LEFT:
  46206. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  46207. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46208. break;
  46209. case PMREMGenerator.CP_EDGE_RIGHT:
  46210. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  46211. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  46212. break;
  46213. case PMREMGenerator.CP_EDGE_TOP:
  46214. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  46215. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  46216. break;
  46217. case PMREMGenerator.CP_EDGE_BOTTOM:
  46218. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  46219. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  46220. break;
  46221. }
  46222. //clamp filter extents in non-center tap faces to remain within surface
  46223. filterExtents[neighborFace].clampMin(0, 0, 0);
  46224. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  46225. }
  46226. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  46227. // from the center tap face, then process the opposite face entirely for now.
  46228. //Note that the cases in which this happens, what usually happens is that
  46229. // more than one edge bleeds onto the opposite face, and the bounding box
  46230. // encompasses the entire cube map face.
  46231. if (bleedOverAmount[i] > srcSize) {
  46232. //determine opposite face
  46233. switch (faceIdx) {
  46234. case PMREMGenerator.CP_FACE_X_POS:
  46235. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  46236. break;
  46237. case PMREMGenerator.CP_FACE_X_NEG:
  46238. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  46239. break;
  46240. case PMREMGenerator.CP_FACE_Y_POS:
  46241. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  46242. break;
  46243. case PMREMGenerator.CP_FACE_Y_NEG:
  46244. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  46245. break;
  46246. case PMREMGenerator.CP_FACE_Z_POS:
  46247. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  46248. break;
  46249. case PMREMGenerator.CP_FACE_Z_NEG:
  46250. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  46251. break;
  46252. default:
  46253. break;
  46254. }
  46255. //just encompass entire face for now
  46256. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  46257. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  46258. }
  46259. }
  46260. };
  46261. //--------------------------------------------------------------------------------------
  46262. //ProcessFilterExtents
  46263. // Process bounding box in each cube face
  46264. //
  46265. //--------------------------------------------------------------------------------------
  46266. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  46267. //accumulators are 64-bit floats in order to have the precision needed
  46268. // over a summation of a large number of pixels
  46269. var dstAccum = [0, 0, 0, 0];
  46270. var weightAccum = 0;
  46271. var k = 0;
  46272. var nSrcChannels = this.numChannels;
  46273. // norm cube map and srcCubeMap have same face width
  46274. var faceWidth = srcSize;
  46275. //amount to add to pointer to move to next scanline in images
  46276. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  46277. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  46278. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  46279. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  46280. // iterate over cubefaces
  46281. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  46282. //if bbox is non empty
  46283. if (!filterExtents[iFaceIdx].empty()) {
  46284. var uStart = filterExtents[iFaceIdx].min.x;
  46285. var vStart = filterExtents[iFaceIdx].min.y;
  46286. var uEnd = filterExtents[iFaceIdx].max.x;
  46287. var vEnd = filterExtents[iFaceIdx].max.y;
  46288. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  46289. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  46290. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  46291. for (var v = vStart; v <= vEnd; v++) {
  46292. var normCubeRowWalk = 0;
  46293. var srcCubeRowWalk = 0;
  46294. for (var u = uStart; u <= uEnd; u++) {
  46295. //pointer to direction in cube map associated with texel
  46296. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  46297. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  46298. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  46299. //check dot product to see if texel is within cone
  46300. var tapDotProd = texelVectX * centerTapDir.x +
  46301. texelVectY * centerTapDir.y +
  46302. texelVectZ * centerTapDir.z;
  46303. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  46304. //solid angle stored in 4th channel of normalizer/solid angle cube map
  46305. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  46306. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  46307. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  46308. // so just adding one to specularpower do the trick.
  46309. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  46310. //iterate over channels
  46311. for (k = 0; k < nSrcChannels; k++) {
  46312. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  46313. srcCubeRowWalk++;
  46314. }
  46315. weightAccum += weight; //accumulate weight
  46316. }
  46317. else {
  46318. //step across source pixel
  46319. srcCubeRowWalk += nSrcChannels;
  46320. }
  46321. normCubeRowWalk += 4; // 4 channels per norm cube map.
  46322. }
  46323. startIndexNormCubeMap += normCubePitch;
  46324. startIndexSrcCubeMap += srcCubePitch;
  46325. }
  46326. }
  46327. }
  46328. //divide through by weights if weight is non zero
  46329. if (weightAccum != 0.0) {
  46330. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  46331. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  46332. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  46333. if (this.numChannels > 3) {
  46334. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  46335. }
  46336. }
  46337. else {
  46338. // otherwise sample nearest
  46339. // get face idx and u, v texel coordinate in face
  46340. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  46341. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  46342. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  46343. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  46344. if (this.numChannels > 3) {
  46345. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  46346. }
  46347. }
  46348. return PMREMGenerator._vectorTemp;
  46349. };
  46350. //--------------------------------------------------------------------------------------
  46351. // Fixup cube edges
  46352. //
  46353. // average texels on cube map faces across the edges
  46354. // WARP/BENT Method Only.
  46355. //--------------------------------------------------------------------------------------
  46356. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  46357. var k;
  46358. var j;
  46359. var i;
  46360. var iFace;
  46361. var iCorner = 0;
  46362. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  46363. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  46364. // note that if functionality to filter across the three texels for each corner, then
  46365. //indexed by corner and face idx. the array contains the face the start points belongs to.
  46366. var cornerPtr = [
  46367. [[], [], []],
  46368. [[], [], []],
  46369. [[], [], []],
  46370. [[], [], []],
  46371. [[], [], []],
  46372. [[], [], []],
  46373. [[], [], []],
  46374. [[], [], []]
  46375. ];
  46376. //if there is no fixup, or fixup width = 0, do nothing
  46377. if (cubeMapSize < 1) {
  46378. return;
  46379. }
  46380. //special case 1x1 cubemap, average face colors
  46381. if (cubeMapSize == 1) {
  46382. //iterate over channels
  46383. for (k = 0; k < this.numChannels; k++) {
  46384. var accum = 0.0;
  46385. //iterate over faces to accumulate face colors
  46386. for (iFace = 0; iFace < 6; iFace++) {
  46387. accum += cubeMap[iFace][k];
  46388. }
  46389. //compute average over 6 face colors
  46390. accum /= 6.0;
  46391. //iterate over faces to distribute face colors
  46392. for (iFace = 0; iFace < 6; iFace++) {
  46393. cubeMap[iFace][k] = accum;
  46394. }
  46395. }
  46396. return;
  46397. }
  46398. //iterate over faces to collect list of corner texel pointers
  46399. for (iFace = 0; iFace < 6; iFace++) {
  46400. //the 4 corner pointers for this face
  46401. faceCornerStartIndicies[0] = [iFace, 0];
  46402. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  46403. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  46404. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  46405. //iterate over face corners to collect cube corner pointers
  46406. for (iCorner = 0; iCorner < 4; iCorner++) {
  46407. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  46408. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  46409. cornerNumPtrs[corner]++;
  46410. }
  46411. }
  46412. //iterate over corners to average across corner tap values
  46413. for (iCorner = 0; iCorner < 8; iCorner++) {
  46414. for (k = 0; k < this.numChannels; k++) {
  46415. var cornerTapAccum = 0.0;
  46416. //iterate over corner texels and average results
  46417. for (i = 0; i < 3; i++) {
  46418. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  46419. }
  46420. //divide by 3 to compute average of corner tap values
  46421. cornerTapAccum *= (1.0 / 3.0);
  46422. //iterate over corner texels and average results
  46423. for (i = 0; i < 3; i++) {
  46424. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  46425. }
  46426. }
  46427. }
  46428. //iterate over the twelve edges of the cube to average across edges
  46429. for (i = 0; i < 12; i++) {
  46430. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  46431. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  46432. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  46433. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  46434. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  46435. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  46436. var edgeWalk = 0;
  46437. var neighborEdgeWalk = 0;
  46438. //Determine walking pointers based on edge type
  46439. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  46440. switch (edge) {
  46441. case PMREMGenerator.CP_EDGE_LEFT:
  46442. // no change to faceEdgeStartPtr
  46443. edgeWalk = this.numChannels * cubeMapSize;
  46444. break;
  46445. case PMREMGenerator.CP_EDGE_RIGHT:
  46446. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46447. edgeWalk = this.numChannels * cubeMapSize;
  46448. break;
  46449. case PMREMGenerator.CP_EDGE_TOP:
  46450. // no change to faceEdgeStartPtr
  46451. edgeWalk = this.numChannels;
  46452. break;
  46453. case PMREMGenerator.CP_EDGE_BOTTOM:
  46454. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46455. edgeWalk = this.numChannels;
  46456. break;
  46457. }
  46458. //For certain types of edge abutments, the neighbor edge walk needs to
  46459. // be flipped: the cases are
  46460. // if a left edge mates with a left or bottom edge on the neighbor
  46461. // if a top edge mates with a top or right edge on the neighbor
  46462. // if a right edge mates with a right or top edge on the neighbor
  46463. // if a bottom edge mates with a bottom or left edge on the neighbor
  46464. //Seeing as the edges are enumerated as follows
  46465. // left =0
  46466. // right =1
  46467. // top =2
  46468. // bottom =3
  46469. //
  46470. //If the edge enums are the same, or the sum of the enums == 3,
  46471. // the neighbor edge walk needs to be flipped
  46472. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  46473. switch (neighborEdge) {
  46474. case PMREMGenerator.CP_EDGE_LEFT:
  46475. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  46476. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46477. break;
  46478. case PMREMGenerator.CP_EDGE_RIGHT:
  46479. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46480. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  46481. break;
  46482. case PMREMGenerator.CP_EDGE_TOP:
  46483. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46484. neighborEdgeWalk = -this.numChannels;
  46485. break;
  46486. case PMREMGenerator.CP_EDGE_BOTTOM:
  46487. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  46488. neighborEdgeWalk = -this.numChannels;
  46489. break;
  46490. }
  46491. }
  46492. else {
  46493. //swapped direction neighbor edge walk
  46494. switch (neighborEdge) {
  46495. case PMREMGenerator.CP_EDGE_LEFT:
  46496. //no change to neighborEdgeStartPtr for this case since it points
  46497. // to the upper left corner already
  46498. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46499. break;
  46500. case PMREMGenerator.CP_EDGE_RIGHT:
  46501. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  46502. neighborEdgeWalk = this.numChannels * cubeMapSize;
  46503. break;
  46504. case PMREMGenerator.CP_EDGE_TOP:
  46505. //no change to neighborEdgeStartPtr for this case since it points
  46506. // to the upper left corner already
  46507. neighborEdgeWalk = this.numChannels;
  46508. break;
  46509. case PMREMGenerator.CP_EDGE_BOTTOM:
  46510. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  46511. neighborEdgeWalk = this.numChannels;
  46512. break;
  46513. }
  46514. }
  46515. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  46516. //nearby neighborhood
  46517. //step ahead one texel on edge
  46518. edgeStartIndex += edgeWalk;
  46519. neighborEdgeStartIndex += neighborEdgeWalk;
  46520. // note that this loop does not process the corner texels, since they have already been
  46521. // averaged across faces across earlier
  46522. for (j = 1; j < (cubeMapSize - 1); j++) {
  46523. //for each set of taps along edge, average them
  46524. // and rewrite the results into the edges
  46525. for (k = 0; k < this.numChannels; k++) {
  46526. var edgeTap = cubeMap[face][edgeStartIndex + k];
  46527. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  46528. //compute average of tap intensity values
  46529. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  46530. //propagate average of taps to edge taps
  46531. cubeMap[face][edgeStartIndex + k] = avgTap;
  46532. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  46533. }
  46534. edgeStartIndex += edgeWalk;
  46535. neighborEdgeStartIndex += neighborEdgeWalk;
  46536. }
  46537. }
  46538. };
  46539. return PMREMGenerator;
  46540. }());
  46541. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  46542. PMREMGenerator.CP_UDIR = 0;
  46543. PMREMGenerator.CP_VDIR = 1;
  46544. PMREMGenerator.CP_FACEAXIS = 2;
  46545. //used to index cube faces
  46546. PMREMGenerator.CP_FACE_X_POS = 0;
  46547. PMREMGenerator.CP_FACE_X_NEG = 1;
  46548. PMREMGenerator.CP_FACE_Y_POS = 2;
  46549. PMREMGenerator.CP_FACE_Y_NEG = 3;
  46550. PMREMGenerator.CP_FACE_Z_POS = 4;
  46551. PMREMGenerator.CP_FACE_Z_NEG = 5;
  46552. //used to index image edges
  46553. // NOTE.. the actual number corresponding to the edge is important
  46554. // do not change these, or the code will break
  46555. //
  46556. // CP_EDGE_LEFT is u = 0
  46557. // CP_EDGE_RIGHT is u = width-1
  46558. // CP_EDGE_TOP is v = 0
  46559. // CP_EDGE_BOTTOM is v = height-1
  46560. PMREMGenerator.CP_EDGE_LEFT = 0;
  46561. PMREMGenerator.CP_EDGE_RIGHT = 1;
  46562. PMREMGenerator.CP_EDGE_TOP = 2;
  46563. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  46564. //corners of CUBE map (P or N specifys if it corresponds to the
  46565. // positive or negative direction each of X, Y, and Z
  46566. PMREMGenerator.CP_CORNER_NNN = 0;
  46567. PMREMGenerator.CP_CORNER_NNP = 1;
  46568. PMREMGenerator.CP_CORNER_NPN = 2;
  46569. PMREMGenerator.CP_CORNER_NPP = 3;
  46570. PMREMGenerator.CP_CORNER_PNN = 4;
  46571. PMREMGenerator.CP_CORNER_PNP = 5;
  46572. PMREMGenerator.CP_CORNER_PPN = 6;
  46573. PMREMGenerator.CP_CORNER_PPP = 7;
  46574. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  46575. //3x2 matrices that map cube map indexing vectors in 3d
  46576. // (after face selection and divide through by the
  46577. // _ABSOLUTE VALUE_ of the max coord)
  46578. // into NVC space
  46579. //Note this currently assumes the D3D cube face ordering and orientation
  46580. PMREMGenerator._sgFace2DMapping = [
  46581. //XPOS face
  46582. [[0, 0, -1],
  46583. [0, -1, 0],
  46584. [1, 0, 0]],
  46585. //XNEG face
  46586. [[0, 0, 1],
  46587. [0, -1, 0],
  46588. [-1, 0, 0]],
  46589. //YPOS face
  46590. [[1, 0, 0],
  46591. [0, 0, 1],
  46592. [0, 1, 0]],
  46593. //YNEG face
  46594. [[1, 0, 0],
  46595. [0, 0, -1],
  46596. [0, -1, 0]],
  46597. //ZPOS face
  46598. [[1, 0, 0],
  46599. [0, -1, 0],
  46600. [0, 0, 1]],
  46601. //ZNEG face
  46602. [[-1, 0, 0],
  46603. [0, -1, 0],
  46604. [0, 0, -1]],
  46605. ];
  46606. //------------------------------------------------------------------------------
  46607. // D3D cube map face specification
  46608. // mapping from 3D x,y,z cube map lookup coordinates
  46609. // to 2D within face u,v coordinates
  46610. //
  46611. // --------------------> U direction
  46612. // | (within-face texture space)
  46613. // | _____
  46614. // | | |
  46615. // | | +Y |
  46616. // | _____|_____|_____ _____
  46617. // | | | | | |
  46618. // | | -X | +Z | +X | -Z |
  46619. // | |_____|_____|_____|_____|
  46620. // | | |
  46621. // | | -Y |
  46622. // | |_____|
  46623. // |
  46624. // v V direction
  46625. // (within-face texture space)
  46626. //------------------------------------------------------------------------------
  46627. //Information about neighbors and how texture coorrdinates change across faces
  46628. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  46629. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  46630. //Note this currently assumes the D3D cube face ordering and orientation
  46631. PMREMGenerator._sgCubeNgh = [
  46632. //XPOS face
  46633. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46634. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46635. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46636. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  46637. //XNEG face
  46638. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46639. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  46640. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  46641. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  46642. //YPOS face
  46643. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46644. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46645. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46646. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  46647. //YNEG face
  46648. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46649. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46650. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46651. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  46652. //ZPOS face
  46653. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46654. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46655. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46656. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  46657. //ZNEG face
  46658. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46659. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46660. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  46661. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  46662. ];
  46663. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  46664. // this table is used to average over the edges.
  46665. PMREMGenerator._sgCubeEdgeList = [
  46666. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  46667. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  46668. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  46669. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46670. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  46671. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  46672. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  46673. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  46674. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  46675. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  46676. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  46677. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  46678. ];
  46679. //Information about which of the 8 cube corners are correspond to the
  46680. // the 4 corners in each cube face
  46681. // the order is upper left, upper right, lower left, lower right
  46682. PMREMGenerator._sgCubeCornerList = [
  46683. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  46684. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  46685. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  46686. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  46687. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  46688. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  46689. ];
  46690. Internals.PMREMGenerator = PMREMGenerator;
  46691. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46692. })(BABYLON || (BABYLON = {}));
  46693. //# sourceMappingURL=babylon.pmremgenerator.js.map
  46694. var BABYLON;
  46695. (function (BABYLON) {
  46696. /**
  46697. * This represents a texture coming from an HDR input.
  46698. *
  46699. * The only supported format is currently panorama picture stored in RGBE format.
  46700. * Example of such files can be found on HDRLib: http://hdrlib.com/
  46701. */
  46702. var HDRCubeTexture = (function (_super) {
  46703. __extends(HDRCubeTexture, _super);
  46704. /**
  46705. * Instantiates an HDRTexture from the following parameters.
  46706. *
  46707. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  46708. * @param scene The scene the texture will be used in
  46709. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  46710. * @param noMipmap Forces to not generate the mipmap if true
  46711. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  46712. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  46713. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  46714. */
  46715. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  46716. if (noMipmap === void 0) { noMipmap = false; }
  46717. if (generateHarmonics === void 0) { generateHarmonics = true; }
  46718. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  46719. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  46720. if (onLoad === void 0) { onLoad = null; }
  46721. if (onError === void 0) { onError = null; }
  46722. var _this = _super.call(this, scene) || this;
  46723. _this._useInGammaSpace = false;
  46724. _this._generateHarmonics = true;
  46725. _this._isBABYLONPreprocessed = false;
  46726. _this._onLoad = null;
  46727. _this._onError = null;
  46728. /**
  46729. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  46730. */
  46731. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  46732. /**
  46733. * The spherical polynomial data extracted from the texture.
  46734. */
  46735. _this.sphericalPolynomial = null;
  46736. /**
  46737. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  46738. * This is usefull at run time to apply the good shader.
  46739. */
  46740. _this.isPMREM = false;
  46741. _this._isBlocking = true;
  46742. if (!url) {
  46743. return _this;
  46744. }
  46745. _this.name = url;
  46746. _this.url = url;
  46747. _this.hasAlpha = false;
  46748. _this.isCube = true;
  46749. _this._textureMatrix = BABYLON.Matrix.Identity();
  46750. _this._onLoad = onLoad;
  46751. _this._onError = onError;
  46752. if (size) {
  46753. _this._isBABYLONPreprocessed = false;
  46754. _this._noMipmap = noMipmap;
  46755. _this._size = size;
  46756. _this._useInGammaSpace = useInGammaSpace;
  46757. _this._usePMREMGenerator = usePMREMGenerator &&
  46758. scene.getEngine().getCaps().textureLOD &&
  46759. _this.getScene().getEngine().getCaps().textureFloat &&
  46760. !_this._useInGammaSpace;
  46761. }
  46762. else {
  46763. _this._isBABYLONPreprocessed = true;
  46764. _this._noMipmap = false;
  46765. _this._useInGammaSpace = false;
  46766. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  46767. _this.getScene().getEngine().getCaps().textureFloat &&
  46768. !_this._useInGammaSpace;
  46769. }
  46770. _this.isPMREM = _this._usePMREMGenerator;
  46771. _this._texture = _this._getFromCache(url, _this._noMipmap);
  46772. if (!_this._texture) {
  46773. if (!scene.useDelayedTextureLoading) {
  46774. _this.loadTexture();
  46775. }
  46776. else {
  46777. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  46778. }
  46779. }
  46780. return _this;
  46781. }
  46782. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  46783. /**
  46784. * Gets wether or not the texture is blocking during loading.
  46785. */
  46786. get: function () {
  46787. return this._isBlocking;
  46788. },
  46789. /**
  46790. * Sets wether or not the texture is blocking during loading.
  46791. */
  46792. set: function (value) {
  46793. this._isBlocking = value;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. /**
  46799. * Occurs when the file is a preprocessed .babylon.hdr file.
  46800. */
  46801. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  46802. var _this = this;
  46803. var mipLevels = 0;
  46804. var floatArrayView = null;
  46805. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  46806. var mips = [];
  46807. var startIndex = 30;
  46808. for (var level = 0; level < mipLevels; level++) {
  46809. mips.push([]);
  46810. // Fill each pixel of the mip level.
  46811. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  46812. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46813. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  46814. mips[level].push(faceData);
  46815. startIndex += faceSize;
  46816. }
  46817. }
  46818. return mips;
  46819. } : null;
  46820. var callback = function (buffer) {
  46821. // Create Native Array Views
  46822. var intArrayView = new Int32Array(buffer);
  46823. floatArrayView = new Float32Array(buffer);
  46824. // Fill header.
  46825. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  46826. _this._size = intArrayView[1]; // CubeMap max mip face size.
  46827. // Update Texture Information.
  46828. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  46829. // Fill polynomial information.
  46830. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  46831. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  46832. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  46833. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  46834. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  46835. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  46836. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  46837. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  46838. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  46839. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  46840. // Fill pixel data.
  46841. mipLevels = intArrayView[29]; // Number of mip levels.
  46842. var startIndex = 30;
  46843. var data = [];
  46844. var faceSize = Math.pow(_this._size, 2) * 3;
  46845. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  46846. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  46847. startIndex += faceSize;
  46848. }
  46849. var results = [];
  46850. var byteArray = null;
  46851. // Push each faces.
  46852. for (var k = 0; k < 6; k++) {
  46853. var dataFace = null;
  46854. // If special cases.
  46855. if (!mipmapGenerator) {
  46856. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  46857. dataFace = data[j];
  46858. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46859. // 3 channels of 1 bytes per pixel in bytes.
  46860. var byteBuffer = new ArrayBuffer(faceSize);
  46861. byteArray = new Uint8Array(byteBuffer);
  46862. }
  46863. for (var i = 0; i < _this._size * _this._size; i++) {
  46864. // Put in gamma space if requested.
  46865. if (_this._useInGammaSpace) {
  46866. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46867. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46868. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46869. }
  46870. // Convert to int texture for fallback.
  46871. if (byteArray) {
  46872. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46873. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46874. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46875. // May use luminance instead if the result is not accurate.
  46876. var max = Math.max(Math.max(r, g), b);
  46877. if (max > 255) {
  46878. var scale = 255 / max;
  46879. r *= scale;
  46880. g *= scale;
  46881. b *= scale;
  46882. }
  46883. byteArray[(i * 3) + 0] = r;
  46884. byteArray[(i * 3) + 1] = g;
  46885. byteArray[(i * 3) + 2] = b;
  46886. }
  46887. }
  46888. }
  46889. else {
  46890. dataFace = data[k];
  46891. }
  46892. // Fill the array accordingly.
  46893. if (byteArray) {
  46894. results.push(byteArray);
  46895. }
  46896. else {
  46897. results.push(dataFace);
  46898. }
  46899. }
  46900. return results;
  46901. };
  46902. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  46903. };
  46904. /**
  46905. * Occurs when the file is raw .hdr file.
  46906. */
  46907. HDRCubeTexture.prototype.loadHDRTexture = function () {
  46908. var _this = this;
  46909. var callback = function (buffer) {
  46910. // Extract the raw linear data.
  46911. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  46912. // Generate harmonics if needed.
  46913. if (_this._generateHarmonics) {
  46914. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  46915. }
  46916. var results = [];
  46917. var byteArray = null;
  46918. // Push each faces.
  46919. for (var j = 0; j < 6; j++) {
  46920. // Create uintarray fallback.
  46921. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  46922. // 3 channels of 1 bytes per pixel in bytes.
  46923. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  46924. byteArray = new Uint8Array(byteBuffer);
  46925. }
  46926. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  46927. // If special cases.
  46928. if (_this._useInGammaSpace || byteArray) {
  46929. for (var i = 0; i < _this._size * _this._size; i++) {
  46930. // Put in gamma space if requested.
  46931. if (_this._useInGammaSpace) {
  46932. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  46933. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  46934. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  46935. }
  46936. // Convert to int texture for fallback.
  46937. if (byteArray) {
  46938. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  46939. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  46940. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  46941. // May use luminance instead if the result is not accurate.
  46942. var max = Math.max(Math.max(r, g), b);
  46943. if (max > 255) {
  46944. var scale = 255 / max;
  46945. r *= scale;
  46946. g *= scale;
  46947. b *= scale;
  46948. }
  46949. byteArray[(i * 3) + 0] = r;
  46950. byteArray[(i * 3) + 1] = g;
  46951. byteArray[(i * 3) + 2] = b;
  46952. }
  46953. }
  46954. }
  46955. if (byteArray) {
  46956. results.push(byteArray);
  46957. }
  46958. else {
  46959. results.push(dataFace);
  46960. }
  46961. }
  46962. return results;
  46963. };
  46964. var mipmapGenerator = null;
  46965. if (!this._noMipmap &&
  46966. this._usePMREMGenerator) {
  46967. mipmapGenerator = function (data) {
  46968. // Custom setup of the generator matching with the PBR shader values.
  46969. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  46970. return generator.filterCubeMap();
  46971. };
  46972. }
  46973. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  46974. };
  46975. /**
  46976. * Starts the loading process of the texture.
  46977. */
  46978. HDRCubeTexture.prototype.loadTexture = function () {
  46979. if (this._isBABYLONPreprocessed) {
  46980. this.loadBabylonTexture();
  46981. }
  46982. else {
  46983. this.loadHDRTexture();
  46984. }
  46985. };
  46986. HDRCubeTexture.prototype.clone = function () {
  46987. var size = this._isBABYLONPreprocessed ? null : this._size;
  46988. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  46989. // Base texture
  46990. newTexture.level = this.level;
  46991. newTexture.wrapU = this.wrapU;
  46992. newTexture.wrapV = this.wrapV;
  46993. newTexture.coordinatesIndex = this.coordinatesIndex;
  46994. newTexture.coordinatesMode = this.coordinatesMode;
  46995. return newTexture;
  46996. };
  46997. // Methods
  46998. HDRCubeTexture.prototype.delayLoad = function () {
  46999. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  47000. return;
  47001. }
  47002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  47003. this._texture = this._getFromCache(this.url, this._noMipmap);
  47004. if (!this._texture) {
  47005. this.loadTexture();
  47006. }
  47007. };
  47008. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  47009. return this._textureMatrix;
  47010. };
  47011. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  47012. var texture = null;
  47013. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  47014. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  47015. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  47016. texture.name = parsedTexture.name;
  47017. texture.hasAlpha = parsedTexture.hasAlpha;
  47018. texture.level = parsedTexture.level;
  47019. texture.coordinatesMode = parsedTexture.coordinatesMode;
  47020. texture.isBlocking = parsedTexture.isBlocking;
  47021. }
  47022. return texture;
  47023. };
  47024. HDRCubeTexture.prototype.serialize = function () {
  47025. if (!this.name) {
  47026. return null;
  47027. }
  47028. var serializationObject = {};
  47029. serializationObject.name = this.name;
  47030. serializationObject.hasAlpha = this.hasAlpha;
  47031. serializationObject.isCube = true;
  47032. serializationObject.level = this.level;
  47033. serializationObject.size = this._size;
  47034. serializationObject.coordinatesMode = this.coordinatesMode;
  47035. serializationObject.useInGammaSpace = this._useInGammaSpace;
  47036. serializationObject.generateHarmonics = this._generateHarmonics;
  47037. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  47038. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  47039. serializationObject.customType = "BABYLON.HDRCubeTexture";
  47040. serializationObject.noMipmap = this._noMipmap;
  47041. serializationObject.isBlocking = this._isBlocking;
  47042. return serializationObject;
  47043. };
  47044. /**
  47045. * Saves as a file the data contained in the texture in a binary format.
  47046. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47047. * as the spherical used in the lighting.
  47048. * @param url The HDR file url.
  47049. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47050. * @param onError Method called if any error happens during download.
  47051. * @return The packed binary data.
  47052. */
  47053. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  47054. if (onError === void 0) { onError = null; }
  47055. var callback = function (buffer) {
  47056. var data = new Blob([buffer], { type: 'application/octet-stream' });
  47057. // Returns a URL you can use as a href.
  47058. var objUrl = window.URL.createObjectURL(data);
  47059. // Simulates a link to it and click to dowload.
  47060. var a = document.createElement("a");
  47061. document.body.appendChild(a);
  47062. a.style.display = "none";
  47063. a.href = objUrl;
  47064. a.download = "envmap.babylon.hdr";
  47065. a.click();
  47066. };
  47067. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  47068. };
  47069. /**
  47070. * Serializes the data contained in the texture in a binary format.
  47071. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  47072. * as the spherical used in the lighting.
  47073. * @param url The HDR file url.
  47074. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  47075. * @param onError Method called if any error happens during download.
  47076. * @return The packed binary data.
  47077. */
  47078. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  47079. if (onError === void 0) { onError = null; }
  47080. // Needs the url tho create the texture.
  47081. if (!url) {
  47082. return null;
  47083. }
  47084. // Check Power of two size.
  47085. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  47086. return null;
  47087. }
  47088. var getDataCallback = function (dataBuffer) {
  47089. // Extract the raw linear data.
  47090. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  47091. // Generate harmonics if needed.
  47092. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  47093. // Generate seamless faces
  47094. var mipGeneratorArray = [];
  47095. // Data are known to be in +X +Y +Z -X -Y -Z
  47096. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  47097. mipGeneratorArray.push(cubeData.right); // +X
  47098. mipGeneratorArray.push(cubeData.left); // -X
  47099. mipGeneratorArray.push(cubeData.up); // +Y
  47100. mipGeneratorArray.push(cubeData.down); // -Y
  47101. mipGeneratorArray.push(cubeData.front); // +Z
  47102. mipGeneratorArray.push(cubeData.back); // -Z
  47103. // Custom setup of the generator matching with the PBR shader values.
  47104. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  47105. var mippedData = generator.filterCubeMap();
  47106. // Compute required byte length.
  47107. var byteLength = 1 * 4; // Raw Data Version int32.
  47108. byteLength += 4; // CubeMap max mip face size int32.
  47109. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  47110. // Add data size.
  47111. byteLength += 4; // Number of mip levels int32.
  47112. for (var level = 0; level < mippedData.length; level++) {
  47113. var mipSize = size >> level;
  47114. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  47115. }
  47116. // Prepare binary structure.
  47117. var buffer = new ArrayBuffer(byteLength);
  47118. var intArrayView = new Int32Array(buffer);
  47119. var floatArrayView = new Float32Array(buffer);
  47120. // Fill header.
  47121. intArrayView[0] = 1; // Version 1.
  47122. intArrayView[1] = size; // CubeMap max mip face size.
  47123. // Fill polynomial information.
  47124. sphericalPolynomial.x.toArray(floatArrayView, 2);
  47125. sphericalPolynomial.y.toArray(floatArrayView, 5);
  47126. sphericalPolynomial.z.toArray(floatArrayView, 8);
  47127. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  47128. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  47129. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  47130. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  47131. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  47132. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  47133. // Fill pixel data.
  47134. intArrayView[29] = mippedData.length; // Number of mip levels.
  47135. var startIndex = 30;
  47136. for (var level = 0; level < mippedData.length; level++) {
  47137. // Fill each pixel of the mip level.
  47138. var faceSize = Math.pow(size >> level, 2) * 3;
  47139. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  47140. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  47141. startIndex += faceSize;
  47142. }
  47143. }
  47144. // Callback.
  47145. callback(buffer);
  47146. };
  47147. // Download and process.
  47148. BABYLON.Tools.LoadFile(url, function (data) {
  47149. getDataCallback(data);
  47150. }, null, null, true, onError);
  47151. };
  47152. return HDRCubeTexture;
  47153. }(BABYLON.BaseTexture));
  47154. HDRCubeTexture._facesMapping = [
  47155. "right",
  47156. "up",
  47157. "front",
  47158. "left",
  47159. "down",
  47160. "back"
  47161. ];
  47162. BABYLON.HDRCubeTexture = HDRCubeTexture;
  47163. })(BABYLON || (BABYLON = {}));
  47164. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  47165. var BABYLON;
  47166. (function (BABYLON) {
  47167. var DefaultLoadingScreen = (function () {
  47168. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47169. if (_loadingText === void 0) { _loadingText = ""; }
  47170. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47171. var _this = this;
  47172. this._renderingCanvas = _renderingCanvas;
  47173. this._loadingText = _loadingText;
  47174. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47175. // Resize
  47176. this._resizeLoadingUI = function () {
  47177. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47178. _this._loadingDiv.style.position = "absolute";
  47179. _this._loadingDiv.style.left = canvasRect.left + "px";
  47180. _this._loadingDiv.style.top = canvasRect.top + "px";
  47181. _this._loadingDiv.style.width = canvasRect.width + "px";
  47182. _this._loadingDiv.style.height = canvasRect.height + "px";
  47183. };
  47184. }
  47185. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47186. if (this._loadingDiv) {
  47187. // Do not add a loading screen if there is already one
  47188. return;
  47189. }
  47190. this._loadingDiv = document.createElement("div");
  47191. this._loadingDiv.id = "babylonjsLoadingDiv";
  47192. this._loadingDiv.style.opacity = "0";
  47193. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47194. // Loading text
  47195. this._loadingTextDiv = document.createElement("div");
  47196. this._loadingTextDiv.style.position = "absolute";
  47197. this._loadingTextDiv.style.left = "0";
  47198. this._loadingTextDiv.style.top = "50%";
  47199. this._loadingTextDiv.style.marginTop = "80px";
  47200. this._loadingTextDiv.style.width = "100%";
  47201. this._loadingTextDiv.style.height = "20px";
  47202. this._loadingTextDiv.style.fontFamily = "Arial";
  47203. this._loadingTextDiv.style.fontSize = "14px";
  47204. this._loadingTextDiv.style.color = "white";
  47205. this._loadingTextDiv.style.textAlign = "center";
  47206. this._loadingTextDiv.innerHTML = "Loading";
  47207. this._loadingDiv.appendChild(this._loadingTextDiv);
  47208. //set the predefined text
  47209. this._loadingTextDiv.innerHTML = this._loadingText;
  47210. // Generating keyframes
  47211. var style = document.createElement('style');
  47212. style.type = 'text/css';
  47213. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  47214. style.innerHTML = keyFrames;
  47215. document.getElementsByTagName('head')[0].appendChild(style);
  47216. // Loading img
  47217. var imgBack = new Image();
  47218. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  47219. imgBack.style.position = "absolute";
  47220. imgBack.style.left = "50%";
  47221. imgBack.style.top = "50%";
  47222. imgBack.style.marginLeft = "-50px";
  47223. imgBack.style.marginTop = "-50px";
  47224. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47225. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47226. imgBack.style.transformOrigin = "50% 50%";
  47227. imgBack.style.webkitTransformOrigin = "50% 50%";
  47228. this._loadingDiv.appendChild(imgBack);
  47229. this._resizeLoadingUI();
  47230. window.addEventListener("resize", this._resizeLoadingUI);
  47231. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47232. document.body.appendChild(this._loadingDiv);
  47233. this._loadingDiv.style.opacity = "1";
  47234. };
  47235. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47236. var _this = this;
  47237. if (!this._loadingDiv) {
  47238. return;
  47239. }
  47240. var onTransitionEnd = function () {
  47241. if (!_this._loadingDiv) {
  47242. return;
  47243. }
  47244. document.body.removeChild(_this._loadingDiv);
  47245. window.removeEventListener("resize", _this._resizeLoadingUI);
  47246. _this._loadingDiv = null;
  47247. };
  47248. this._loadingDiv.style.opacity = "0";
  47249. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47250. };
  47251. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47252. set: function (text) {
  47253. this._loadingText = text;
  47254. if (this._loadingTextDiv) {
  47255. this._loadingTextDiv.innerHTML = this._loadingText;
  47256. }
  47257. },
  47258. enumerable: true,
  47259. configurable: true
  47260. });
  47261. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47262. get: function () {
  47263. return this._loadingDivBackgroundColor;
  47264. },
  47265. set: function (color) {
  47266. this._loadingDivBackgroundColor = color;
  47267. if (!this._loadingDiv) {
  47268. return;
  47269. }
  47270. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47271. },
  47272. enumerable: true,
  47273. configurable: true
  47274. });
  47275. return DefaultLoadingScreen;
  47276. }());
  47277. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47278. })(BABYLON || (BABYLON = {}));
  47279. //# sourceMappingURL=babylon.loadingScreen.js.map
  47280. var BABYLON;
  47281. (function (BABYLON) {
  47282. var SceneLoader = (function () {
  47283. function SceneLoader() {
  47284. }
  47285. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47286. get: function () {
  47287. return 0;
  47288. },
  47289. enumerable: true,
  47290. configurable: true
  47291. });
  47292. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47293. get: function () {
  47294. return 1;
  47295. },
  47296. enumerable: true,
  47297. configurable: true
  47298. });
  47299. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47300. get: function () {
  47301. return 2;
  47302. },
  47303. enumerable: true,
  47304. configurable: true
  47305. });
  47306. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47307. get: function () {
  47308. return 3;
  47309. },
  47310. enumerable: true,
  47311. configurable: true
  47312. });
  47313. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47314. get: function () {
  47315. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47316. },
  47317. set: function (value) {
  47318. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47319. },
  47320. enumerable: true,
  47321. configurable: true
  47322. });
  47323. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47324. get: function () {
  47325. return SceneLoader._ShowLoadingScreen;
  47326. },
  47327. set: function (value) {
  47328. SceneLoader._ShowLoadingScreen = value;
  47329. },
  47330. enumerable: true,
  47331. configurable: true
  47332. });
  47333. Object.defineProperty(SceneLoader, "loggingLevel", {
  47334. get: function () {
  47335. return SceneLoader._loggingLevel;
  47336. },
  47337. set: function (value) {
  47338. SceneLoader._loggingLevel = value;
  47339. },
  47340. enumerable: true,
  47341. configurable: true
  47342. });
  47343. SceneLoader._getDefaultPlugin = function () {
  47344. return SceneLoader._registeredPlugins[".babylon"];
  47345. };
  47346. SceneLoader._getPluginForExtension = function (extension) {
  47347. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47348. if (registeredPlugin) {
  47349. return registeredPlugin;
  47350. }
  47351. return SceneLoader._getDefaultPlugin();
  47352. };
  47353. SceneLoader._getPluginForDirectLoad = function (data) {
  47354. for (var extension in SceneLoader._registeredPlugins) {
  47355. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47356. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47357. return SceneLoader._registeredPlugins[extension];
  47358. }
  47359. }
  47360. return SceneLoader._getDefaultPlugin();
  47361. };
  47362. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47363. if (sceneFilename.name) {
  47364. sceneFilename = sceneFilename.name;
  47365. }
  47366. var dotPosition = sceneFilename.lastIndexOf(".");
  47367. var queryStringPosition = sceneFilename.indexOf("?");
  47368. if (queryStringPosition === -1) {
  47369. queryStringPosition = sceneFilename.length;
  47370. }
  47371. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47372. return SceneLoader._getPluginForExtension(extension);
  47373. };
  47374. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47375. SceneLoader._getDirectLoad = function (sceneFilename) {
  47376. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47377. return sceneFilename.substr(5);
  47378. }
  47379. return null;
  47380. };
  47381. // Public functions
  47382. SceneLoader.GetPluginForExtension = function (extension) {
  47383. return SceneLoader._getPluginForExtension(extension).plugin;
  47384. };
  47385. SceneLoader.RegisterPlugin = function (plugin) {
  47386. if (typeof plugin.extensions === "string") {
  47387. var extension = plugin.extensions;
  47388. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47389. plugin: plugin,
  47390. isBinary: false
  47391. };
  47392. }
  47393. else {
  47394. var extensions = plugin.extensions;
  47395. Object.keys(extensions).forEach(function (extension) {
  47396. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47397. plugin: plugin,
  47398. isBinary: extensions[extension].isBinary
  47399. };
  47400. });
  47401. }
  47402. };
  47403. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47404. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47405. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47406. return;
  47407. }
  47408. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47409. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47410. return;
  47411. }
  47412. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47413. var loadingToken = {};
  47414. scene._addPendingData(loadingToken);
  47415. var manifestChecked = function (success) {
  47416. scene.database = database;
  47417. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(directLoad) : SceneLoader._getPluginForFilename(sceneFilename);
  47418. var plugin = registeredPlugin.plugin;
  47419. var useArrayBuffer = registeredPlugin.isBinary;
  47420. var importMeshFromData = function (data) {
  47421. var meshes = [];
  47422. var particleSystems = [];
  47423. var skeletons = [];
  47424. if (scene.isDisposed) {
  47425. if (onerror) {
  47426. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  47427. }
  47428. return;
  47429. }
  47430. try {
  47431. if (plugin.importMesh) {
  47432. var syncedPlugin = plugin;
  47433. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  47434. if (onerror) {
  47435. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47436. }
  47437. scene._removePendingData(loadingToken);
  47438. return;
  47439. }
  47440. if (onsuccess) {
  47441. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47442. onsuccess(meshes, particleSystems, skeletons);
  47443. scene._removePendingData(loadingToken);
  47444. }
  47445. }
  47446. else {
  47447. var asyncedPlugin = plugin;
  47448. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47449. if (onsuccess) {
  47450. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47451. onsuccess(meshes, particleSystems, skeletons);
  47452. scene._removePendingData(loadingToken);
  47453. }
  47454. }, function () {
  47455. if (onerror) {
  47456. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  47457. }
  47458. scene._removePendingData(loadingToken);
  47459. });
  47460. }
  47461. }
  47462. catch (e) {
  47463. if (onerror) {
  47464. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  47465. }
  47466. scene._removePendingData(loadingToken);
  47467. }
  47468. };
  47469. if (directLoad) {
  47470. importMeshFromData(directLoad);
  47471. return;
  47472. }
  47473. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  47474. importMeshFromData(data);
  47475. }, progressCallBack, database, useArrayBuffer, function () {
  47476. if (onerror) {
  47477. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  47478. }
  47479. });
  47480. };
  47481. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  47482. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47483. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47484. }
  47485. else {
  47486. // If the scene is a data stream or offline support is not enabled, it's a direct load
  47487. manifestChecked(true);
  47488. }
  47489. };
  47490. /**
  47491. * Load a scene
  47492. * @param rootUrl a string that defines the root url for scene and resources
  47493. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47494. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47495. */
  47496. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  47497. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  47498. };
  47499. /**
  47500. * Append a scene
  47501. * @param rootUrl a string that defines the root url for scene and resources
  47502. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47503. * @param scene is the instance of BABYLON.Scene to append to
  47504. */
  47505. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  47506. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47507. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47508. return;
  47509. }
  47510. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47511. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47512. var plugin = registeredPlugin.plugin;
  47513. var useArrayBuffer = registeredPlugin.isBinary;
  47514. var database;
  47515. var loadingToken = {};
  47516. scene._addPendingData(loadingToken);
  47517. if (SceneLoader.ShowLoadingScreen) {
  47518. scene.getEngine().displayLoadingUI();
  47519. }
  47520. var loadSceneFromData = function (data) {
  47521. scene.database = database;
  47522. if (plugin.load) {
  47523. var syncedPlugin = plugin;
  47524. if (!syncedPlugin.load(scene, data, rootUrl)) {
  47525. if (onerror) {
  47526. onerror(scene);
  47527. }
  47528. scene._removePendingData(loadingToken);
  47529. scene.getEngine().hideLoadingUI();
  47530. return;
  47531. }
  47532. if (onsuccess) {
  47533. onsuccess(scene);
  47534. }
  47535. scene._removePendingData(loadingToken);
  47536. }
  47537. else {
  47538. var asyncedPlugin = plugin;
  47539. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47540. if (onsuccess) {
  47541. onsuccess(scene);
  47542. }
  47543. scene._removePendingData(loadingToken);
  47544. }, function () {
  47545. if (onerror) {
  47546. onerror(scene);
  47547. }
  47548. scene._removePendingData(loadingToken);
  47549. scene.getEngine().hideLoadingUI();
  47550. });
  47551. }
  47552. if (SceneLoader.ShowLoadingScreen) {
  47553. scene.executeWhenReady(function () {
  47554. scene.getEngine().hideLoadingUI();
  47555. });
  47556. }
  47557. };
  47558. var manifestChecked = function (success) {
  47559. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  47560. };
  47561. if (directLoad) {
  47562. loadSceneFromData(directLoad);
  47563. return;
  47564. }
  47565. if (rootUrl.indexOf("file:") === -1) {
  47566. if (scene.getEngine().enableOfflineSupport) {
  47567. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47568. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47569. }
  47570. else {
  47571. manifestChecked(true);
  47572. }
  47573. }
  47574. else {
  47575. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  47576. }
  47577. };
  47578. return SceneLoader;
  47579. }());
  47580. // Flags
  47581. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47582. SceneLoader._ShowLoadingScreen = true;
  47583. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47584. // Members
  47585. SceneLoader._registeredPlugins = {};
  47586. BABYLON.SceneLoader = SceneLoader;
  47587. ;
  47588. })(BABYLON || (BABYLON = {}));
  47589. //# sourceMappingURL=babylon.sceneLoader.js.map
  47590. var BABYLON;
  47591. (function (BABYLON) {
  47592. var Internals;
  47593. (function (Internals) {
  47594. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47595. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47596. var parsedMaterial = parsedData.materials[index];
  47597. if (parsedMaterial.id === id) {
  47598. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47599. }
  47600. }
  47601. return null;
  47602. };
  47603. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47604. names = (names instanceof Array) ? names : [names];
  47605. for (var i in names) {
  47606. if (mesh.name === names[i]) {
  47607. hierarchyIds.push(mesh.id);
  47608. return true;
  47609. }
  47610. }
  47611. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47612. hierarchyIds.push(mesh.id);
  47613. return true;
  47614. }
  47615. return false;
  47616. };
  47617. var logOperation = function (operation, producer) {
  47618. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47619. };
  47620. BABYLON.SceneLoader.RegisterPlugin({
  47621. extensions: ".babylon",
  47622. canDirectLoad: function (data) {
  47623. if (data.indexOf("babylon") !== -1) {
  47624. return true;
  47625. }
  47626. return false;
  47627. },
  47628. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47629. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47630. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47631. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47632. // and avoid problems with multiple concurrent .babylon loads.
  47633. var log = "importMesh has failed JSON parse";
  47634. try {
  47635. var parsedData = JSON.parse(data);
  47636. log = "";
  47637. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47638. var loadedSkeletonsIds = [];
  47639. var loadedMaterialsIds = [];
  47640. var hierarchyIds = [];
  47641. var index;
  47642. var cache;
  47643. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47644. var parsedMesh = parsedData.meshes[index];
  47645. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47646. if (meshesNames instanceof Array) {
  47647. // Remove found mesh name from list.
  47648. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47649. }
  47650. //Geometry?
  47651. if (parsedMesh.geometryId) {
  47652. //does the file contain geometries?
  47653. if (parsedData.geometries) {
  47654. //find the correct geometry and add it to the scene
  47655. var found = false;
  47656. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47657. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  47658. return;
  47659. }
  47660. else {
  47661. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47662. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47663. switch (geometryType) {
  47664. case "boxes":
  47665. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47666. break;
  47667. case "spheres":
  47668. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47669. break;
  47670. case "cylinders":
  47671. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47672. break;
  47673. case "toruses":
  47674. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47675. break;
  47676. case "grounds":
  47677. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47678. break;
  47679. case "planes":
  47680. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47681. break;
  47682. case "torusKnots":
  47683. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47684. break;
  47685. case "vertexData":
  47686. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47687. break;
  47688. }
  47689. found = true;
  47690. }
  47691. });
  47692. }
  47693. });
  47694. if (!found) {
  47695. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47696. }
  47697. }
  47698. }
  47699. // Material ?
  47700. if (parsedMesh.materialId) {
  47701. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47702. if (!materialFound && parsedData.multiMaterials) {
  47703. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47704. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47705. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47706. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47707. var subMatId = parsedMultiMaterial.materials[matIndex];
  47708. loadedMaterialsIds.push(subMatId);
  47709. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47710. log += "\n\tMaterial " + mat.toString(fullDetails);
  47711. }
  47712. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47713. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47714. materialFound = true;
  47715. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47716. break;
  47717. }
  47718. }
  47719. }
  47720. if (!materialFound) {
  47721. loadedMaterialsIds.push(parsedMesh.materialId);
  47722. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47723. if (!mat) {
  47724. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47725. }
  47726. else {
  47727. log += "\n\tMaterial " + mat.toString(fullDetails);
  47728. }
  47729. }
  47730. }
  47731. // Skeleton ?
  47732. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  47733. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47734. if (!skeletonAlreadyLoaded) {
  47735. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47736. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47737. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47738. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47739. skeletons.push(skeleton);
  47740. loadedSkeletonsIds.push(parsedSkeleton.id);
  47741. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47742. }
  47743. }
  47744. }
  47745. }
  47746. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47747. meshes.push(mesh);
  47748. log += "\n\tMesh " + mesh.toString(fullDetails);
  47749. }
  47750. }
  47751. // Connecting parents
  47752. var currentMesh;
  47753. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47754. currentMesh = scene.meshes[index];
  47755. if (currentMesh._waitingParentId) {
  47756. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47757. currentMesh._waitingParentId = undefined;
  47758. }
  47759. }
  47760. // freeze and compute world matrix application
  47761. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47762. currentMesh = scene.meshes[index];
  47763. if (currentMesh._waitingFreezeWorldMatrix) {
  47764. currentMesh.freezeWorldMatrix();
  47765. currentMesh._waitingFreezeWorldMatrix = undefined;
  47766. }
  47767. else {
  47768. currentMesh.computeWorldMatrix(true);
  47769. }
  47770. }
  47771. // Particles
  47772. if (parsedData.particleSystems) {
  47773. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47774. var parsedParticleSystem = parsedData.particleSystems[index];
  47775. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47776. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  47777. }
  47778. }
  47779. }
  47780. return true;
  47781. }
  47782. catch (err) {
  47783. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  47784. log = null;
  47785. throw err;
  47786. }
  47787. finally {
  47788. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  47789. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  47790. }
  47791. }
  47792. },
  47793. load: function (scene, data, rootUrl) {
  47794. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47795. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47796. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47797. // and avoid problems with multiple concurrent .babylon loads.
  47798. var log = "importScene has failed JSON parse";
  47799. try {
  47800. var parsedData = JSON.parse(data);
  47801. log = "";
  47802. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47803. // Scene
  47804. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  47805. scene.autoClear = parsedData.autoClear;
  47806. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  47807. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  47808. if (parsedData.gravity) {
  47809. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  47810. }
  47811. // Fog
  47812. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  47813. scene.fogMode = parsedData.fogMode;
  47814. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  47815. scene.fogStart = parsedData.fogStart;
  47816. scene.fogEnd = parsedData.fogEnd;
  47817. scene.fogDensity = parsedData.fogDensity;
  47818. log += "\tFog mode for scene: ";
  47819. switch (scene.fogMode) {
  47820. // getters not compiling, so using hardcoded
  47821. case 1:
  47822. log += "exp\n";
  47823. break;
  47824. case 2:
  47825. log += "exp2\n";
  47826. break;
  47827. case 3:
  47828. log += "linear\n";
  47829. break;
  47830. }
  47831. }
  47832. //Physics
  47833. if (parsedData.physicsEnabled) {
  47834. var physicsPlugin;
  47835. if (parsedData.physicsEngine === "cannon") {
  47836. physicsPlugin = new BABYLON.CannonJSPlugin();
  47837. }
  47838. else if (parsedData.physicsEngine === "oimo") {
  47839. physicsPlugin = new BABYLON.OimoJSPlugin();
  47840. }
  47841. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  47842. //else - default engine, which is currently oimo
  47843. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  47844. scene.enablePhysics(physicsGravity, physicsPlugin);
  47845. }
  47846. // Metadata
  47847. if (parsedData.metadata !== undefined) {
  47848. scene.metadata = parsedData.metadata;
  47849. }
  47850. //collisions, if defined. otherwise, default is true
  47851. if (parsedData.collisionsEnabled != undefined) {
  47852. scene.collisionsEnabled = parsedData.collisionsEnabled;
  47853. }
  47854. scene.workerCollisions = !!parsedData.workerCollisions;
  47855. var index;
  47856. var cache;
  47857. // Lights
  47858. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  47859. var parsedLight = parsedData.lights[index];
  47860. var light = BABYLON.Light.Parse(parsedLight, scene);
  47861. log += (index === 0 ? "\n\tLights:" : "");
  47862. log += "\n\t\t" + light.toString(fullDetails);
  47863. }
  47864. // Animations
  47865. if (parsedData.animations) {
  47866. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  47867. var parsedAnimation = parsedData.animations[index];
  47868. var animation = BABYLON.Animation.Parse(parsedAnimation);
  47869. scene.animations.push(animation);
  47870. log += (index === 0 ? "\n\tAnimations:" : "");
  47871. log += "\n\t\t" + animation.toString(fullDetails);
  47872. }
  47873. }
  47874. if (parsedData.autoAnimate) {
  47875. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  47876. }
  47877. // Materials
  47878. if (parsedData.materials) {
  47879. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47880. var parsedMaterial = parsedData.materials[index];
  47881. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47882. log += (index === 0 ? "\n\tMaterials:" : "");
  47883. log += "\n\t\t" + mat.toString(fullDetails);
  47884. }
  47885. }
  47886. if (parsedData.multiMaterials) {
  47887. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  47888. var parsedMultiMaterial = parsedData.multiMaterials[index];
  47889. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47890. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  47891. log += "\n\t\t" + mmat.toString(fullDetails);
  47892. }
  47893. }
  47894. // Morph targets
  47895. if (parsedData.morphTargetManagers) {
  47896. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  47897. var managerData = _a[_i];
  47898. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  47899. }
  47900. }
  47901. // Skeletons
  47902. if (parsedData.skeletons) {
  47903. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  47904. var parsedSkeleton = parsedData.skeletons[index];
  47905. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47906. log += (index === 0 ? "\n\tSkeletons:" : "");
  47907. log += "\n\t\t" + skeleton.toString(fullDetails);
  47908. }
  47909. }
  47910. // Geometries
  47911. var geometries = parsedData.geometries;
  47912. if (geometries) {
  47913. // Boxes
  47914. var boxes = geometries.boxes;
  47915. if (boxes) {
  47916. for (index = 0, cache = boxes.length; index < cache; index++) {
  47917. var parsedBox = boxes[index];
  47918. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  47919. }
  47920. }
  47921. // Spheres
  47922. var spheres = geometries.spheres;
  47923. if (spheres) {
  47924. for (index = 0, cache = spheres.length; index < cache; index++) {
  47925. var parsedSphere = spheres[index];
  47926. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  47927. }
  47928. }
  47929. // Cylinders
  47930. var cylinders = geometries.cylinders;
  47931. if (cylinders) {
  47932. for (index = 0, cache = cylinders.length; index < cache; index++) {
  47933. var parsedCylinder = cylinders[index];
  47934. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  47935. }
  47936. }
  47937. // Toruses
  47938. var toruses = geometries.toruses;
  47939. if (toruses) {
  47940. for (index = 0, cache = toruses.length; index < cache; index++) {
  47941. var parsedTorus = toruses[index];
  47942. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  47943. }
  47944. }
  47945. // Grounds
  47946. var grounds = geometries.grounds;
  47947. if (grounds) {
  47948. for (index = 0, cache = grounds.length; index < cache; index++) {
  47949. var parsedGround = grounds[index];
  47950. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  47951. }
  47952. }
  47953. // Planes
  47954. var planes = geometries.planes;
  47955. if (planes) {
  47956. for (index = 0, cache = planes.length; index < cache; index++) {
  47957. var parsedPlane = planes[index];
  47958. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  47959. }
  47960. }
  47961. // TorusKnots
  47962. var torusKnots = geometries.torusKnots;
  47963. if (torusKnots) {
  47964. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  47965. var parsedTorusKnot = torusKnots[index];
  47966. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  47967. }
  47968. }
  47969. // VertexData
  47970. var vertexData = geometries.vertexData;
  47971. if (vertexData) {
  47972. for (index = 0, cache = vertexData.length; index < cache; index++) {
  47973. var parsedVertexData = vertexData[index];
  47974. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  47975. }
  47976. }
  47977. }
  47978. // Meshes
  47979. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47980. var parsedMesh = parsedData.meshes[index];
  47981. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47982. log += (index === 0 ? "\n\tMeshes:" : "");
  47983. log += "\n\t\t" + mesh.toString(fullDetails);
  47984. }
  47985. // Cameras
  47986. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  47987. var parsedCamera = parsedData.cameras[index];
  47988. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  47989. log += (index === 0 ? "\n\tCameras:" : "");
  47990. log += "\n\t\t" + camera.toString(fullDetails);
  47991. }
  47992. if (parsedData.activeCameraID) {
  47993. scene.setActiveCameraByID(parsedData.activeCameraID);
  47994. }
  47995. // Browsing all the graph to connect the dots
  47996. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  47997. var camera = scene.cameras[index];
  47998. if (camera._waitingParentId) {
  47999. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48000. camera._waitingParentId = undefined;
  48001. }
  48002. }
  48003. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48004. var light = scene.lights[index];
  48005. if (light._waitingParentId) {
  48006. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48007. light._waitingParentId = undefined;
  48008. }
  48009. }
  48010. // Sounds
  48011. var loadedSounds = [];
  48012. var loadedSound;
  48013. if (BABYLON.AudioEngine && parsedData.sounds) {
  48014. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48015. var parsedSound = parsedData.sounds[index];
  48016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48017. if (!parsedSound.url)
  48018. parsedSound.url = parsedSound.name;
  48019. if (!loadedSounds[parsedSound.url]) {
  48020. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48021. loadedSounds[parsedSound.url] = loadedSound;
  48022. }
  48023. else {
  48024. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48025. }
  48026. }
  48027. else {
  48028. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48029. }
  48030. }
  48031. }
  48032. loadedSounds = [];
  48033. // Connect parents & children and parse actions
  48034. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48035. var mesh = scene.meshes[index];
  48036. if (mesh._waitingParentId) {
  48037. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48038. mesh._waitingParentId = undefined;
  48039. }
  48040. if (mesh._waitingActions) {
  48041. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48042. mesh._waitingActions = undefined;
  48043. }
  48044. }
  48045. // freeze world matrix application
  48046. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48047. var currentMesh = scene.meshes[index];
  48048. if (currentMesh._waitingFreezeWorldMatrix) {
  48049. currentMesh.freezeWorldMatrix();
  48050. currentMesh._waitingFreezeWorldMatrix = undefined;
  48051. }
  48052. else {
  48053. currentMesh.computeWorldMatrix(true);
  48054. }
  48055. }
  48056. // Particles Systems
  48057. if (parsedData.particleSystems) {
  48058. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48059. var parsedParticleSystem = parsedData.particleSystems[index];
  48060. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48061. }
  48062. }
  48063. // Lens flares
  48064. if (parsedData.lensFlareSystems) {
  48065. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48066. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48067. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48068. }
  48069. }
  48070. // Shadows
  48071. if (parsedData.shadowGenerators) {
  48072. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48073. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48074. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48075. }
  48076. }
  48077. // Lights exclusions / inclusions
  48078. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48079. var light = scene.lights[index];
  48080. // Excluded check
  48081. if (light._excludedMeshesIds.length > 0) {
  48082. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48083. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48084. if (excludedMesh) {
  48085. light.excludedMeshes.push(excludedMesh);
  48086. }
  48087. }
  48088. light._excludedMeshesIds = [];
  48089. }
  48090. // Included check
  48091. if (light._includedOnlyMeshesIds.length > 0) {
  48092. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48093. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48094. if (includedOnlyMesh) {
  48095. light.includedOnlyMeshes.push(includedOnlyMesh);
  48096. }
  48097. }
  48098. light._includedOnlyMeshesIds = [];
  48099. }
  48100. }
  48101. // Actions (scene)
  48102. if (parsedData.actions) {
  48103. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48104. }
  48105. // Finish
  48106. return true;
  48107. }
  48108. catch (err) {
  48109. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48110. log = null;
  48111. throw err;
  48112. }
  48113. finally {
  48114. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48115. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48116. }
  48117. }
  48118. }
  48119. });
  48120. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48121. })(BABYLON || (BABYLON = {}));
  48122. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48123. var BABYLON;
  48124. (function (BABYLON) {
  48125. var FilesInput = (function () {
  48126. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  48127. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  48128. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  48129. this._engine = p_engine;
  48130. this._canvas = p_canvas;
  48131. this._currentScene = p_scene;
  48132. this._sceneLoadedCallback = p_sceneLoadedCallback;
  48133. this._progressCallback = p_progressCallback;
  48134. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  48135. this._textureLoadingCallback = p_textureLoadingCallback;
  48136. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  48137. }
  48138. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  48139. var _this = this;
  48140. if (p_elementToMonitor) {
  48141. this._elementToMonitor = p_elementToMonitor;
  48142. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  48143. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  48144. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  48145. }
  48146. };
  48147. FilesInput.prototype.renderFunction = function () {
  48148. if (this._additionnalRenderLoopLogicCallback) {
  48149. this._additionnalRenderLoopLogicCallback();
  48150. }
  48151. if (this._currentScene) {
  48152. if (this._textureLoadingCallback) {
  48153. var remaining = this._currentScene.getWaitingItemsCount();
  48154. if (remaining > 0) {
  48155. this._textureLoadingCallback(remaining);
  48156. }
  48157. }
  48158. this._currentScene.render();
  48159. }
  48160. };
  48161. FilesInput.prototype.drag = function (e) {
  48162. e.stopPropagation();
  48163. e.preventDefault();
  48164. };
  48165. FilesInput.prototype.drop = function (eventDrop) {
  48166. eventDrop.stopPropagation();
  48167. eventDrop.preventDefault();
  48168. this.loadFiles(eventDrop);
  48169. };
  48170. FilesInput.prototype.loadFiles = function (event) {
  48171. if (this._startingProcessingFilesCallback)
  48172. this._startingProcessingFilesCallback();
  48173. // Handling data transfer via drag'n'drop
  48174. if (event && event.dataTransfer && event.dataTransfer.files) {
  48175. this._filesToLoad = event.dataTransfer.files;
  48176. }
  48177. // Handling files from input files
  48178. if (event && event.target && event.target.files) {
  48179. this._filesToLoad = event.target.files;
  48180. }
  48181. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48182. for (var i = 0; i < this._filesToLoad.length; i++) {
  48183. var name_1 = this._filesToLoad[i].name.toLowerCase();
  48184. var extension = name_1.split('.').pop();
  48185. var type = this._filesToLoad[i].type;
  48186. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48187. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  48188. this._sceneFileToLoad = this._filesToLoad[i];
  48189. }
  48190. else {
  48191. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  48192. }
  48193. }
  48194. this.reload();
  48195. }
  48196. };
  48197. FilesInput.prototype.reload = function () {
  48198. var _this = this;
  48199. var that = this;
  48200. // If a ".babylon" file has been provided
  48201. if (this._sceneFileToLoad) {
  48202. if (this._currentScene) {
  48203. if (BABYLON.Tools.errorsCount > 0) {
  48204. BABYLON.Tools.ClearLogCache();
  48205. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48206. }
  48207. this._engine.stopRenderLoop();
  48208. this._currentScene.dispose();
  48209. }
  48210. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48211. that._currentScene = newScene;
  48212. // Wait for textures and shaders to be ready
  48213. that._currentScene.executeWhenReady(function () {
  48214. if (that._sceneLoadedCallback) {
  48215. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  48216. }
  48217. that._engine.runRenderLoop(function () { that.renderFunction(); });
  48218. });
  48219. }, function (progress) {
  48220. if (_this._progressCallback) {
  48221. _this._progressCallback(progress);
  48222. }
  48223. });
  48224. }
  48225. else {
  48226. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48227. }
  48228. };
  48229. return FilesInput;
  48230. }());
  48231. FilesInput.FilesToLoad = new Array();
  48232. BABYLON.FilesInput = FilesInput;
  48233. })(BABYLON || (BABYLON = {}));
  48234. //# sourceMappingURL=babylon.filesInput.js.map
  48235. BABYLON.Effect.ShadersStore={"postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(V,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n\n#ifdef REFRACTION\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n\n\n\nfloat NdotV=clamp(dot(normalW,viewDirectionW),0.,1.)+0.00001;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular*=surfaceReflectivityColor;\nfinalSpecular=max(finalSpecular,0.0);\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=surfaceRefractionColor;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\nfinalSpecular*vLightingIntensity.x*vLightingIntensity.w +\n#endif\n#ifdef REFLECTION\nfinalRadiance*vLightingIntensity.z +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=result.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}"};
  48236. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec3 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\n\n\n\n\n\nreturn esm;\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nclipSpace=0.5*clipSpace+vec3(0.5);\nvec2 uv=clipSpace.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\n\n\n\n\n\nreturn esm;\n}\n#endif\n","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  48237. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  48238. module.exports = BABYLON;
  48239. };